Skip to content
Verified contractExact--

ReferralHubReader

Address0xab91590fe31c0e800454b2f2ba3d4e3a355d3113
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.36

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.36+commit.8a079791
Language
solidity
Optimization
Yes, 600,000 runs
EVM version
cancun
License
--
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,409,541
Creation transaction
0x11f4e111a7…4230964843

src/hub/ReferralHubReader.sol

// SPDX-License-Identifier: -- WISE --

pragma solidity =0.8.36;

import {IReferralHub} from "./IReferralHub.sol";
import {ReferralHubDeclarations} from "./ReferralHubDeclarations.sol";
import {CohortWeeks} from "../diamond/shared/CohortWeeks.sol";

/**
 * @dev ReferralHubReader: a stateless read companion of the hub, built
 * only from its primitive getters, so it can be redeployed at any time. It
 * batches the week bucket reads (a referrer's ladder inputs per week and a
 * source's reported referred average and paid units per week), the paid
 * cursors, the claimables and the weekly rates, and serves two account
 * views for a dashboard: one referrer's claimables over several source
 * chains with the payout address each would pay, and one referrer's
 * standing on the ladder of a week (both inputs, the tier each reaches,
 * the next threshold of each and the rates). The tier walk mirrors the
 * hub's rate computation over the same table the hub picks for the week.
 */
contract ReferralHubReader {

    IReferralHub public immutable HUB;

    error ZeroAddress();

    struct LadderStanding {
        uint256 referredInput;
        uint256 selfInput;
        uint256 referredTierBps;
        uint256 selfTierBps;
        uint256 nextReferredThreshold;
        uint256 nextSelfThreshold;
        uint256 y1Bps;
        uint256 y2Bps;
        uint256 mBps;
        uint256 elevatedFromWeek;
        uint256 elevatedUntilWeek;
        bool elevated;
    }

    constructor(
        address _hub
    ) {
        require(
            _hub != address(0),
            ZeroAddress()
        );

        HUB = IReferralHub(
            _hub
        );
    }

    function ladderInputsRange(
        address _referrer,
        uint256 _fromWeek,
        uint256 _count
    )
        external
        view
        returns (
            uint256[] memory referredInputs,
            uint256[] memory selfInputs
        )
    {
        referredInputs = new uint256[](
            _count
        );

        selfInputs = new uint256[](
            _count
        );

        for (uint256 i; i < _count; ++i) {
            (
                referredInputs[i],
                selfInputs[i]
            ) = HUB.ladderInputsAt(
                _referrer,
                _fromWeek + i
            );
        }
    }

    function weekReportsAtSource(
        bytes32 _source,
        address _referrer,
        uint256 _fromWeek,
        uint256 _count
    )
        external
        view
        returns (
            uint256[] memory referredAverages,
            uint256[] memory paidUnits
        )
    {
        referredAverages = new uint256[](
            _count
        );

        paidUnits = new uint256[](
            _count
        );

        for (uint256 i; i < _count; ++i) {
            (
                referredAverages[i],
                paidUnits[i]
            ) = HUB.weekReportOf(
                _source,
                _referrer,
                _fromWeek + i
            );
        }
    }

    function paidCursorAt(
        address _reporter,
        address _referrer,
        uint256 _week
    )
        external
        view
        returns (
            uint256 y1Cursor,
            uint256 y2Cursor,
            uint256 mCursor
        )
    {
        return HUB.paidCursorAtSource(
            HUB.sourceKeyOf(
                block.chainid,
                _reporter
            ),
            _referrer,
            _week
        );
    }

    function paidCursorsAtSource(
        bytes32 _source,
        address _referrer,
        uint256 _fromWeek,
        uint256 _count
    )
        external
        view
        returns (uint256[] memory cursorWords)
    {
        cursorWords = new uint256[](
            _count
        );

        for (uint256 i; i < _count; ++i) {

            (
                uint256 y1Cursor,
                uint256 y2Cursor,
                uint256 mCursor
            ) = HUB.paidCursorAtSource(
                _source,
                _referrer,
                _fromWeek + i
            );

            cursorWords[i] = CohortWeeks._packLanes(
                y1Cursor,
                y2Cursor,
                mCursor
            );
        }
    }

    function claimableOf(
        uint256 _chainId,
        address[] calldata _referrers
    )
        external
        view
        returns (uint256[] memory amounts)
    {
        amounts = new uint256[](
            _referrers.length
        );

        for (uint256 i; i < _referrers.length; ++i) {
            amounts[i] = HUB.claimable(
                _chainId,
                _referrers[i]
            );
        }
    }

    function weeklyRatesRange(
        address _referrer,
        uint256 _fromWeek,
        uint256 _count
    )
        external
        view
        returns (
            uint256[] memory y1Bps,
            uint256[] memory y2Bps,
            uint256[] memory mBps
        )
    {
        y1Bps = new uint256[](
            _count
        );

        y2Bps = new uint256[](
            _count
        );

        mBps = new uint256[](
            _count
        );

        for (uint256 i; i < _count; ++i) {
            (
                y1Bps[i],
                y2Bps[i],
                mBps[i]
            ) = HUB.weeklyRates(
                _referrer,
                _fromWeek + i
            );
        }
    }

    /**
     * @dev Per source chain id: the claimable amount and the address a
     * claim would pay, the owner itself until a designation from that
     * chain redirected it. `total` sums every amount and `claimableNow`
     * equals it, kept in the answer from the time an undesignated spoke
     * bucket could not pay; both are before the payout pool's funding.
     */
    function claimablesOf(
        address _referrer,
        uint256[] calldata _chainIds
    )
        external
        view
        returns (
            uint256[] memory amounts,
            address[] memory payouts,
            uint256 total,
            uint256 claimableNow
        )
    {
        amounts = new uint256[](
            _chainIds.length
        );

        payouts = new address[](
            _chainIds.length
        );

        for (uint256 i; i < _chainIds.length; ++i) {
            amounts[i] = HUB.claimable(
                _chainIds[i],
                _referrer
            );

            payouts[i] = HUB.payoutAddressOf(
                _chainIds[i],
                _referrer
            );

            total += amounts[i];
        }

        claimableNow = total;
    }

    /**
     * @dev A week's inputs are its sources' reports for that closed week,
     * so the current week reads zero until it closes and reports land. A
     * next threshold of zero means the input sits on the top tier. The
     * tiers are the natural ones; `elevated` says whether the week is
     * priced as at the cap instead (the rates reported are the effective
     * ones), with the hub's latest window beside it. A week the latest
     * window holds is elevated; so is a week of an earlier window of the
     * referrer's history, read from its effective rate standing at the cap
     * while the natural ladder does not reach it (a week whose ladder
     * reaches the cap on its own is priced the same either way).
     */
    function ladderStandingOf(
        address _referrer,
        uint256 _week
    )
        external
        view
        returns (LadderStanding memory standing)
    {
        (
            standing.referredInput,
            standing.selfInput
        ) = HUB.ladderInputsAt(
            _referrer,
            _week
        );

        (
            standing.y1Bps,
            standing.y2Bps,
            standing.mBps
        ) = HUB.weeklyRates(
            _referrer,
            _week
        );

        ReferralHubDeclarations.RateTable memory table = _tableFor(
            _week
        );

        (
            standing.referredTierBps,
            standing.nextReferredThreshold
        ) = _tierOf(
            table,
            standing.referredInput
        );

        (
            standing.selfTierBps,
            standing.nextSelfThreshold
        ) = _tierOf(
            table,
            standing.selfInput
        );

        standing.elevatedFromWeek = HUB.elevatedFromWeek(
            _referrer
        );

        standing.elevatedUntilWeek = HUB.elevatedUntilWeek(
            _referrer
        );

        standing.elevated = (
            standing.elevatedFromWeek != 0
                && _week >= standing.elevatedFromWeek
                && (standing.elevatedUntilWeek == 0 || _week < standing.elevatedUntilWeek)
        ) || (
            standing.y1Bps == table.capBps
                && standing.referredTierBps + standing.selfTierBps < table.capBps
        );
    }

    function _tableFor(
        uint256 _week
    )
        internal
        view
        returns (ReferralHubDeclarations.RateTable memory table)
    {
        uint256 index = HUB.rateTableCount();

        while (index > 1) {
            --index;

            table = HUB.rateTableAt(
                index
            );

            if (table.effectiveFromWeek <= _week) {
                return table;
            }
        }

        return HUB.rateTableAt(
            0
        );
    }

    function _tierOf(
        ReferralHubDeclarations.RateTable memory _table,
        uint256 _value
    )
        internal
        pure
        returns (
            uint256 tierBps,
            uint256 nextThreshold
        )
    {
        for (uint256 i = 8; i > 0; --i) {

            if (_value >= _table.thresholds[i - 1]) {

                if (i < 8) {
                    nextThreshold = _table.thresholds[i];
                }

                return (
                    _table.tierBps[i - 1],
                    nextThreshold
                );
            }
        }

        nextThreshold = _table.thresholds[0];
    }
}

node_modules/@chainlink/contracts-ccip/contracts/libraries/Client.sol

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

// End consumer library.
library Client {
  /// @dev RMN depends on this struct, if changing, please notify the RMN maintainers.
  struct EVMTokenAmount {
    address token; // token address on the local chain.
    uint256 amount; // Amount of tokens.
  }

  struct Any2EVMMessage {
    bytes32 messageId; // MessageId corresponding to ccipSend on source.
    uint64 sourceChainSelector; // Source chain selector.
    bytes sender; // abi.decode(sender) if coming from an EVM chain.
    bytes data; // payload sent in original message.
    EVMTokenAmount[] destTokenAmounts; // Tokens and their amounts in their destination chain representation.
  }

  // If extraArgs is empty bytes, the default is 200k gas limit.
  struct EVM2AnyMessage {
    bytes receiver; // abi.encode(receiver address) for dest EVM chains.
    bytes data; // Data payload.
    EVMTokenAmount[] tokenAmounts; // Token transfers.
    address feeToken; // Address of feeToken. address(0) means you will send msg.value.
    bytes extraArgs; // Populate this with _argsToBytes(EVMExtraArgsV2).
  }

  // Tag to indicate only a gas limit. Only usable for EVM as destination chain.
  bytes4 public constant EVM_EXTRA_ARGS_V1_TAG = 0x97a657c9;

  struct EVMExtraArgsV1 {
    uint256 gasLimit;
  }

  function _argsToBytes(
    EVMExtraArgsV1 memory extraArgs
  ) internal pure returns (bytes memory bts) {
    return abi.encodeWithSelector(EVM_EXTRA_ARGS_V1_TAG, extraArgs);
  }

  // Tag to indicate a gas limit (or dest chain equivalent processing units) and Out Of Order Execution. This tag is
  // available for multiple chain families. If there is no chain family specific tag, this is the default available
  // for a chain.
  // Note: not available for Solana VM based chains.
  bytes4 public constant GENERIC_EXTRA_ARGS_V2_TAG = 0x181dcf10;

  /// @param gasLimit: gas limit for the callback on the destination chain.
  /// @param allowOutOfOrderExecution: if true, it indicates that the message can be executed in any order relative to
  /// other messages from the same sender. This value's default varies by chain. On some chains, a particular value is
  /// enforced, meaning if the expected value is not set, the message request will revert.
  /// @dev Fully compatible with the previously existing EVMExtraArgsV2.
  struct GenericExtraArgsV2 {
    uint256 gasLimit;
    bool allowOutOfOrderExecution;
  }

  // Extra args tag for chains that use the Solana VM.
  bytes4 public constant SVM_EXTRA_ARGS_V1_TAG = 0x1f3b3aba;

  struct SVMExtraArgsV1 {
    uint32 computeUnits;
    uint64 accountIsWritableBitmap;
    bool allowOutOfOrderExecution;
    bytes32 tokenReceiver;
    // Additional accounts needed for execution of CCIP receiver. Must be empty if message.receiver is zero.
    // Token transfer related accounts are specified in the token pool lookup table on SVM.
    bytes32[] accounts;
  }

  /// @dev The maximum number of accounts that can be passed in SVMExtraArgs.
  uint256 public constant SVM_EXTRA_ARGS_MAX_ACCOUNTS = 64;

  /// @dev The expected static payload size of a token transfer when Borsh encoded and submitted to SVM.
  /// TokenPool extra data and offchain data sizes are dynamic, and should be accounted for separately.
  uint256 public constant SVM_TOKEN_TRANSFER_DATA_OVERHEAD = (4 + 32) // source_pool
    + 32 // token_address
    + 4 // gas_amount
    + 4 // extra_data overhead
    + 32 // amount
    + 32 // size of the token lookup table account
    + 32 // token-related accounts in the lookup table, over-estimated to 32, typically between 11 - 13
    + 32 // token account belonging to the token receiver, e.g ATA, not included in the token lookup table
    + 32 // per-chain token pool config, not included in the token lookup table
    + 32 // per-chain token billing config, not always included in the token lookup table
    + 32; // OffRamp pool signer PDA, not included in the token lookup table

  /// @dev Number of overhead accounts needed for message execution on SVM.
  /// @dev These are message.receiver, and the OffRamp Signer PDA specific to the receiver.
  uint256 public constant SVM_MESSAGING_ACCOUNTS_OVERHEAD = 2;

  /// @dev The size of each SVM account address in bytes.
  uint256 public constant SVM_ACCOUNT_BYTE_SIZE = 32;

  function _argsToBytes(
    GenericExtraArgsV2 memory extraArgs
  ) internal pure returns (bytes memory bts) {
    return abi.encodeWithSelector(GENERIC_EXTRA_ARGS_V2_TAG, extraArgs);
  }

  function _svmArgsToBytes(
    SVMExtraArgsV1 memory extraArgs
  ) internal pure returns (bytes memory bts) {
    return abi.encodeWithSelector(SVM_EXTRA_ARGS_V1_TAG, extraArgs);
  }
}

node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

src/diamond/shared/CohortWeeks.sol

// SPDX-License-Identifier: -- WISE --

pragma solidity =0.8.36;

/**
 * @dev CohortWeeks: the week epoch, lane geometry and carry codecs of the
 * referral cohort recorder, shared by the vault facets and the hub so no
 * contract restates these numbers (`week = timestamp / WEEK`).
 *
 * The book word and every crumb word hold three 80-bit lanes (year-1,
 * year-2, mature); a crumb word also sets bit 252 when written, and its
 * format is frozen because the hub prices it. Ring slots pack four uint64
 * lanes per storage word. The saturating helpers return the clipped
 * remainder and never revert, since they run inside the transfer hook.
 *
 * Same-chain carry (moves only, staged and consumed in one transaction):
 * word0 `referrer(160) | version(8) | pairCount(8)`, word1
 * `trackedDelta(128) | mature(128)`, then two pairs per word, a pair being
 * `amount(64) | slot(8) | ring(8)`. Bridge carry (cross-chain only), three
 * header words `referrer(160) | version(8) | captureWeek(32) |
 * pairCount(8)`, `trackedDelta(128) | assignedAt(64) | originRank(8)` and
 * `mature(128)`, then the pairs two per word in the same pair format.
 * `_bridgeCarryValid` rejects a payload wholesale unless its length and
 * layout hold, every reserved bit is zero, its lanes sum to at most
 * trackedDelta and trackedDelta is at most the amount the same message
 * mints. Every carried pair lands at the slot of its own credit week,
 * aged only by the week boundaries crossed between capture and landing
 * (`_landedCarryPair`), so a relocation never changes a cohort's age. A
 * destination clock behind the capture week takes the lag off the age,
 * floored at zero: a slot ahead of the destination week is the one its
 * next boundary graduates, so only credit younger than the lag lands in
 * the destination's current week.
 *
 * Self crumb word: `currentWeekSeconds(80) | previousWeekSeconds(80) |
 * settledAt(64)`. It is settled before every change of the tracked
 * contribution, which keeps the completed previous week exact.
 */
library CohortWeeks {

    uint256 internal constant WEEK = 1 weeks;

    uint256 internal constant RING_SLOTS = 52;

    // The 52-week year, the divisor of the commission rate: a rate is per
    // 52 weeks, the length of one ring year, so every full ring year pays
    // exactly the stated rate.
    uint256 internal constant YEAR = RING_SLOTS * WEEK;

    uint256 internal constant MAX_SETTLE_BOUNDARIES = 104;

    uint256 internal constant LANE_MASK_80 = (1 << 80) - 1;

    uint256 internal constant LANE_Y2_SHIFT = 80;

    uint256 internal constant LANE_M_SHIFT = 160;

    uint256 internal constant SELF_STAMP_SHIFT = 160;

    uint256 internal constant SELF_STAMP_MASK = (1 << 64) - 1;

    uint256 internal constant CRUMB_WRITTEN_BIT = 1 << 252;

    uint256 internal constant CRUMB_VERSION = 1;

    uint256 internal constant GAP_TO_SHIFT = 32;

    uint256 internal constant GAP_MATURE_SHIFT = 64;

    uint256 internal constant RING_LANE_MAX = type(uint64).max;

    uint256 internal constant CARRY_VERSION = 1;

    uint256 internal constant MAX_CARRY_PAIRS = 104;

    uint256 internal constant MAX_CARRY_WORDS = 54;

    uint256 internal constant CARRY_RING_YEAR1 = 0;

    uint256 internal constant CARRY_RING_YEAR2 = 1;

    uint256 internal constant CARRY_VERSION_SHIFT = 160;

    uint256 internal constant CARRY_PAIR_COUNT_SHIFT = 168;

    uint256 internal constant CARRY_BYTE_MASK = 0xff;

    uint256 internal constant CARRY_HALF_SHIFT = 128;

    uint256 internal constant CARRY_HALF_MASK = (1 << 128) - 1;

    uint256 internal constant CARRY_PAIR_SLOT_SHIFT = 64;

    uint256 internal constant CARRY_PAIR_RING_SHIFT = 72;

    uint256 internal constant CARRY_PAIR_RESERVED_SHIFT = 80;

    uint256 internal constant CARRY_LANE_MATURE = 2;

    uint256 internal constant BRIDGE_CARRY_VERSION = 3;

    uint256 internal constant BRIDGE_CARRY_HEADER_WORDS = 3;

    uint256 internal constant BRIDGE_CARRY_HEADER_BYTES = 96;

    // The longest bridge carry: three header words and 104 pairs.
    uint256 internal constant BRIDGE_CARRY_BYTES = 1_760;

    uint256 internal constant BRIDGE_CARRY_PAIR_COUNT_SHIFT = 200;

    uint256 internal constant BRIDGE_CARRY_ASSIGNED_AT_SHIFT = 128;

    uint256 internal constant BRIDGE_CARRY_RANK_SHIFT = 192;

    uint256 internal constant BRIDGE_CARRY_CAPTURE_WEEK_SHIFT = 168;

    uint256 internal constant BRIDGE_CARRY_CAPTURE_WEEK_MASK = (1 << 32) - 1;

    uint256 internal constant BRIDGE_CARRY_ENVELOPE_RESERVED_SHIFT = 208;

    uint256 internal constant BRIDGE_CARRY_TRACKED_RESERVED_SHIFT = 200;

    uint256 internal constant SELF_LOG_WEEK_MASK = (1 << 32) - 1;

    uint256 internal constant SELF_LOG_SECONDS_SHIFT = 32;

    uint256 internal constant SELF_LOG_STAKE_SHIFT = 112;

    function _packCarryEnvelope(
        address _referrer,
        uint256 _pairCount
    )
        internal
        pure
        returns (uint256)
    {
        return uint256(uint160(_referrer))
            | (CARRY_VERSION << CARRY_VERSION_SHIFT)
            | (_pairCount << CARRY_PAIR_COUNT_SHIFT);
    }

    function _carryEnvelopeReferrer(
        uint256 _word
    )
        internal
        pure
        returns (address)
    {
        return address(
            uint160(_word)
        );
    }

    function _carryEnvelopeVersion(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return (_word >> CARRY_VERSION_SHIFT) & CARRY_BYTE_MASK;
    }

    function _carryEnvelopePairCount(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return (_word >> CARRY_PAIR_COUNT_SHIFT) & CARRY_BYTE_MASK;
    }

    function _packCarryAmounts(
        uint256 _trackedDelta,
        uint256 _mature
    )
        internal
        pure
        returns (uint256)
    {
        return _trackedDelta
            | (_mature << CARRY_HALF_SHIFT);
    }

    function _carryTrackedDelta(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return _word & CARRY_HALF_MASK;
    }

    function _carryMature(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return _word >> CARRY_HALF_SHIFT;
    }

    function _packCarryPair(
        uint256 _amount,
        uint256 _slot,
        uint256 _ring
    )
        internal
        pure
        returns (uint256)
    {
        return _amount
            | (_slot << CARRY_PAIR_SLOT_SHIFT)
            | (_ring << CARRY_PAIR_RING_SHIFT);
    }

    function _carryPairAmount(
        uint256 _pair
    )
        internal
        pure
        returns (uint256)
    {
        return _pair & RING_LANE_MAX;
    }

    function _carryPairSlot(
        uint256 _pair
    )
        internal
        pure
        returns (uint256)
    {
        return (_pair >> CARRY_PAIR_SLOT_SHIFT) & CARRY_BYTE_MASK;
    }

    function _carryPairRing(
        uint256 _pair
    )
        internal
        pure
        returns (uint256)
    {
        return (_pair >> CARRY_PAIR_RING_SHIFT) & CARRY_BYTE_MASK;
    }

    function _packCarryPairsWord(
        uint256 _pairLo,
        uint256 _pairHi
    )
        internal
        pure
        returns (uint256)
    {
        return _pairLo
            | (_pairHi << CARRY_HALF_SHIFT);
    }

    function _carryPairLo(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return _word & CARRY_HALF_MASK;
    }

    function _carryPairHi(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return _word >> CARRY_HALF_SHIFT;
    }

    function _packBridgeCarryEnvelope(
        address _referrer,
        uint256 _captureWeek,
        uint256 _pairCount
    )
        internal
        pure
        returns (uint256)
    {
        return uint256(uint160(_referrer))
            | (BRIDGE_CARRY_VERSION << CARRY_VERSION_SHIFT)
            | (_captureWeek << BRIDGE_CARRY_CAPTURE_WEEK_SHIFT)
            | (_pairCount << BRIDGE_CARRY_PAIR_COUNT_SHIFT);
    }

    function _packBridgeCarryTracked(
        uint256 _trackedDelta,
        uint256 _assignedAt,
        uint256 _rank
    )
        internal
        pure
        returns (uint256)
    {
        return _trackedDelta
            | (_assignedAt << BRIDGE_CARRY_ASSIGNED_AT_SHIFT)
            | (_rank << BRIDGE_CARRY_RANK_SHIFT);
    }

    function _bridgeCarryAssignedAt(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return (_word >> BRIDGE_CARRY_ASSIGNED_AT_SHIFT) & RING_LANE_MAX;
    }

    function _bridgeCarryRank(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return (_word >> BRIDGE_CARRY_RANK_SHIFT) & CARRY_BYTE_MASK;
    }

    function _bridgeCarryCaptureWeek(
        uint256 _word0
    )
        internal
        pure
        returns (uint256)
    {
        return (_word0 >> BRIDGE_CARRY_CAPTURE_WEEK_SHIFT) & BRIDGE_CARRY_CAPTURE_WEEK_MASK;
    }

    function _bridgeCarryPairCount(
        uint256 _word0
    )
        internal
        pure
        returns (uint256)
    {
        return (_word0 >> BRIDGE_CARRY_PAIR_COUNT_SHIFT) & CARRY_BYTE_MASK;
    }

    function _packBridgeCarry(
        uint256[] memory _words
    )
        internal
        pure
        returns (bytes memory)
    {
        return abi.encodePacked(
            _words
        );
    }

    function _unpackBridgeCarry(
        bytes memory _data
    )
        internal
        pure
        returns (uint256[] memory words)
    {
        words = new uint256[](
            _data.length / 32
        );

        for (uint256 i; i < words.length; ++i) {

            uint256 word;

            assembly {
                word := mload(add(_data, mul(add(i, 1), 0x20)))
            }

            words[i] = word;
        }
    }

    function _carryPairOf(
        uint256[] memory _words,
        uint256 _firstPairWord,
        uint256 _index
    )
        internal
        pure
        returns (uint256)
    {
        uint256 word = _words[_firstPairWord + _index / 2];

        return _index % 2 == 0
            ? _carryPairLo(
                word
            )
            : _carryPairHi(
                word
            );
    }

    function _carryPairSums(
        uint256[] memory _words,
        uint256 _firstPairWord,
        uint256 _pairCount
    )
        internal
        pure
        returns (
            uint256 year1,
            uint256 year2
        )
    {
        for (uint256 i; i < _pairCount; ++i) {

            uint256 pair = _carryPairOf(
                _words,
                _firstPairWord,
                i
            );

            if (_carryPairRing(pair) == CARRY_RING_YEAR1) {
                year1 += _carryPairAmount(
                    pair
                );
            } else {
                year2 += _carryPairAmount(
                    pair
                );
            }
        }
    }

    function _carryPairsValid(
        uint256[] memory _words,
        uint256 _firstPairWord,
        uint256 _pairCount,
        uint256 _laneSum,
        bool _checkReserved
    )
        internal
        pure
        returns (
            bool ok,
            uint256 laneSum
        )
    {
        laneSum = _laneSum;

        if (
            _pairCount % 2 == 1
                && _carryPairHi(_words[_words.length - 1]) != 0
        ) {
            return (
                false,
                _laneSum
            );
        }

        for (uint256 i; i < _pairCount; ++i) {

            uint256 pair = _carryPairOf(
                _words,
                _firstPairWord,
                i
            );

            if (
                _checkReserved
                    && pair >> CARRY_PAIR_RESERVED_SHIFT != 0
            ) {
                return (
                    false,
                    _laneSum
                );
            }

            if (
                _carryPairSlot(pair) >= RING_SLOTS
                    || _carryPairRing(pair) > CARRY_RING_YEAR2
            ) {
                return (
                    false,
                    _laneSum
                );
            }

            laneSum += _carryPairAmount(
                pair
            );
        }

        return (
            true,
            laneSum
        );
    }

    function _bridgeCarryValid(
        bytes memory _data,
        uint256 _mintAmount
    )
        internal
        pure
        returns (bool)
    {
        if (
            _data.length < BRIDGE_CARRY_HEADER_BYTES
                || _data.length > BRIDGE_CARRY_BYTES
                || _data.length % 32 != 0
        ) {
            return false;
        }

        uint256[] memory words = _unpackBridgeCarry(
            _data
        );

        uint256 pairCount = _bridgeCarryPairCount(
            words[0]
        );

        if (
            _carryEnvelopeVersion(words[0]) != BRIDGE_CARRY_VERSION
                || words[0] >> BRIDGE_CARRY_ENVELOPE_RESERVED_SHIFT != 0
                || words[1] >> BRIDGE_CARRY_TRACKED_RESERVED_SHIFT != 0
                || words[2] >> CARRY_HALF_SHIFT != 0
                || words.length != BRIDGE_CARRY_HEADER_WORDS + (pairCount + 1) / 2
        ) {
            return false;
        }

        (
            bool pairsOk,
            uint256 laneSum
        ) = _carryPairsValid(
            words,
            BRIDGE_CARRY_HEADER_WORDS,
            pairCount,
            words[2],
            true
        );

        if (pairsOk == false) {
            return false;
        }

        uint256 trackedDelta = _carryTrackedDelta(
            words[1]
        );

        if (_carryEnvelopeReferrer(words[0]) == address(0)) {

            if (laneSum != 0 || pairCount != 0) {
                return false;
            }
        } else {

            if (laneSum > trackedDelta) {
                return false;
            }
        }

        if (trackedDelta == 0 && laneSum == 0) {
            return false;
        }

        return trackedDelta <= _mintAmount;
    }

    function _landedCarryPair(
        uint256 _pair,
        uint256 _captureWeek,
        uint256 _arrivalWeek
    )
        internal
        pure
        returns (
            uint256 slot,
            uint256 lane
        )
    {
        uint256 age = (_captureWeek + RING_SLOTS - _carryPairSlot(_pair)) % RING_SLOTS
            + _carryPairRing(_pair) * RING_SLOTS;

        if (_arrivalWeek > _captureWeek) {
            age += _arrivalWeek - _captureWeek;
        }

        if (_captureWeek > _arrivalWeek) {

            uint256 lag = _captureWeek - _arrivalWeek;

            age = age > lag
                ? age - lag
                : 0;
        }

        if (age >= 2 * RING_SLOTS) {
            return (
                0,
                CARRY_LANE_MATURE
            );
        }

        return (
            (_arrivalWeek + 2 * RING_SLOTS - age) % RING_SLOTS,
            age / RING_SLOTS
        );
    }

    function _packSelfLogRecord(
        uint256 _fromWeek,
        uint256 _completedSeconds,
        uint256 _stake
    )
        internal
        pure
        returns (uint256)
    {
        return _fromWeek
            | (_completedSeconds << SELF_LOG_SECONDS_SHIFT)
            | (_stake << SELF_LOG_STAKE_SHIFT);
    }

    function _selfLogFromWeek(
        uint256 _record
    )
        internal
        pure
        returns (uint256)
    {
        return _record & SELF_LOG_WEEK_MASK;
    }

    function _selfLogSeconds(
        uint256 _record
    )
        internal
        pure
        returns (uint256)
    {
        return (_record >> SELF_LOG_SECONDS_SHIFT) & LANE_MASK_80;
    }

    function _selfLogStake(
        uint256 _record
    )
        internal
        pure
        returns (uint256)
    {
        return (_record >> SELF_LOG_STAKE_SHIFT) & LANE_MASK_80;
    }

    function _packGapRecord(
        uint256 _fromWeek,
        uint256 _toWeekExclusive,
        uint256 _mature
    )
        internal
        pure
        returns (uint256)
    {
        return _fromWeek
            | (_toWeekExclusive << GAP_TO_SHIFT)
            | (_mature << GAP_MATURE_SHIFT);
    }

    function _gapRecordFromWeek(
        uint256 _record
    )
        internal
        pure
        returns (uint256)
    {
        return _record & ((1 << GAP_TO_SHIFT) - 1);
    }

    function _gapRecordToWeek(
        uint256 _record
    )
        internal
        pure
        returns (uint256)
    {
        return (_record >> GAP_TO_SHIFT) & ((1 << GAP_TO_SHIFT) - 1);
    }

    function _gapRecordMature(
        uint256 _record
    )
        internal
        pure
        returns (uint256)
    {
        return (_record >> GAP_MATURE_SHIFT) & LANE_MASK_80;
    }

    function _laneY1(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return _word & LANE_MASK_80;
    }

    function _laneY2(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return (_word >> LANE_Y2_SHIFT) & LANE_MASK_80;
    }

    function _laneM(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return (_word >> LANE_M_SHIFT) & LANE_MASK_80;
    }

    function _packLanes(
        uint256 _y1,
        uint256 _y2,
        uint256 _m
    )
        internal
        pure
        returns (uint256)
    {
        return _y1
            | (_y2 << LANE_Y2_SHIFT)
            | (_m << LANE_M_SHIFT);
    }

    function _saturatingAddCapped(
        uint256 _lane,
        uint256 _add,
        uint256 _cap
    )
        internal
        pure
        returns (
            uint256 result,
            uint256 clipped
        )
    {
        uint256 sum = _lane + _add;

        if (sum > _cap) {
            return (
                _cap,
                sum - _cap
            );
        }

        return (
            sum,
            0
        );
    }

    function _saturatingAdd80(
        uint256 _lane,
        uint256 _add
    )
        internal
        pure
        returns (
            uint256 result,
            uint256 clipped
        )
    {
        return _saturatingAddCapped(
            _lane,
            _add,
            LANE_MASK_80
        );
    }

    function _saturatingAdd64(
        uint256 _lane,
        uint256 _add
    )
        internal
        pure
        returns (
            uint256 result,
            uint256 clipped
        )
    {
        return _saturatingAddCapped(
            _lane,
            _add,
            RING_LANE_MAX
        );
    }

    function _saturatingSub(
        uint256 _value,
        uint256 _sub
    )
        internal
        pure
        returns (
            uint256 result,
            uint256 clipped
        )
    {
        if (_sub > _value) {
            return (
                0,
                _sub - _value
            );
        }

        return (
            _value - _sub,
            0
        );
    }

    function _clampLane80(
        uint256 _value
    )
        internal
        pure
        returns (uint256)
    {
        return _value < LANE_MASK_80
            ? _value
            : LANE_MASK_80;
    }

    function _packSelfCrumb(
        uint256 _currentSeconds,
        uint256 _previousSeconds,
        uint256 _settledAt
    )
        internal
        pure
        returns (uint256)
    {
        return _currentSeconds
            | (_previousSeconds << LANE_Y2_SHIFT)
            | (_settledAt << SELF_STAMP_SHIFT);
    }

    function _selfCrumbCurrent(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return _word & LANE_MASK_80;
    }

    function _selfCrumbPrevious(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return (_word >> LANE_Y2_SHIFT) & LANE_MASK_80;
    }

    function _selfCrumbSettledAt(
        uint256 _word
    )
        internal
        pure
        returns (uint256)
    {
        return (_word >> SELF_STAMP_SHIFT) & SELF_STAMP_MASK;
    }

    function _settleSelfCrumb(
        uint256 _word,
        uint256 _tracked,
        uint256 _to
    )
        internal
        pure
        returns (uint256)
    {
        uint256 settledAt = _selfCrumbSettledAt(
            _word
        );

        if (settledAt >= _to) {
            return _word;
        }

        uint256 stake = _clampLane80(
            _tracked
        );

        uint256 fromWeek = settledAt / WEEK;

        uint256 toWeek = _to / WEEK;

        uint256 current = _selfCrumbCurrent(
            _word
        );

        uint256 previous = _selfCrumbPrevious(
            _word
        );

        if (toWeek == fromWeek) {
            current = _clampLane80(
                current + stake * (_to - settledAt)
            );
        } else {
            previous = _completedPreviousSeconds(
                current,
                stake,
                settledAt,
                toWeek
            );

            current = _clampLane80(
                stake * (_to - toWeek * WEEK)
            );
        }

        return _packSelfCrumb(
            current,
            previous,
            _to
        );
    }

    function _completedPreviousSeconds(
        uint256 _current,
        uint256 _stake,
        uint256 _settledAt,
        uint256 _week
    )
        internal
        pure
        returns (uint256)
    {
        if (_settledAt / WEEK + 1 == _week) {
            return _clampLane80(
                _current + _stake * (_week * WEEK - _settledAt)
            );
        }

        return _clampLane80(
            _stake * WEEK
        );
    }

    function _liveSecondsCohort(
        uint256 _from,
        uint256 _to,
        uint256 _disarmedAt,
        uint256 _rearmedAt
    )
        internal
        pure
        returns (uint256)
    {
        uint256 skipFrom = _from > _disarmedAt
            ? _from
            : _disarmedAt;

        uint256 skipTo = _to < _rearmedAt
            ? _to
            : _rearmedAt;

        if (skipTo <= skipFrom) {
            return _to - _from;
        }

        return _to
            - _from
            - (skipTo - skipFrom);
    }
}

src/diamond/shared/OwnableMaster.sol

// SPDX-License-Identifier: -- WISE --

pragma solidity =0.8.36;

error NoValue();

error NotMaster();

error NotProposed();

/**
 * @dev Two-step ownership transfer, ported verbatim from
 * `src/legacy/OwnableMasterLegacy.sol`. Storage layout is identical
 * (slots 0 and 1) so a diamond inheriting this contract reproduces
 * the legacy slot ordering for the master/proposedMaster pair.
 */
contract OwnableMaster {

    address public master;

    address public proposedMaster;

    address internal constant ZERO_ADDRESS = address(0x0);

    event MasterProposed(
        address indexed proposer,
        address indexed proposedMaster
    );

    event RenouncedOwnership(
        address indexed previousMaster
    );

    modifier onlyProposed() {
        _onlyProposed();
        _;
    }

    modifier onlyMaster() {
        _onlyMaster();
        _;
    }

    function _onlyMaster()
        private
        view
    {
        if (msg.sender == master) {
            return;
        }

        revert NotMaster();
    }

    function _onlyProposed()
        private
        view
    {
        if (msg.sender == proposedMaster) {
            return;
        }

        revert NotProposed();
    }

    constructor(
        address _master
    ) {
        if (_master == ZERO_ADDRESS) {
            revert NoValue();
        }

        master = _master;
    }

    function proposeOwner(
        address _proposedOwner
    )
        external
        onlyMaster
    {
        if (_proposedOwner == ZERO_ADDRESS) {
            revert NoValue();
        }

        proposedMaster = _proposedOwner;

        emit MasterProposed(
            msg.sender,
            _proposedOwner
        );
    }

    function claimOwnership()
        external
        onlyProposed
    {
        master = msg.sender;
    }

    function renounceOwnership()
        external
        onlyMaster
    {
        master = ZERO_ADDRESS;
        proposedMaster = ZERO_ADDRESS;

        emit RenouncedOwnership(
            msg.sender
        );
    }
}

src/hub/IReferralHub.sol

// SPDX-License-Identifier: -- WISE --

pragma solidity =0.8.36;

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import {Client} from "@chainlink/contracts-ccip/contracts/libraries/Client.sol";

/**
 * @dev The external surface of the deployed ReferralHub diamond, its own
 * getters and the facet routed entrypoints alike.
 */
interface IReferralHub {

    // ---- OwnableMaster (proxy native) ----

    function master()
        external
        view
        returns (address);

    function proposedMaster()
        external
        view
        returns (address);

    function proposeOwner(
        address _proposedMaster
    )
        external;

    function claimOwnership()
        external;

    function renounceOwnership()
        external;

    // ---- Selector machinery (proxy native) ----

    function initialized()
        external
        view
        returns (bool);

    function selectorToFacet(
        bytes4 _selector
    )
        external
        view
        returns (address);

    function proposedSelectorFacet(
        bytes4 _selector
    )
        external
        view
        returns (address);

    function selectorChangeQueuedAt(
        bytes4 _selector
    )
        external
        view
        returns (uint256);

    function finalizeSetup()
        external;

    function proposeSelector(
        bytes4 _selector,
        address _facet
    )
        external;

    function proposeSelectors(
        bytes4[] calldata _selectors,
        address _facet
    )
        external;

    function executeSelectorChange(
        bytes4 _selector
    )
        external;

    function executeSelectorChanges(
        bytes4[] calldata _selectors
    )
        external;

    function cancelSelectorProposal(
        bytes4 _selector
    )
        external;

    function proposeLeverChange(
        bytes calldata _call
    )
        external;

    function cancelLeverChange(
        bytes32 _changeHash
    )
        external;

    function leverChangeQueuedAt(
        bytes32 _changeHash
    )
        external
        view
        returns (uint256);

    // ---- Storage getters (proxy native) ----

    function USD_TOKEN()
        external
        view
        returns (IERC20);

    function claimable(
        uint256 _chainId,
        address _account
    )
        external
        view
        returns (uint256);

    function totalAccrued()
        external
        view
        returns (uint256);

    function totalClaimed()
        external
        view
        returns (uint256);

    function totalPayable()
        external
        view
        returns (uint256);

    function allowedReporter(
        address _reporter
    )
        external
        view
        returns (bool);

    function payoutStamp(
        uint256 _chainId,
        address _owner
    )
        external
        view
        returns (uint256);

    function ccipRouter()
        external
        view
        returns (address);

    function flushSourceChainId(
        uint64 _chainSelector,
        address _sender
    )
        external
        view
        returns (uint256);

    function designationSourceChainId(
        uint64 _chainSelector,
        address _sender
    )
        external
        view
        returns (uint256);

    function flushCommitment(
        bytes32 _messageId
    )
        external
        view
        returns (bytes32);

    function delivererShareCap()
        external
        view
        returns (uint256);

    function sourceSystemOf(
        bytes32 _source
    )
        external
        view
        returns (uint256);

    function sourceChainIdOf(
        bytes32 _source
    )
        external
        view
        returns (uint256);

    function MAX_SYSTEMS()
        external
        view
        returns (uint256);

    // ---- Intake facet ----

    function reportSelf(
        address _referrer,
        uint256[] calldata _selfRuns
    )
        external;

    function settleWeeks(
        address _referrer,
        uint256 _fromWeek,
        uint256 _weekCount
    )
        external;

    function deliverCrumbs(
        address _referrer,
        address _deliverer,
        uint256[] calldata _weeks,
        uint256[] calldata _words
    )
        external;

    function deliverGap(
        address _referrer,
        address _deliverer,
        uint256 _record,
        uint256 _fromWeek,
        uint256 _maxWeeks
    )
        external;

    function setAllowedReporter(
        address _reporter,
        bool _allowed
    )
        external;

    function setSourceSystem(
        bytes32 _source,
        uint256 _systemId
    )
        external;

    function sourceKeyOf(
        uint256 _chainId,
        address _vault
    )
        external
        view
        returns (bytes32);

    function sourceCountOf(
        address _referrer
    )
        external
        view
        returns (uint256);

    function sourceOfAt(
        address _referrer,
        uint256 _index
    )
        external
        view
        returns (bytes32);

    function paidCursorAtSource(
        bytes32 _source,
        address _referrer,
        uint256 _week
    )
        external
        view
        returns (
            uint256 y1Cursor,
            uint256 y2Cursor,
            uint256 mCursor
        );

    // ---- Mailbox facet ----

    function ccipReceive(
        Client.Any2EVMMessage calldata _message
    )
        external;

    function applyFlush(
        bytes32 _messageId,
        uint64 _srcChainSelector,
        uint256 _chainId,
        address _vault,
        bytes calldata _payload
    )
        external;

    function supportsInterface(
        bytes4 _interfaceId
    )
        external
        view
        returns (bool);

    function setCcipRouter(
        address _router
    )
        external;

    function setFlushSource(
        uint64 _chainSelector,
        address _vault,
        uint256 _chainId
    )
        external;

    function setDesignationSource(
        uint64 _chainSelector,
        address _registry,
        uint256 _chainId
    )
        external;

    // ---- Payout facet ----

    function claim(
        uint256 _chainId,
        address _referrer
    )
        external;

    function claimUpTo(
        uint256 _chainId,
        address _referrer,
        uint256 _amount
    )
        external;

    function claimAll(
        address _referrer,
        uint256[] calldata _chainIds
    )
        external
        returns (uint256 total);

    function setPayoutAddress(
        address _payout
    )
        external;

    function payoutAddressOf(
        uint256 _chainId,
        address _owner
    )
        external
        view
        returns (address);

    // ---- Rates facet ----

    function pushRateTable(
        ReferralHubDeclarations.RateTable calldata _table
    )
        external;

    function setDelivererShareCap(
        uint256 _cap
    )
        external;

    function elevateReferrer(
        address _referrer,
        uint256 _fromWeek
    )
        external;

    function endElevation(
        address _referrer,
        uint256 _untilWeek
    )
        external;

    function elevatedFromWeek(
        address _referrer
    )
        external
        view
        returns (uint256);

    function elevatedUntilWeek(
        address _referrer
    )
        external
        view
        returns (uint256);

    function weeklyRates(
        address _referrer,
        uint256 _week
    )
        external
        view
        returns (
            uint256 y1Bps,
            uint256 y2Bps,
            uint256 mBps
        );

    function rateTableCount()
        external
        view
        returns (uint256);

    function rateTableAt(
        uint256 _index
    )
        external
        view
        returns (ReferralHubDeclarations.RateTable memory);

    // ---- Checkpoints facet ----

    function ladderInputsAt(
        address _referrer,
        uint256 _week
    )
        external
        view
        returns (
            uint256 referredInput,
            uint256 selfInput
        );

    function weekReportOf(
        bytes32 _source,
        address _referrer,
        uint256 _week
    )
        external
        view
        returns (
            uint256 referredAverage,
            uint256 paidUnits
        );

    function weekSelfOf(
        bytes32 _source,
        address _referrer,
        uint256 _week
    )
        external
        view
        returns (uint256);
}

src/hub/ReferralHubDeclarations.sol

// SPDX-License-Identifier: -- WISE --

pragma solidity =0.8.36;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import {OwnableMaster} from "../diamond/shared/OwnableMaster.sol";
import {CohortWeeks} from "../diamond/shared/CohortWeeks.sol";

/**
 * @dev Storage, constants, events and errors of the referral hub, shared by
 * the hub diamond and every facet. Sources are keyed by bytes32 because the
 * CREATE3 vaults share one address across chains, and claimables are kept
 * per source chain. Week W's ladder inputs live in W's own bucket: the
 * referred averages and the self averages, each summed over the sources.
 * `sourceWeekOf[source][referrer][week]` holds a source's reported referred
 * average for the week in the low half and the commission units already
 * paid for it in the high half; `sourceSelfOf[source][referrer][week]` holds
 * the source's reported self average; both are merged by maximum, so a
 * source's report for a closed week only rises.
 * `weekInputsOf[referrer][week]` holds the referred sum in the low half and
 * the self sum in the high half. An average is at most three 80-bit lanes
 * over one week by construction, so no half can overflow.
 * `sourceChainIdOf` is the chain a source credits, written at its first
 * delivery; `sourceListedFor` guards the per-referrer source list.
 * `sourceSystemOf` tags a source with its vault system for indexers and the
 * umbrella's accounting; pricing no longer reads it, and it freezes once
 * the source delivered. MAX_SYSTEMS is permanent.
 * `leverChangeQueuedAt` holds the proposal time of a queued master lever
 * call, keyed by the hash of its canonical calldata (the setter rebuilds
 * it from its decoded arguments, so trailing bytes never make a second
 * usable key): a proposal is accepted only after `finalizeSetup`, and a
 * grant (allowing a reporter, setting the router, setting a flush or
 * designation source to a chain id) runs only as that exact call at least
 * SELECTOR_CHANGE_DELAY after its proposal, the delay the vault side
 * `payoutHub` pointer and every hub selector change already wait, and each
 * proposal runs once; a revocation never waits.
 * `elevationWindowsOf[referrer]` is the referrer's elevation history: one
 * word per window, the from week in the low half and the until week in
 * the high half (zero while open), at most MAX_ELEVATION_WINDOWS words;
 * `elevatedFromWeek` and `elevatedUntilWeek` mirror the latest window.
 * A week is priced as at the cap when any window holds it, so a grant
 * after an end never changes the verdict of an earlier window.
 * Threat model: only
 * master-registered sources write, every write is a maximum or a cursor
 * advance, and a cell is paid at most its cumulative due, so a replayed,
 * reordered or duplicated delivery can never pay twice. The state the
 * buckets retired (the score aggregates, checkpoints, freshness words,
 * report retention and the remainder park) stays declared and unused, so
 * the layout only ever grows at its tail.
 */
abstract contract ReferralHubDeclarations is OwnableMaster {

    uint256 internal constant WEEK_HALF_SHIFT = 128;

    uint256 internal constant WEEK_HALF_MASK = (1 << 128) - 1;

    uint256 internal constant RATE_MASK = (1 << 16) - 1;

    uint256 internal constant RATE_Y2_SHIFT = 16;

    uint256 internal constant RATE_M_SHIFT = 32;

    uint256 internal constant GAP_WEEK_MASK = (1 << 32) - 1;

    uint256 internal constant BPS_DENOMINATOR = 10_000;

    uint256 internal constant PAYOUT_STAMP_SHIFT = 8;

    uint256 internal constant DESIGNATION_VERSION = 2;

    uint256 internal constant DESIGNATION_PAYLOAD_LENGTH = 160;

    uint256 internal constant MAX_DESIGNATION_FUTURE_DRIFT = 1 hours;

    uint256 internal constant MAX_BOT_SHARE_BPS = 2_000;

    uint256 internal constant MAX_SCHEDULE_HORIZON_WEEKS = 520;

    struct RateTable {
        uint32 effectiveFromWeek;
        uint16 capBps;
        uint16 y2RateBps;
        uint16 mRateBps;
        uint16 botShareBps;
        uint16[8] tierBps;
        uint96[8] thresholds;
    }

    // ---- Retired score state (unused, kept for the layout) ----

    mapping(address => uint256) internal globalReferredScore;

    mapping(address => uint256) internal globalSelfScore;

    mapping(address => uint256[]) internal referrerCheckpoints;

    mapping(bytes32 => mapping(address => uint256)) internal lastSourceReport;

    // ---- The sources a referrer was ever reported from (and a retired report word) ----

    mapping(address => bytes32[]) internal sourcesOf;

    mapping(bytes32 => mapping(address => uint256)) internal previousSourceReport;

    // ---- Week-versioned rate tables ----

    RateTable[] internal rateTables;

    // ---- Intake cursors + claimables ----

    mapping(bytes32 => mapping(address => mapping(uint256 => uint256))) internal paidCursor;

    mapping(bytes32 => mapping(address => mapping(uint256 => uint256))) internal paidRemainder;

    mapping(uint256 => mapping(address => uint256)) public claimable;

    uint256 public totalAccrued;

    uint256 public totalClaimed;

    uint256 public totalPayable;

    // ---- Access + policy knobs ----

    mapping(address => bool) public allowedReporter;

    // Retired with the dwell-min schedule.
    uint256[] internal dwellMinLog;

    mapping(uint256 => mapping(address => address)) internal payoutAddress;

    mapping(uint256 => mapping(address => uint256)) public payoutStamp;

    // ---- Cross-chain flush mailbox ----

    address public ccipRouter;

    mapping(uint64 => mapping(address => uint256)) public flushSourceChainId;

    mapping(uint64 => mapping(address => uint256)) public designationSourceChainId;

    mapping(bytes32 => bytes32) public flushCommitment;

    // Retired with the per-envelope score report.
    mapping(bytes32 => mapping(address => uint256)) internal appliedScoreStamp;

    // ---- Diamond proxy ----

    IERC20 public USD_TOKEN;

    mapping(bytes4 => address) public selectorToFacet;

    mapping(bytes4 => address) public proposedSelectorFacet;

    mapping(bytes4 => uint256) public selectorChangeQueuedAt;

    bool public initialized;

    uint256 internal constant SELECTOR_CHANGE_DELAY = 3 days;

    // ---- Courier share cap ----

    uint256 public delivererShareCap;

    // ---- Vault systems ----

    uint256 public constant MAX_SYSTEMS = 8;

    mapping(bytes32 => uint256) public sourceSystemOf;

    // ---- Week buckets ----

    mapping(bytes32 => mapping(address => mapping(uint256 => uint256))) internal sourceWeekOf;

    mapping(address => mapping(uint256 => uint256)) internal weekInputsOf;

    mapping(bytes32 => mapping(address => mapping(uint256 => uint256))) internal sourceSelfOf;

    mapping(bytes32 => uint256) public sourceChainIdOf;

    mapping(address => mapping(bytes32 => bool)) internal sourceListedFor;

    // ---- Lever timelock ----

    mapping(bytes32 => uint256) public leverChangeQueuedAt;

    // ---- Elevation (a referrer priced as at the cap for a week window) ----

    mapping(address => uint256) public elevatedFromWeek;

    mapping(address => uint256) public elevatedUntilWeek;

    // ---- Elevation window history (every window keeps its verdict) ----

    uint256 internal constant MAX_ELEVATION_WINDOWS = 8;

    mapping(address => uint256[]) internal elevationWindowsOf;

    // ---- Events ----

    event RateTableScheduled(
        uint256 indexed index,
        uint256 effectiveFromWeek
    );

    event CrumbPriced(
        bytes32 indexed source,
        address indexed referrer,
        uint256 indexed week,
        address deliverer,
        uint256 y1Increment,
        uint256 y2Increment,
        uint256 mIncrement,
        uint256 paid
    );

    event GapPriced(
        bytes32 indexed source,
        address indexed referrer,
        address deliverer,
        uint256 fromWeek,
        uint256 toWeekExclusive,
        uint256 paid
    );

    event CrumbLaneRegression(
        bytes32 indexed source,
        address indexed referrer,
        uint256 indexed week,
        uint256 laneKind,
        uint256 incoming,
        uint256 cursor
    );

    event ReporterAllowedSet(
        address indexed reporter,
        bool allowed
    );

    event PayoutAddressSet(
        uint256 indexed chainId,
        address indexed owner,
        address indexed payout
    );

    event PayoutClaimed(
        uint256 indexed chainId,
        address indexed referrer,
        address indexed payout,
        uint256 amount
    );

    event CcipRouterSet(
        address indexed router
    );

    event FlushSourceSet(
        uint64 indexed chainSelector,
        address indexed vault,
        uint256 chainId
    );

    event DesignationSourceSet(
        uint64 indexed chainSelector,
        address indexed registry,
        uint256 chainId
    );

    event FlushReceived(
        bytes32 indexed messageId,
        uint64 indexed srcChainSelector,
        address indexed vault,
        uint256 chainId,
        bytes payload
    );

    event FlushApplied(
        bytes32 indexed messageId,
        bytes32 indexed source,
        uint256 entryCount
    );

    event DesignationPushReceived(
        uint64 indexed srcChainSelector,
        uint256 indexed chainId,
        address indexed owner
    );

    event DelivererSharePaid(
        uint256 indexed chainId,
        address indexed deliverer,
        address indexed referrer,
        bytes32 messageId,
        uint256 amount
    );

    event FlushDesignationSkipped(
        uint256 indexed chainId,
        address indexed owner,
        uint256 stamp
    );

    event SetupFinalized();

    event ReferrerElevated(
        address indexed referrer,
        uint256 fromWeek
    );

    event ReferrerElevationEnded(
        address indexed referrer,
        uint256 untilWeek
    );

    event SelectorProposed(
        bytes4 indexed selector,
        address indexed facet,
        uint256 executableAt
    );

    event SelectorsProposed(
        bytes4[] selectors,
        address indexed facet,
        uint256 executableAt
    );

    event SelectorUpdated(
        bytes4 indexed selector,
        address indexed facet
    );

    event SelectorProposalCancelled(
        bytes4 indexed selector
    );

    event DelivererShareCapSet(
        uint256 cap
    );

    event SourceListed(
        address indexed referrer,
        bytes32 indexed source,
        uint256 chainId
    );

    event WeekReferredReported(
        bytes32 indexed source,
        address indexed referrer,
        uint256 indexed week,
        uint256 referredAverage
    );

    event WeekSelfReported(
        bytes32 indexed source,
        address indexed referrer,
        uint256 indexed week,
        uint256 selfAverage
    );

    event WeekRatesRaised(
        address indexed referrer,
        uint256 indexed week
    );

    event WeekToppedUp(
        bytes32 indexed source,
        address indexed referrer,
        uint256 indexed week,
        uint256 amount
    );

    event SourceSystemSet(
        bytes32 indexed source,
        uint256 systemId
    );

    event LeverChangeProposed(
        bytes32 indexed changeHash,
        bytes call,
        uint256 executableAt
    );

    event LeverChangeCancelled(
        bytes32 indexed changeHash
    );

    // ---- Errors ----

    error ZeroAddress();

    error NotReporter();

    error FutureWeek();

    error WeekNotClosed();

    error InvalidSelfRun();

    error LengthMismatch();

    error BatchTooLarge();

    error InvalidCrumbWord();

    error InvalidGapRecord();

    error InvalidWindow();

    error TableNotFuture();

    error TableNotOrdered();

    error InvalidRateTable();

    error NothingClaimable();

    error PotDry();

    error NotPayoutAuthorized();

    error NotCcipRouter();

    error UnknownFlushSource();

    error FlushAlreadyReceived();

    error UnknownFlushCommitment();

    error FlushPayloadInvalid();

    error BotShareTooHigh();

    error SourceOnHubChain();

    error WeekOutOfRange();

    error SourceAlreadySet();

    error SystemOutOfRange();

    error LeverChangeNotQueued();

    error LeverTimelockNotElapsed();

    error SetupNotFinalized();

    error ElevationNotFuture();

    error AlreadyElevated();

    error NotElevated();

    error ElevationHistoryFull();

    /**
     * @dev Consumes the queued lever change a grant runs as. Before
     * `finalizeSetup` the grant runs at once (the deploy wiring needs no
     * proposal); afterwards only the exact call master queued at least
     * SELECTOR_CHANGE_DELAY earlier passes, and the entry is cleared so
     * each proposal runs once.
     */
    function _consumeLeverChange(
        bytes32 _changeHash
    )
        internal
    {
        if (initialized == false) {
            return;
        }

        uint256 queuedAt = leverChangeQueuedAt[_changeHash];

        require(
            queuedAt > 0,
            LeverChangeNotQueued()
        );

        require(
            block.timestamp >= queuedAt + SELECTOR_CHANGE_DELAY,
            LeverTimelockNotElapsed()
        );

        leverChangeQueuedAt[_changeHash] = 0;
    }

    /**
     * @dev The launch ladder: thresholds 5k to 1M USD, tiers 1 to 8
     * percent, cap 1_000 bps, year-2 500 bps, mature 100 bps, courier share
     * 500 bps.
     */
    function _seedGenesisRateTable()
        internal
    {
        rateTables.push(
            RateTable({
                effectiveFromWeek: 0,
                capBps: 1_000,
                y2RateBps: 500,
                mRateBps: 100,
                botShareBps: 500,
                tierBps: [
                    uint16(100),
                    200,
                    300,
                    400,
                    500,
                    600,
                    700,
                    800
                ],
                thresholds: [
                    uint96(5_000 * 1e6),
                    10_000 * 1e6,
                    20_000 * 1e6,
                    30_000 * 1e6,
                    50_000 * 1e6,
                    100_000 * 1e6,
                    500_000 * 1e6,
                    1_000_000 * 1e6
                ]
            })
        );

        emit RateTableScheduled(
            0,
            0
        );
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 600000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "@chainlink/contracts-ccip/=node_modules/@chainlink/contracts-ccip/",
    "@chainlink/contracts/=node_modules/@chainlink/contracts/",
    "@arbitrum/=node_modules/@arbitrum/",
    "@eth-optimism/=node_modules/@eth-optimism/",
    "@offchainlabs/=node_modules/@offchainlabs/",
    "@scroll-tech/=node_modules/@scroll-tech/",
    "@zksync/=node_modules/@zksync/",
    "solady/=node_modules/solady/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.