Skip to content
Verified contractPartialLicenseRef-Dromos-Restricted-Use-1.0

LeafMessageOrchestrator

Address0x7ea1079604af6da2282b80f4cdc6cea7b07914fe
Balance

0.249929 ETH

 

Transactions

2

 

Compiler

solc 0.8.36

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.36+commit.8a079791
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
prague
License
LicenseRef-Dromos-Restricted-Use-1.0
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,206,271
Creation transaction
0x371eabaf28…ec41ef887f
Libraries
V3/src/src/libraries/RewardsLogicLibrary.sol:RewardsLogicLibrary0x2b73…8d6720V3/src/src/libraries/LeafAllocationLibrary.sol:LeafAllocationLibrary0xc7e2…3e0398V3/src/src/libraries/VotingRewardsFactoryLibrary.sol:VotingRewardsFactoryLibrary0x1c38…49634e

V3/src/bridge/LeafMessageOrchestrator.sol

/// SPDX-License-Identifier: LicenseRef-Dromos-Restricted-Use-1.0
pragma solidity 0.8.36;

import {MessageOrchestrator} from 'V3/bridge/MessageOrchestrator.sol';
import {
  ILeafMessageOrchestrator,
  ILeafVoter,
  IMessageAdapter,
  IMessageOrchestrator
} from 'V3/interfaces/bridge/ILeafMessageOrchestrator.sol';
import {IVoterCommon} from 'V3/interfaces/voter/IVoterCommon.sol';
import {Roles} from 'V3/libraries/Roles.sol';

/**
 * @title LeafMessageOrchestrator
 * @notice Leaf-side orchestrator, deployed on every chain. Sends outbound messages from the local `LeafVoter` to
 * root and routes inbound root messages back to it.
 * @dev Holds the pre-funding pool that pays root-triggered deallocation returns.
 */
contract LeafMessageOrchestrator is MessageOrchestrator, ILeafMessageOrchestrator {
  /// @inheritdoc ILeafMessageOrchestrator
  ILeafVoter public immutable LEAF_VOTER;

  /// @inheritdoc ILeafMessageOrchestrator
  uint256 public immutable ROOT_CHAIN_ID;

  /// @inheritdoc ILeafMessageOrchestrator
  IMessageAdapter public adapter;
  /// @inheritdoc ILeafMessageOrchestrator
  uint256 public nonceOut;

  /// @inheritdoc ILeafMessageOrchestrator
  mapping(uint256 _nonce => bool _used) public noncesUsed;

  /// @inheritdoc ILeafMessageOrchestrator
  uint256 public deallocationGasLimit;

  /// @inheritdoc ILeafMessageOrchestrator
  uint256 public lastChainVoteNonce;
  /// @inheritdoc ILeafMessageOrchestrator
  mapping(uint256 _tokenId => uint256 _nonce) public lastTokenIdVoteNonce;
  /// @inheritdoc ILeafMessageOrchestrator
  mapping(uint256 _tokenId => uint256 _nonce) public lastOperatorNonce;

  /// @inheritdoc ILeafMessageOrchestrator
  mapping(uint256 _tokenId => uint256 _nonce) public lastEmergencyDeallocNonce;

  /// @inheritdoc ILeafMessageOrchestrator
  mapping(uint256 _tokenId => uint256 _nonce) public lastShapeNonce;

  /**
   * @notice Binds the orchestrator to its local `LeafVoter` and root chain id at deployment.
   * @param _leafVoter Local `LeafVoter`: the only `dispatch` caller, the inbound routing target, and role source.
   * @param _rootChainId Chain id of root; the registered adapter's `REMOTE_CHAIN_ID` must match it.
   * @param _adapter Initial root transport, or zero when root adapters are registered later.
   * @param _deallocationGasLimit Initial gas budget for deallocation returns, or zero until configured.
   */
  constructor(
    address _leafVoter,
    uint256 _rootChainId,
    IMessageAdapter _adapter,
    uint256 _deallocationGasLimit
  ) payable {
    if (_leafVoter == address(0)) revert ZeroAddress();
    if (_rootChainId == 0) revert InvalidRootChainId();

    LEAF_VOTER = ILeafVoter(_leafVoter);
    ROOT_CHAIN_ID = _rootChainId;
    if (address(_adapter) != address(0)) {
      if (_adapter.REMOTE_CHAIN_ID() != _rootChainId) revert AdapterChainIdMismatch();
      adapter = _adapter;
      emit AdapterUpdated(_adapter);
    }
    deallocationGasLimit = _deallocationGasLimit;
    emit DeallocationGasLimitSet(_deallocationGasLimit);
  }

  /// @notice Accepts the pre-funding that pays root-triggered deallocation returns, plus the transport's refunds.
  receive() external payable {}

  /// @inheritdoc ILeafMessageOrchestrator
  function dispatch(
    MessageType _msgType,
    bytes calldata _payload,
    uint256 _gasLimit,
    address _refundRecipient,
    bool _fundFromPool
  ) external payable {
    if (msg.sender != address(LEAF_VOTER)) revert CallerNotAuthorized();
    if (_msgType != MessageType.Redeem && _msgType != MessageType.Deallocate) revert UnsupportedMessageType();
    IMessageAdapter _adapter = adapter;
    if (address(_adapter) == address(0)) revert AdapterNotRegistered();
    // The `LeafVoter` gates the status: `redeem` is `chainIsActiveOrSunset`, open only while Active or Sunset. A
    // `Deallocate` goes out while Suspended.

    uint256 _nonce = ++nonceOut;
    bytes memory _message = _encodeMessage(_msgType, _nonce, _payload);

    // A pool-funded return refunds back into the pool it drew from; everything else refunds the caller's recipient.
    address _refund = _fundFromPool ? address(this) : _refundRecipient;
    uint256 _budget = _resolveGasLimit(_msgType, _gasLimit);
    uint256 _value = msg.value;

    if (_msgType == MessageType.Deallocate) {
      // Live quote instead of a configured cost, so the fee charged never drifts from the real one.
      uint256 _fee = _adapter.quoteMessage(_message, _budget, _refund);
      if (_fundFromPool) {
        // Checked here so an unfunded draw reverts with this error, not the transport's raw balance failure.
        if (address(this).balance < _fee) revert InsufficientDeallocationMessageValue();
        _value = _fee;
      } else if (_value < _fee) {
        // Caller-funded: the whole value goes out, so the transport refunds the excess to `_refundRecipient`.
        revert InsufficientDeallocationMessageValue();
      }
    }

    _adapter.sendMessage{value: _value}(_message, _budget, _refund);

    emit MessageDispatched(_adapter.REMOTE_CHAIN_ID(), _nonce, _msgType);
  }

  /// @inheritdoc IMessageOrchestrator
  function route(uint256 _originChainId, bytes calldata _payload) external payable {
    if (msg.sender != address(adapter)) revert CallerNotAdapter();

    // No suspension gate: root messages keep applying while Suspended so the leaf repairs itself. The `LeafVoter`
    // masks the applied rate to zero for that window, so no unfunded emissions accrue.
    (MessageType _msgType, uint256 _chainNonce, bytes calldata _body) = _decodeMessage(_payload);

    // Single-use replay gate. No try/catch below: a reverting handler must roll the nonce back so the transport
    // redelivers and the additive `AllocateChain` delta still applies exactly once.
    if (noncesUsed[_chainNonce]) revert NonceAlreadyUsed();
    noncesUsed[_chainNonce] = true;

    // `payable` so a relayer can fund the deallocation return an `AllocateGauge` triggers: the value lands in the
    // pre-funding pool. Value on any other type just tops the pool up, recoverable with `withdrawNative`.

    if (_msgType == MessageType.AllocateChain) {
      _handleAllocateChain(_chainNonce, _body);
    } else if (_msgType == MessageType.AllocateGauge) {
      _handleAllocateGauge(_chainNonce, _body);
    } else if (_msgType == MessageType.ClaimRewards) {
      _handleClaimRewards(_body);
    } else if (_msgType == MessageType.SetOperator) {
      _handleSetOperator(_chainNonce, _body);
    } else if (_msgType == MessageType.ReduceCooldown) {
      _handleReduceCooldown(_body);
    } else if (_msgType == MessageType.EmergencyDeallocate) {
      _handleEmergencyDeallocate(_chainNonce, _body);
    } else {
      revert UnsupportedMessageType();
    }

    emit MessageReceived(_originChainId, _chainNonce, _msgType);
  }

  /// @inheritdoc ILeafMessageOrchestrator
  function setAdapter(IMessageAdapter _adapter) external {
    if (!LEAF_VOTER.hasRole(Roles.ADAPTER_CONFIG_ROLE, msg.sender)) revert CallerNotAdapterAuthority();
    if (address(_adapter) == address(0)) revert InvalidAdapter();
    // The only authenticated route must point at root, or another chain could authenticate root-only messages.
    if (_adapter.REMOTE_CHAIN_ID() != ROOT_CHAIN_ID) revert AdapterChainIdMismatch();

    adapter = _adapter;

    emit AdapterUpdated(_adapter);
  }

  /// @inheritdoc ILeafMessageOrchestrator
  function setDeallocationGasLimit(uint256 _gasLimit) external {
    if (!LEAF_VOTER.hasRole(Roles.GAS_CONFIGURER_ROLE, msg.sender)) revert CallerNotGasConfigurer();
    if (_gasLimit == 0) revert ZeroGasLimit();

    deallocationGasLimit = _gasLimit;

    emit DeallocationGasLimitSet(_gasLimit);
  }

  /// @inheritdoc ILeafMessageOrchestrator
  function withdrawNative(uint256 _amount, address _destination) external {
    if (!LEAF_VOTER.hasRole(Roles.NATIVE_WITHDRAWER_ROLE, msg.sender)) revert CallerNotNativeWithdrawer();
    if (_destination == address(0)) revert ZeroAddress();
    // slither-disable-next-line arbitrary-send-eth
    (bool _ok,) = _destination.call{value: _amount}('');
    if (!_ok) revert WithdrawFailed();

    emit NativeWithdrawn(_destination, _amount);
  }

  /// @inheritdoc ILeafMessageOrchestrator
  function quoteDispatch(
    MessageType _msgType,
    bytes calldata _payload,
    uint256 _gasLimit,
    address _refundRecipient
  ) external view returns (uint256 _fee) {
    IMessageAdapter _adapter = adapter;
    if (address(_adapter) == address(0)) revert AdapterNotRegistered();

    // Price the wrapped envelope, not the bare payload. The header is fixed-width, so the nonce cannot move the
    // quote and a dispatch landing in between cannot invalidate it.
    _fee = _adapter.quoteMessage(
      _encodeMessage(_msgType, nonceOut + 1, _payload), _resolveGasLimit(_msgType, _gasLimit), _refundRecipient
    );
  }

  /**
   * @notice Applies an inbound `AllocateChain`: adds the tokenId's chain VP delta and, when newest, refreshes the
   *         emissions scalar.
   * @dev The delta is additive and applies once per message, so message order does not matter and an in-flight
   *      message can never bring back a budget the leaf-first `deallocate` already cleared.
   * @dev `lastChainVoteNonce` is the newest nonce seen, and it gates the `emissionsPerVP` scalar only.
   * @param _chainNonce Inbound nonce carried by the message.
   * @param _body Encoded `AllocateChainMessage` body.
   */
  function _handleAllocateChain(uint256 _chainNonce, bytes calldata _body) internal {
    IVoterCommon.AllocateChainMessage memory _message = abi.decode(_body, (IVoterCommon.AllocateChainMessage));

    // A message sent at or before the token's last emergency deallocation carries pre-drain state, so it must
    // bring back neither the cleared budget nor the stale scalar.
    bool _preEmergency = _chainNonce <= lastEmergencyDeallocNonce[_message.tokenId];
    uint128 _allocationDelta = _preEmergency ? 0 : _message.allocationDelta;

    // A pre-emergency nonce can sit above the newest seen, so exclude it here too.
    bool _isNewestChainVote = !_preEmergency && _chainNonce > lastChainVoteNonce;
    if (_isNewestChainVote) lastChainVoteNonce = _chainNonce;

    // Newest across chain and gauge only, so a delayed gauge vote cannot bring back an older shape.
    bool _refreshShape = !_preEmergency && _chainNonce > lastShapeNonce[_message.tokenId];
    if (_refreshShape) lastShapeNonce[_message.tokenId] = _chainNonce;

    LEAF_VOTER.applyChainAllocation({
      _tokenId: _message.tokenId,
      _allocationDelta: _allocationDelta,
      _emissionsPerVP: _message.emissionsPerVP,
      _refreshEmissionsPerVP: _isNewestChainVote,
      _refreshShape: _refreshShape,
      _snapshot: _message.snapshot
    });
  }

  /**
   * @notice Applies an inbound `AllocateGauge`: distributes the tokenId's chain budget across gauges.
   * @dev Gated by the tokenId's allocation nonce; a stale message returns without distributing.
   * @dev The leaf reverts `CooldownActive` while the cooldown runs, and a failing per-gauge checkpoint reverts too.
   *      Either way the whole message reverts, so the reduction is not spent and the transport redelivers it —
   *      safe because the message carries no voting power.
   * @dev After an emergency deallocation only the token's newest-seen nonce moves, so a vote in that gap
   *      loses its scalar refresh. Bounded: the chain is Suspended and the next message refreshes it.
   * @param _chainNonce Inbound nonce carried by the message.
   * @param _body Encoded `AllocateGaugeMessage` body.
   */
  function _handleAllocateGauge(uint256 _chainNonce, bytes calldata _body) internal {
    IVoterCommon.AllocateGaugeMessage memory _message = abi.decode(_body, (IVoterCommon.AllocateGaugeMessage));
    uint256 _tokenId = _message.tokenId;

    // Newest wins: a newer allocation already set this token's gauges, so a stale one is dropped.
    if (_chainNonce <= lastTokenIdVoteNonce[_tokenId]) {
      return;
    }
    lastTokenIdVoteNonce[_tokenId] = _chainNonce;

    bool _isNewestChainVote = _chainNonce > lastChainVoteNonce;
    if (_isNewestChainVote) lastChainVoteNonce = _chainNonce;

    // A gauge vote older than a later chain reallocation books at the current shape, not its own stale one.
    bool _refreshShape = _chainNonce > lastShapeNonce[_tokenId];
    if (_refreshShape) lastShapeNonce[_tokenId] = _chainNonce;

    // No value rides into the leaf: inbound value stays here as the pre-funding a triggered return draws from.
    // The reward checkpoints below are `LeafVoter` bookkeeping, not calls into the gauges.
    // slither-disable-next-line unused-return
    LEAF_VOTER.applyGaugeAllocations({
      _tokenId: _tokenId,
      _expiry: _message.expiry,
      _emissionsPerVP: _message.emissionsPerVP,
      _refreshEmissionsPerVP: _isNewestChainVote,
      _refreshShape: _refreshShape,
      _newSnapshot: _message.tokenSnapshot,
      _gauges: _message.allocations
    });
  }

  /**
   * @notice Claims fees and incentives from an inbound `ClaimRewards` message.
   * @dev Past the root-stamped expiry the claim is dropped with `ExpiredMessageDropped` instead of reverting:
   *      an expired message never becomes executable, so the transport nonce `route` consumed must stay spent.
   *      The recipient was fixed at dispatch, so a claim stalled past a root-side token transfer must not still
   *      pay the previous owner.
   * @param _body Encoded reward claim body.
   */
  function _handleClaimRewards(bytes calldata _body) internal {
    (
      uint256 _tokenId,
      uint48 _expiry,
      address _recipient,
      ILeafVoter.FeeClaim[] memory _feeClaims,
      ILeafVoter.IncentiveClaim[] memory _incentiveClaims
    ) = abi.decode(_body, (uint256, uint48, address, ILeafVoter.FeeClaim[], ILeafVoter.IncentiveClaim[]));

    if (_expiry < block.timestamp) {
      emit ExpiredMessageDropped(MessageType.ClaimRewards, _tokenId);
      return;
    }

    LEAF_VOTER.claimRewards(_tokenId, _recipient, _feeClaims, _incentiveClaims);
  }

  /**
   * @notice Propagates a per-tokenId operator assignment into the LeafVoter's mirror.
   * @dev Gated by the tokenId's operator nonce (`lastOperatorNonce`); a stale message returns without applying.
   * @dev Past the root-stamped expiry the assignment is dropped with `ExpiredMessageDropped` instead of reverting,
   *      but only after advancing the operator nonce: an expired message never becomes executable, and committing
   *      its nonce keeps older in-flight assignments from applying after it. A stalled assignment must not install
   *      an operator chosen before the token changed hands on root.
   * @param _chainNonce Inbound nonce carried by the message.
   * @param _body Encoded `OperatorMessage` body.
   */
  function _handleSetOperator(uint256 _chainNonce, bytes calldata _body) internal {
    IVoterCommon.OperatorMessage memory _operatorMessage = abi.decode(_body, (IVoterCommon.OperatorMessage));
    uint256 _tokenId = _operatorMessage.tokenId;

    if (_chainNonce <= lastOperatorNonce[_tokenId]) return;
    lastOperatorNonce[_tokenId] = _chainNonce;

    if (_operatorMessage.expiry < block.timestamp) {
      emit ExpiredMessageDropped(MessageType.SetOperator, _tokenId);
      return;
    }

    LEAF_VOTER.setOperator(_tokenId, _operatorMessage.operator);
  }

  /**
   * @notice Accrues a tokenId's pending cooldown reduction from an inbound `ReduceCooldown`.
   * @dev No nonce gate: reductions add up, so order does not matter and `route` already applies each message once.
   * @param _body Encoded `ReduceCooldownMessage` body.
   */
  function _handleReduceCooldown(bytes calldata _body) internal {
    IVoterCommon.ReduceCooldownMessage memory _message = abi.decode(_body, (IVoterCommon.ReduceCooldownMessage));
    LEAF_VOTER.applyCooldownReduction(_message.tokenId, _message.reduction);
  }

  /**
   * @notice Applies an inbound `EmergencyDeallocate`: clears the token's gauges and cuts its chain budget by the
   *         drained amount. Runs while the chain is Suspended.
   * @dev No ordering gate: a fixed amount is subtracted once. A post-resume delta applied after it over-subtracts,
   *      so governance must not resume until this lands — see the precondition on `IVoter.setChainStatus`.
   * @dev Advances both newest-seen nonces: the gauge one blocks a stale re-distribution, the emergency one makes
   *      `_handleAllocateChain` drop pre-drain deltas.
   * @param _chainNonce Inbound nonce carried by the message.
   * @param _body Encoded `EmergencyDeallocateMessage` body.
   */
  function _handleEmergencyDeallocate(uint256 _chainNonce, bytes calldata _body) internal {
    IVoterCommon.EmergencyDeallocateMessage memory _message =
      abi.decode(_body, (IVoterCommon.EmergencyDeallocateMessage));
    uint256 _tokenId = _message.tokenId;

    if (_chainNonce > lastTokenIdVoteNonce[_tokenId]) lastTokenIdVoteNonce[_tokenId] = _chainNonce;
    // Keep the HIGHEST emergency nonce: a late older one must not un-guard a delta a newer one already drained.
    if (_chainNonce > lastEmergencyDeallocNonce[_tokenId]) lastEmergencyDeallocNonce[_tokenId] = _chainNonce;

    LEAF_VOTER.applyEmergencyDeallocation(_tokenId, _message.amount);
  }

  /**
   * @notice Destination gas budget: the configured `deallocationGasLimit` for a `Deallocate`, `_supplied` otherwise.
   * @dev A `Deallocate` is quoted against this budget, so reading it from config keeps quote and send in sync.
   * @param _msgType Message type being dispatched or quoted.
   * @param _supplied Gas limit the caller passed.
   * @return _budget Gas limit to stamp on the message.
   */
  function _resolveGasLimit(MessageType _msgType, uint256 _supplied) internal view returns (uint256 _budget) {
    _budget = _msgType == MessageType.Deallocate ? deallocationGasLimit : _supplied;
  }
}

V3/src/bridge/MessageOrchestrator.sol

/// SPDX-License-Identifier: LicenseRef-Dromos-Restricted-Use-1.0
pragma solidity 0.8.36;

import {IMessageOrchestrator} from 'V3/interfaces/bridge/IMessageOrchestrator.sol';

/**
 * @title MessageOrchestrator
 * @notice Abstract base for the cross-chain orchestrators between the voters and the transport adapters.
 * @dev Holds only the shared header encode/decode; root and leaf add their own storage and routing.
 */
abstract contract MessageOrchestrator is IMessageOrchestrator {
  /**
   * @notice Wraps a body with the 39-byte header (`uint8 msgType` + `uint256 chainNonce` + `uint48 dispatchedAt`).
   * @dev Stamps `dispatchedAt` from the sender's clock here, so no dispatch site can omit it.
   * @param _msgType Message type to encode.
   * @param _chainNonce Chain nonce to encode.
   * @param _payload Message body to append after the header.
   * @return _message Wrapped message payload.
   */
  function _encodeMessage(
    MessageType _msgType,
    uint256 _chainNonce,
    bytes calldata _payload
  ) internal view returns (bytes memory _message) {
    _message = abi.encodePacked(uint8(_msgType), _chainNonce, uint48(block.timestamp), _payload);
  }

  /**
   * @notice Splits a wrapped payload into its header fields and body.
   * @dev Reverts `InvalidPayload` below 39 bytes, `NoneMessageType` on a zero type byte, `InvalidMessageType`
   *      above the enum max.
   * @dev Reverts `ClockBehindDispatch` while the local clock trails `dispatchedAt`, so the transport redelivers
   *      once it catches up. A chain resuming from an outage produces blocks stamped behind wall time; applying
   *      a message there would start its accrual before the sender booked it, minting claims the sender never
   *      backs.
   * @param _payload Wrapped message payload delivered by the adapter.
   * @return _msgType Decoded message type.
   * @return _chainNonce Decoded chain nonce.
   * @return _body Unwrapped body, a calldata slice.
   */
  function _decodeMessage(bytes calldata _payload)
    internal
    view
    returns (MessageType _msgType, uint256 _chainNonce, bytes calldata _body)
  {
    if (_payload.length < 39) revert InvalidPayload();
    uint8 _msgTypeByte;
    uint48 _dispatchedAt;
    assembly {
      _msgTypeByte := shr(248, calldataload(_payload.offset))
      _chainNonce := calldataload(add(_payload.offset, 1))
      _dispatchedAt := shr(208, calldataload(add(_payload.offset, 33)))
      _body.offset := add(_payload.offset, 39)
      _body.length := sub(_payload.length, 39)
    }
    if (_msgTypeByte == 0) revert NoneMessageType();
    if (_msgTypeByte > uint8(type(MessageType).max)) revert InvalidMessageType();
    if (_dispatchedAt > block.timestamp) revert ClockBehindDispatch();
    _msgType = MessageType(_msgTypeByte);
  }
}

V3/src/interfaces/bridge/ILeafMessageOrchestrator.sol

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

import {IMessageAdapter} from 'V3/interfaces/bridge/IMessageAdapter.sol';
import {IMessageOrchestrator} from 'V3/interfaces/bridge/IMessageOrchestrator.sol';
import {ILeafVoter} from 'V3/interfaces/voter/ILeafVoter.sol';

/**
 * @title ILeafMessageOrchestrator
 * @notice Leaf-side orchestrator: sends outbound messages to root and routes inbound root messages to the
 * `LeafVoter`.
 * @dev Holds the pre-funding pool that pays root-triggered deallocation returns.
 */
interface ILeafMessageOrchestrator is IMessageOrchestrator {
  /// @notice Emitted when the registered adapter for the root pair is updated.
  /// @param _current The newly registered adapter.
  event AdapterUpdated(IMessageAdapter _current);

  /// @notice Emitted when the destination gas limit for a deallocation return is set.
  /// @param _gasLimit The gas reserved for root's handler of the return.
  event DeallocationGasLimitSet(uint256 _gasLimit);

  /// @notice Emitted when pre-funding is withdrawn from the orchestrator.
  /// @param _destination Address that received the withdrawal.
  /// @param _amount Native amount withdrawn.
  event NativeWithdrawn(address indexed _destination, uint256 _amount);

  /// @notice Emitted when an inbound claim or operator message arrives past its root-stamped expiry and is dropped.
  /// @dev The message's nonces stay committed: an expired message never becomes executable, and consuming its
  ///      nonces keeps older in-flight messages from applying after it.
  /// @param _msgType Type of the dropped message.
  /// @param _tokenId veNFT id the dropped message targeted.
  event ExpiredMessageDropped(MessageType indexed _msgType, uint256 indexed _tokenId);

  /// @notice Reverts when the orchestrator is deployed with a zero `ROOT_CHAIN_ID`, which no adapter could match.
  error InvalidRootChainId();

  /// @notice Reverts when `setAdapter` is given an adapter whose `REMOTE_CHAIN_ID` is not `ROOT_CHAIN_ID`.
  error AdapterChainIdMismatch();

  /// @notice Reverts when a `Deallocate` is underfunded: the caller's value or the pool is below the quoted fee.
  error InsufficientDeallocationMessageValue();

  /// @notice Reverts when a gas-limit setter is called by an address without `GAS_CONFIGURER_ROLE`.
  error CallerNotGasConfigurer();

  /// @notice Reverts when a gas-limit setter receives zero.
  error ZeroGasLimit();

  /// @notice Reverts when `withdrawNative` is called by an address without `NATIVE_WITHDRAWER_ROLE`.
  error CallerNotNativeWithdrawer();

  /// @notice Reverts when the native transfer in `withdrawNative` fails.
  error WithdrawFailed();

  /// @notice Sets the registered adapter for the root pair. `ADAPTER_CONFIG_ROLE` on the `LeafVoter` only.
  /// @dev Reverts unless `_adapter.REMOTE_CHAIN_ID()` is `ROOT_CHAIN_ID`, so the leaf's only authenticated route
  ///      points at root and no other chain can authenticate root-only messages.
  /// @param _adapter The adapter to register for the root pair.
  function setAdapter(IMessageAdapter _adapter) external;

  /**
   * @notice Sends an outbound `Redeem` or `Deallocate` to root through the registered adapter. `LeafVoter` only.
   * @dev No status check: the `LeafVoter` enforces the status (`redeem` is `chainIsActiveOrSunset`, open only while
   *      Active or Sunset), and a `Deallocate` goes out even while Suspended so root's booking stays right
   *      ahead of an emergency deallocation.
   * @dev A `Deallocate` must cover a live adapter quote, so no configured cost can drift from the real fee.
   *      Pool-funded draws the exact quote and refunds back into the pool; otherwise the whole `msg.value` goes out.
   * @param _msgType Routing identifier consumed by the destination handler.
   * @param _payload Message body; the header is added before sending.
   * @param _gasLimit Destination gas. Ignored for `Deallocate`, which uses the configured `deallocationGasLimit`.
   * @param _refundRecipient Transport refund recipient. Ignored when `_fundFromPool` refunds into the pool.
   * @param _fundFromPool Whether to draw the quoted fee from the pre-funding pool instead of `msg.value`.
   */
  function dispatch(
    MessageType _msgType,
    bytes calldata _payload,
    uint256 _gasLimit,
    address _refundRecipient,
    bool _fundFromPool
  ) external payable;

  /// @notice Sets the destination gas limit stamped on every deallocation return. `GAS_CONFIGURER_ROLE` only.
  /// @dev `dispatch` and `quoteDispatch` both read it for `Deallocate`, so a quote is never taken against a
  ///      different budget than the send uses.
  /// @param _gasLimit New destination gas limit for deallocation returns.
  function setDeallocationGasLimit(uint256 _gasLimit) external;

  /// @notice Withdraws the pre-funding held for root-triggered deallocation returns. `NATIVE_WITHDRAWER_ROLE` only.
  /// @dev Also the recovery path for inbound message value that arrived without a deallocation to spend it on.
  /// @param _amount Native amount to withdraw.
  /// @param _destination Address that receives the withdrawal.
  function withdrawNative(uint256 _amount, address _destination) external;

  /**
   * @notice Quotes the native fee a `dispatch` with the same arguments would need.
   * @dev Prices the wrapped envelope, not the bare payload. The header is fixed-width, so the nonce cannot move the
   *      quote and a dispatch landing in between cannot invalidate it.
   * @dev Reverts `AdapterNotRegistered` if no adapter is registered.
   * @param _msgType Routing identifier the dispatch would stamp.
   * @param _payload Message body the dispatch would wrap.
   * @param _gasLimit Destination gas. Ignored for `Deallocate`, priced against `deallocationGasLimit`.
   * @param _refundRecipient Address the dispatch would name as the transport's refund recipient.
   * @return _fee Native amount the matching `dispatch` requires.
   */
  function quoteDispatch(
    MessageType _msgType,
    bytes calldata _payload,
    uint256 _gasLimit,
    address _refundRecipient
  ) external view returns (uint256 _fee);

  /// @notice Local `LeafVoter` bound to this orchestrator at deployment.
  /// @dev The only caller allowed to `dispatch`, and the source of the roles checked here.
  /// @return Local `LeafVoter`.
  function LEAF_VOTER() external view returns (ILeafVoter);

  /// @notice Chain id of root, the only chain this leaf orchestrator messages. Set at deployment.
  /// @dev `setAdapter` requires the registered adapter's `REMOTE_CHAIN_ID` to equal this.
  /// @return Root chain id.
  function ROOT_CHAIN_ID() external view returns (uint256);

  /// @notice Registered transport adapter for the root pair, or zero if none.
  /// @return Registered adapter.
  function adapter() external view returns (IMessageAdapter);

  /// @notice Destination gas limit stamped on every deallocation return, and the budget its fee is quoted against.
  /// @dev Defaults to zero at deployment. Every `Deallocate` dispatch reverts until governance configures a nonzero
  ///      limit. A root-triggered return keeps its inbound nonce and redelivers, but only until the allocation's
  ///      root-stamped expiry: configure within `allocationLifetime` of going live or in-flight votes are lost.
  /// @return _gasLimit Configured gas limit.
  function deallocationGasLimit() external view returns (uint256 _gasLimit);

  /// @notice Last outbound nonce stamped on a dispatch to root.
  /// @return _lastNonce Last outbound nonce.
  function nonceOut() external view returns (uint256 _lastNonce);

  /// @notice Whether an inbound nonce has already been consumed.
  /// @dev Single-use replay gate shared by every message type; the voting path adds its own ordering checks.
  /// @param _nonce Inbound nonce to check.
  /// @return _isUsed Whether `_nonce` has been consumed.
  function noncesUsed(uint256 _nonce) external view returns (bool _isUsed);

  /// @notice Highest inbound nonce applied to chain-level vote state.
  /// @dev Gated apart from token state, so an out-of-order message skips a stale chain update without blocking its
  ///      token allocation. Applies only when the inbound nonce is strictly greater.
  /// @return _nonce Highest nonce applied to chain-level vote state.
  function lastChainVoteNonce() external view returns (uint256 _nonce);

  /// @notice Highest inbound nonce applied to a tokenId's vote and allocation state.
  /// @dev Gated per tokenId, so a token still updates when its nonce is newer even after the chain nonce moved
  ///      past it. Applies only when the inbound nonce is strictly greater.
  /// @param _tokenId The tokenId to read.
  /// @return _nonce Highest nonce applied to the tokenId's vote state.
  function lastTokenIdVoteNonce(uint256 _tokenId) external view returns (uint256 _nonce);

  /// @notice Highest inbound nonce applied to a tokenId's operator mirror.
  /// @dev Kept apart from the vote nonce, or whichever message lands first would mark the other stale. A
  ///      `SetOperator` applies only when the inbound nonce is strictly greater.
  /// @param _tokenId The tokenId to read.
  /// @return _nonce Highest nonce applied to the tokenId's operator mirror.
  function lastOperatorNonce(uint256 _tokenId) external view returns (uint256 _nonce);

  /// @notice Inbound nonce of the tokenId's last applied `EmergencyDeallocate` message.
  /// @dev An `AllocateChain` at or below this ships a zero delta, so a message in flight when the emergency ran
  ///      cannot bring back the cleared position. Zero until the tokenId's first emergency deallocation.
  /// @param _tokenId The tokenId to read.
  /// @return _nonce Inbound nonce of the tokenId's last emergency deallocation.
  function lastEmergencyDeallocNonce(uint256 _tokenId) external view returns (uint256 _nonce);

  /// @notice Highest inbound nonce, across `AllocateChain` and `AllocateGauge`, allowed to refresh the token's shape.
  /// @dev Both types carry a shape and advance this, so a delayed gauge vote cannot bring back a shape older than a
  ///      chain reallocation that followed it; it books at the current shape instead.
  /// @param _tokenId The tokenId to read.
  /// @return _nonce Highest nonce that refreshed the tokenId's shape.
  function lastShapeNonce(uint256 _tokenId) external view returns (uint256 _nonce);
}

V3/src/interfaces/bridge/IMessageAdapter.sol

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

/**
 * @title IMessageAdapter
 * @notice Interface for transport adapters that carry payloads between `MessageOrchestrator` instances without
 * inspecting their content.
 */
interface IMessageAdapter {
  /// @notice Thrown when `sendMessage` is invoked by a caller that is not a registered orchestrator.
  error CallerNotOrchestrator();

  /// @notice Thrown when the adapter is constructed with a zero chain id.
  error InvalidChainId();

  /// @notice Thrown when a required address argument is the zero address.
  error ZeroAddress();

  /**
   * @notice Sends the payload through the transport.
   * @dev Callable only by the registered orchestrator. Forwards `msg.value` to the underlying transport as the fee.
   * Any excess over the actual fee is expected to be refunded by the transport directly to `_refundRecipient`.
   * @param _message The wrapped message body forwarded to the underlying transport.
   * @param _gasLimit Execution gas reserved for the destination handler.
   * @param _refundRecipient Address that receives native ETH refunds from the transport.
   */
  function sendMessage(bytes calldata _message, uint256 _gasLimit, address _refundRecipient) external payable;

  /**
   * @notice Transport entrypoint invoked by the underlying transport to deliver an inbound payload to the local
   * orchestrator.
   * @dev Implementations that carry an underlying transport validate the transport caller, the origin, and the
   * sender against their configured remote counterpart, then call the orchestrator with `REMOTE_CHAIN_ID` as the
   * source chain id. Implementations without a transport (e.g., `RootLocalAdapter`) may revert.
   * @dev Payable: the transport forwards the relayer's delivery value (Hyperlane's `Mailbox.process` attaches
   * `msg.value` to `handle`), and the adapter passes it through to `route`, where it lands in the orchestrator's
   * pre-funding pool.
   * @param _origin Transport-level identifier of the source chain.
   * @param _sender Trusted counterpart address as reported by the transport.
   * @param _message The wrapped message body delivered to the orchestrator's `route`.
   */
  function handle(uint32 _origin, bytes32 _sender, bytes calldata _message) external payable;

  /**
   * @notice Quotes the transport fee `sendMessage` would charge for the same inputs.
   * @dev Takes the identical arguments to `sendMessage` on purpose: the underlying transport prices the wrapped
   * message and the destination gas budget together, so a quote taken with different arguments is not the fee
   * the send will cost. Callers that quote-then-send in the same transaction get an exact figure; the
   * fee-less local adapter quotes zero.
   * @param _message The wrapped message body that would be forwarded to the underlying transport.
   * @param _gasLimit Execution gas that would be reserved for the destination handler.
   * @param _refundRecipient Address that would receive native ETH refunds from the transport.
   * @return _fee Native amount `sendMessage` requires for these inputs.
   */
  function quoteMessage(
    bytes calldata _message,
    uint256 _gasLimit,
    address _refundRecipient
  ) external view returns (uint256 _fee);

  /**
   * @notice Updates the stored remote adapter address.
   * @dev Implementations that carry a remote counterpart gate this entrypoint behind the adapter authority and reject
   * the zero value. Implementations without a remote counterpart (e.g., `RootLocalAdapter`) may revert.
   * @param _remoteAdapter The new counterpart adapter on the remote chain.
   */
  function setRemoteAdapter(bytes32 _remoteAdapter) external;

  /**
   * @notice Chain id this adapter is bound to. Read by the orchestrator at registration time to verify the
   * adapter is wired to the chain it is being registered for.
   * @return _chainId Chain id of the counterpart chain (or the local chain id for the local adapter on root).
   */
  function REMOTE_CHAIN_ID() external view returns (uint256 _chainId);
}

V3/src/interfaces/bridge/IMessageOrchestrator.sol

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

/**
 * @title IMessageOrchestrator
 * @notice Shared inbound entrypoint of every orchestrator. Registered adapters call `route`, which checks the caller
 * and the nonce, then hands the body to a typed handler.
 */
interface IMessageOrchestrator {
  /**
   * @notice Routing identifier stamped into the message header and read to pick the typed handler.
   * @param None Zero-default guard, rejected at decode so an empty payload cannot pass as the first real type.
   * @param AllocateChain Root to leaf — sets a tokenId's chain-level VP budget and the chain emissions scalar.
   * @param AllocateGauge Root to leaf — distributes a chain budget across gauges; cooldown-gated on the leaf.
   * @param ClaimRewards Root to leaf — claims fee and incentive rewards.
   * @param Redeem Leaf to root — Redeem.
   * @param SetOperator Root to leaf — propagates the per-tokenId operator assignment.
   * @param Deallocate Leaf to root — confirms a tokenId's deallocation so root credits `CHAIN0`.
   * @param ReduceCooldown Root to leaf — accrues a tokenId's pending cooldown reduction.
   * @param EmergencyDeallocate Root to leaf — clears a tokenId's gauges and cuts its chain budget by the drained
   * amount, so a Suspended chain re-syncs when it is next reachable.
   */
  enum MessageType {
    None,
    AllocateChain,
    AllocateGauge,
    ClaimRewards,
    Redeem,
    SetOperator,
    Deallocate,
    ReduceCooldown,
    EmergencyDeallocate
  }

  /// @notice Emitted when an outbound message is handed to a transport adapter and its nonce is stamped.
  /// @param _chainId Destination chain id.
  /// @param _chainNonce Outbound nonce stamped on this message.
  /// @param _msgType Routing identifier carried by the message.
  event MessageDispatched(uint256 indexed _chainId, uint256 _chainNonce, MessageType _msgType);

  /// @notice Emitted when an inbound message is accepted and its nonce is consumed.
  /// @param _chainId Source chain id.
  /// @param _chainNonce Nonce stamped by the source orchestrator.
  /// @param _msgType Routing identifier carried by the message.
  event MessageReceived(uint256 indexed _chainId, uint256 _chainNonce, MessageType _msgType);

  /// @notice Reverts when the inbound payload is too short to contain the wrapped header.
  error InvalidPayload();

  /// @notice Reverts when the inbound message type byte is above the `MessageType` enum range.
  error InvalidMessageType();

  /// @notice Reverts when the inbound message type byte is the `None` zero value, never a routable type.
  error NoneMessageType();

  /// @notice Reverts when a supplied address parameter is the zero address.
  error ZeroAddress();

  /// @notice Reverts when `dispatch` is called and no adapter is registered for the destination.
  error AdapterNotRegistered();

  /// @notice Reverts when `dispatch` is called by anyone other than the local voter contract.
  error CallerNotAuthorized();

  /// @notice Reverts when a `MessageType` is not routable in the current direction.
  error UnsupportedMessageType();

  /// @notice Reverts when `route` is called by anyone other than the registered adapter.
  error CallerNotAdapter();

  /// @notice Reverts when the inbound `chainNonce` has already been consumed.
  error NonceAlreadyUsed();

  /// @notice Reverts while the local clock trails the message's `dispatchedAt`; the transport redelivers once it
  ///         catches up, so a chain resuming from an outage cannot start accrual before the sender booked it.
  error ClockBehindDispatch();

  /// @notice Reverts when an adapter setter is called without `ADAPTER_CONFIG_ROLE` on the local voter.
  error CallerNotAdapterAuthority();

  /// @notice Reverts when `setAdapter` is invoked with the zero address.
  error InvalidAdapter();

  /**
   * @notice Routes a message delivered by a registered adapter to the orchestrator's typed handler.
   * @dev Registered adapter only. Nonces are single-use. Root rejects a `Redeem` from a suspended origin but still
   *      takes a `Deallocate`; the leaf routes while suspended so held root messages keep applying.
   * @dev `payable` so a relayer can send a deallocation return fee: on the leaf it lands in the pre-funding pool
   *      that pays the return. Root has no use for inbound value.
   * @param _originChainId Source chain id, supplied by the adapter from its `REMOTE_CHAIN_ID`.
   * @param _payload The wrapped message to decode and route.
   */
  function route(uint256 _originChainId, bytes calldata _payload) external payable;
}

V3/src/interfaces/factories/IFactoryRegistry.sol

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

/**
 * @title IFactoryRegistry
 * @notice Per-chain approval gate for factories and relationship graph of the
 *         protocol. Tracks which gauge factories and target factories may
 *         participate on the chain, records how gauges, targets, factories
 *         and rewards contracts relate and holds the meta router allowlist.
 */
interface IFactoryRegistry {
  /**
   * @notice Emitted when a gauge factory is registered into the approval set.
   * @param _gaugeFactory The registered gauge factory.
   */
  event GaugeFactoryRegistered(address indexed _gaugeFactory);

  /**
   * @notice Emitted when a gauge factory and a target factory are linked.
   * @param _gaugeFactory The linked gauge factory.
   * @param _targetFactory The target factory the gauge factory serves.
   */
  event FactoriesLinked(address indexed _gaugeFactory, address indexed _targetFactory);

  /**
   * @notice Emitted when a gauge factory is removed from the approval set.
   * @param _gaugeFactory The unregistered gauge factory.
   */
  event GaugeFactoryUnregistered(address indexed _gaugeFactory);

  /**
   * @notice Emitted when a target factory is registered into the approval set.
   * @param _targetFactory The registered target factory.
   */
  event TargetFactoryRegistered(address indexed _targetFactory);

  /**
   * @notice Emitted when a target factory is removed from the approval set.
   * @param _targetFactory The unregistered target factory.
   */
  event TargetFactoryUnregistered(address indexed _targetFactory);

  /**
   * @notice Emitted when a target factory records a freshly deployed target.
   * @param _target The recorded target.
   * @param _targetFactory The target factory that deployed the target.
   */
  event TargetCreated(address indexed _target, address indexed _targetFactory);

  /**
   * @notice Emitted when the GaugeManager records a freshly created gauge.
   * @param _gauge The recorded gauge.
   * @param _gaugeFactory The gauge factory that deployed the gauge.
   * @param _target The target the gauge points at.
   * @param _rewards The gauge's rewards contract.
   */
  event GaugeRegistered(
    address indexed _gauge, address indexed _gaugeFactory, address indexed _target, address _rewards
  );

  /**
   * @notice Emitted when the TokenRegistry pointer is updated.
   * @param _tokenRegistry The new TokenRegistry.
   */
  event TokenRegistrySet(address indexed _tokenRegistry);

  /**
   * @notice Emitted when the LeafVoter is wired in.
   * @param _leafVoter The LeafVoter address.
   */
  event LeafVoterSet(address indexed _leafVoter);

  /**
   * @notice Emitted when the target factory admin is set.
   * @param _targetFactoryAdmin The new target factory admin.
   */
  event TargetFactoryAdminSet(address indexed _targetFactoryAdmin);

  /**
   * @notice Emitted when a meta router is registered into the approval set.
   * @param _metaRouter The registered meta router.
   */
  event MetaRouterRegistered(address indexed _metaRouter);

  /**
   * @notice Emitted when a meta router is removed from the approval set.
   * @param _metaRouter The unregistered meta router.
   */
  event MetaRouterUnregistered(address indexed _metaRouter);

  /**
   * @notice Thrown when the caller lacks the required authorization.
   */
  error NotAuthorized();

  /**
   * @notice Thrown when a zero address is invalid.
   */
  error ZeroAddress();

  /**
   * @notice Thrown when registering an entry already in its approval set.
   */
  error AlreadyRegistered();

  /**
   * @notice Thrown when unregistering an entry not in its approval set.
   */
  error NotRegistered();

  /**
   * @notice Thrown when a target factory required by the operation is not in the approval set.
   */
  error TargetFactoryNotRegistered();

  /**
   * @notice Thrown when a gauge factory required by the operation is not in the approval set.
   */
  error GaugeFactoryNotRegistered();

  /**
   * @notice Thrown when registering a target already recorded in the registry.
   */
  error TargetAlreadyRecorded();

  /**
   * @notice Thrown when registering a gauge already recorded in the registry.
   */
  error GaugeAlreadyRecorded();

  /**
   * @notice Thrown when registering a gauge with a rewards contract already recorded for another gauge.
   */
  error RewardsAlreadyRecorded();

  /**
   * @notice Thrown when adding an entry already present in a factory enumeration.
   */
  error AlreadyEnumerated();

  /**
   * @notice Thrown when linking a gauge to a target not recorded in the registry.
   */
  error TargetNotRecorded();

  /**
   * @notice Thrown when linking a gauge to a target already linked to a gauge.
   */
  error TargetAlreadyLinked();

  /**
   * @notice Thrown when linking a gauge to a target not deployed by its factory's linked target factory.
   */
  error TargetFactoryMismatch();

  /**
   * @notice Thrown when registering a gauge factory against a target factory other than its linked one.
   */
  error GaugeFactoryAlreadyLinked();

  /**
   * @notice Thrown when registering a gauge factory against a target factory already linked to another gauge factory.
   */
  error TargetFactoryAlreadyLinked();

  /**
   * @notice Thrown when the operation requires a gauge factory with a linked target factory and none is recorded.
   */
  error NotLinked();

  /**
   * @notice Thrown when setting the LeafVoter after it has already been set.
   */
  error LeafVoterAlreadySet();

  /**
   * @notice Thrown when deploying with a target factory admin while the LeafVoter is provided.
   */
  error TargetFactoryAdminNotAllowed();

  /**
   * @notice Register a gauge factory and the target factory it serves as a
   *         pair, writing their permanent one to one link on first
   *         registration. The only writer of the link. Registering a
   *         previously unregistered pair reapproves it against the recorded
   *         link. The target factory may already be approved through the
   *         target factory admin, in which case this call links it to its
   *         gauge factory.
   * @dev Caller must hold FACTORY_REGISTRY_ADMIN_ROLE on the LeafVoter.
   *      Reverts on zero addresses, when either factory is linked to a
   *      different counterpart and when the gauge factory is already in its
   *      approval set.
   * @param _gaugeFactory The gauge factory to register.
   * @param _targetFactory The target factory the gauge factory serves.
   */
  function registerFactories(address _gaugeFactory, address _targetFactory) external;

  /**
   * @notice Register a target factory into the approval set without a gauge
   *         factory pair. Lets the lite launch approve pool factories before
   *         the LeafVoter and the gauge stack exist, with the gauge factory
   *         linked later through registerFactories.
   * @dev Caller must be the target factory admin. Reverts on the zero address
   *      and a target factory already in the set.
   * @param _targetFactory The target factory to register.
   */
  function registerTargetFactory(address _targetFactory) external;

  /**
   * @notice Wire the LeafVoter the registry resolves roles and the
   *         GaugeManager through. The lite launch deploys the registry before
   *         the LeafVoter, so the voter is set once by the target factory
   *         admin here instead of at construction. Wiring the voter clears
   *         the target factory admin, disabling the bootstrap role.
   * @dev Caller must be the target factory admin. Reverts on the zero address
   *      and when the LeafVoter is already set.
   * @param _leafVoter The LeafVoter on this chain.
   */
  function setLeafVoter(address _leafVoter) external;

  /**
   * @notice Update the target factory admin.
   * @dev Caller must be the target factory admin. Reverts on the zero address.
   * @param _targetFactoryAdmin The new target factory admin.
   */
  function setTargetFactoryAdmin(address _targetFactoryAdmin) external;

  /**
   * @notice Remove a gauge factory and its linked target factory from their
   *         approval sets as a pair. The link and every record the factories
   *         established keep resolving.
   * @dev Caller must hold FACTORY_REGISTRY_ADMIN_ROLE on the LeafVoter.
   *      Resolves the target factory through the recorded link. Reverts when
   *      either factory is not in its approval set.
   * @param _gaugeFactory The gauge factory of the pair to unregister.
   */
  function unregisterFactories(address _gaugeFactory) external;

  /**
   * @notice Update the TokenRegistry pointer. The registry is a peripheral
   *         contract that can be replaced, so the pointer is settable.
   * @dev Caller must hold FACTORY_REGISTRY_ADMIN_ROLE on the LeafVoter.
   *      Reverts on the zero address.
   * @param _tokenRegistry The new TokenRegistry.
   */
  function setTokenRegistry(address _tokenRegistry) external;

  /**
   * @notice Add a meta router to the approval set. Multiple meta routers can
   *         be approved at once so older versions keep working while new ones
   *         roll out.
   * @dev Caller must hold FACTORY_REGISTRY_ADMIN_ROLE on the LeafVoter.
   *      Reverts on the zero address and a meta router already in the set.
   * @param _metaRouter The meta router to register.
   */
  function registerMetaRouter(address _metaRouter) external;

  /**
   * @notice Remove a meta router from the approval set.
   * @dev Caller must hold FACTORY_REGISTRY_ADMIN_ROLE on the LeafVoter.
   *      Reverts when the meta router is not in the set.
   * @param _metaRouter The meta router to unregister.
   */
  function unregisterMetaRouter(address _metaRouter) external;

  /**
   * @notice Record a freshly deployed target. Called by the target factory
   *         inside its own creation function.
   * @dev msg.sender must be a registered target factory, so a factory outside
   *      the approval set cannot deploy at all. Reverts on the zero address, a
   *      target already recorded and a target already in the factory
   *      enumeration.
   * @param _target The deployed target.
   */
  function registerTarget(address _target) external;

  /**
   * @notice Record a freshly created gauge with its factory, rewards contract
   *         and target link. Called by the GaugeManager in the creation
   *         transaction. Writes both sides of the link, which is permanent
   *         with no later write path.
   * @dev msg.sender must be the GaugeManager, resolved through the LeafVoter.
   *      The gauge factory must be
   *      registered and linked and the target recorded by that factory's
   *      linked target factory. Reverts on zero addresses, a gauge already recorded or
   *      enumerated, a rewards contract already recorded and a target already
   *      linked to a gauge, so the record is write once in every direction.
   * @param _gauge The deployed gauge.
   * @param _gaugeFactory The gauge factory that deployed it.
   * @param _rewards The gauge's rewards contract.
   * @param _target The target the gauge points at.
   */
  function registerGauge(address _gauge, address _gaugeFactory, address _rewards, address _target) external;

  /**
   * @notice True when the gauge factory is in the approval set.
   * @param _gaugeFactory The gauge factory to check.
   * @return _approved Whether the gauge factory is registered.
   */
  function isGaugeFactoryApproved(address _gaugeFactory) external view returns (bool _approved);

  /**
   * @notice True when the target factory is in the approval set.
   * @param _targetFactory The target factory to check.
   * @return _approved Whether the target factory is registered.
   */
  function isTargetFactoryApproved(address _targetFactory) external view returns (bool _approved);

  /**
   * @notice True when the meta router is in the approval set. Gauges resolve
   *         this check to allow a meta router to deposit on behalf of a user.
   * @param _metaRouter The meta router to check.
   * @return _approved Whether the meta router is registered.
   */
  function isMetaRouterApproved(address _metaRouter) external view returns (bool _approved);

  /**
   * @notice The registered gauge factories.
   * @return _factories The gauge factory approval set as an array.
   */
  function gaugeFactories() external view returns (address[] memory _factories);

  /**
   * @notice The number of registered gauge factories.
   * @return _length The gauge factory approval set member count.
   */
  function gaugeFactoriesLength() external view returns (uint256 _length);

  /**
   * @notice The registered gauge factory at an index.
   * @param _index The index to read.
   * @return _factory The member at the index, zero for an out of range index.
   */
  function gaugeFactoriesAt(uint256 _index) external view returns (address _factory);

  /**
   * @notice The registered target factories.
   * @return _factories The target factory approval set as an array.
   */
  function targetFactories() external view returns (address[] memory _factories);

  /**
   * @notice The number of registered target factories.
   * @return _length The target factory approval set member count.
   */
  function targetFactoriesLength() external view returns (uint256 _length);

  /**
   * @notice The registered target factory at an index.
   * @param _index The index to read.
   * @return _factory The member at the index, zero for an out of range index.
   */
  function targetFactoriesAt(uint256 _index) external view returns (address _factory);

  /**
   * @notice The registered meta routers.
   * @return _metaRouters The meta router approval set as an array.
   */
  function metaRouters() external view returns (address[] memory _metaRouters);

  /**
   * @notice The targets recorded by a target factory.
   * @param _factory The target factory to enumerate.
   * @return _targets The targets the factory deployed as an array.
   */
  function factoryToTargets(address _factory) external view returns (address[] memory _targets);

  /**
   * @notice The number of targets recorded by a target factory.
   * @param _factory The target factory to enumerate.
   * @return _length The recorded target count.
   */
  function factoryToTargetsLength(address _factory) external view returns (uint256 _length);

  /**
   * @notice The target recorded by a target factory at an index.
   * @param _factory The target factory to enumerate.
   * @param _index The index to read.
   * @return _target The member at the index, zero for an out of range index.
   */
  function factoryToTargetsAt(address _factory, uint256 _index) external view returns (address _target);

  /**
   * @notice The gauges recorded by a gauge factory.
   * @param _factory The gauge factory to enumerate.
   * @return _gauges The gauges the factory deployed as an array.
   */
  function factoryToGauges(address _factory) external view returns (address[] memory _gauges);

  /**
   * @notice The number of gauges recorded by a gauge factory.
   * @param _factory The gauge factory to enumerate.
   * @return _length The recorded gauge count.
   */
  function factoryToGaugesLength(address _factory) external view returns (uint256 _length);

  /**
   * @notice The gauge recorded by a gauge factory at an index.
   * @param _factory The gauge factory to enumerate.
   * @param _index The index to read.
   * @return _gauge The member at the index, zero for an out of range index.
   */
  function factoryToGaugesAt(address _factory, uint256 _index) external view returns (address _gauge);

  /**
   * @notice Emission cap for a gauge, read from the factory that deployed it.
   * @dev Returns zero when the gauge is unknown or the factory call reverts.
   *      Resolves through the recorded gauge to factory link, so unregistering
   *      a factory stops new gauges but leaves existing caps intact.
   * @param _gauge The gauge to resolve.
   * @return _cap The gauge emission cap in tokens per second.
   */
  function emissionCap(address _gauge) external view returns (uint128 _cap);

  /**
   * @notice LeafVoter on this chain. Resolves roles for every permissioned
   *         registration function and the GaugeManager for gauge recording.
   *         Set at construction in a regular deployment. In the lite launch
   *         it is zero until the target factory admin wires it in through
   *         setLeafVoter.
   * @return _leafVoter The LeafVoter address.
   */
  function leafVoter() external view returns (address _leafVoter);

  /**
   * @notice Bootstrap authority of the registry, added for the lite launch
   *         where the registry deploys before the LeafVoter. Registers target
   *         factories before the LeafVoter exists and wires the LeafVoter in
   *         once deployed.
   * @return _targetFactoryAdmin The target factory admin address, zero once
   *         the LeafVoter is set.
   */
  function targetFactoryAdmin() external view returns (address _targetFactoryAdmin);

  /**
   * @notice TokenRegistry supplying token listing checks on this chain.
   * @return _tokenRegistry The current TokenRegistry, zero during a pool-only lite launch until configured.
   */
  function tokenRegistry() external view returns (address _tokenRegistry);

  /**
   * @notice Gauge factory that deployed each gauge. Written once when the
   *         GaugeManager records the gauge.
   * @param _gauge The gauge to resolve.
   * @return _factory The deploying gauge factory, zero for an unknown gauge.
   */
  function gaugeToFactory(address _gauge) external view returns (address _factory);

  /**
   * @notice Target factory that deployed each target. Written once when the
   *         factory records the target.
   * @param _target The target to resolve.
   * @return _factory The deploying target factory, zero for an unknown target.
   */
  function targetToFactory(address _target) external view returns (address _factory);

  /**
   * @notice The target a gauge points at. Written once when the GaugeManager
   *         records the gauge, with no later write path.
   * @param _gauge The gauge to resolve.
   * @return _target The linked target, zero for a gauge with no target.
   */
  function gaugeToTarget(address _gauge) external view returns (address _target);

  /**
   * @notice The gauge over a target. Written once when the GaugeManager
   *         records the gauge, together with the forward direction, with no
   *         later write path.
   * @param _target The target to resolve.
   * @return _gauge The linked gauge, zero for a target with no gauge.
   */
  function targetToGauge(address _target) external view returns (address _gauge);

  /**
   * @notice The target factory a gauge factory serves. Written once by the
   *         pair registration entrypoint and never modified afterwards,
   *         including across reregistration.
   * @param _gaugeFactory The gauge factory to resolve.
   * @return _targetFactory The linked target factory, zero for an unlinked factory.
   */
  function gaugeFactoryToTargetFactory(address _gaugeFactory) external view returns (address _targetFactory);

  /**
   * @notice The gauge factory serving a target factory. Written once together
   *         with the forward direction and never modified afterwards,
   *         including across reregistration.
   * @param _targetFactory The target factory to resolve.
   * @return _gaugeFactory The linked gauge factory, zero for an unlinked factory.
   */
  function targetFactoryToGaugeFactory(address _targetFactory) external view returns (address _gaugeFactory);

  /**
   * @notice Rewards contract escrowing fees and incentives for each gauge.
   *         Written once when the GaugeManager records the gauge.
   * @param _gauge The gauge to resolve.
   * @return _rewards The rewards contract, zero for an unknown gauge.
   */
  function gaugeToRewards(address _gauge) external view returns (address _rewards);

  /**
   * @notice Gauge behind each rewards contract. Written once when the
   *         GaugeManager records the gauge, together with the forward
   *         direction. Rewards contracts carry no gauge reference, so this is
   *         the only on-chain path from a rewards contract back to its gauge.
   * @param _rewards The rewards contract to resolve.
   * @return _gauge The recorded gauge, zero for an unknown rewards contract.
   */
  function rewardsToGauge(address _rewards) external view returns (address _gauge);
}

V3/src/interfaces/token/IBaseTokenExtensions.sol

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

/// @title IBaseTokenExtensions
/// @notice Interface for token custom behavior shared by every protocol token.
interface IBaseTokenExtensions {
  /// @notice Thrown when an address parameter is the zero address.
  error ZeroAddress();
}

V3/src/interfaces/token/IReceiptTokenExtensions.sol

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

import {IBaseTokenExtensions} from 'V3/interfaces/token/IBaseTokenExtensions.sol';

/// @title IReceiptTokenExtensions
/// @notice Interface for ReceiptToken custom behavior not covered by the ERC20 interface.
interface IReceiptTokenExtensions is IBaseTokenExtensions {
  /// @notice Thrown when a caller other than the leaf voter tries to mint or burn tokens.
  error NotLeafVoter();

  /// @notice Mints receipt tokens to an account.
  /// @param _to The account that receives the minted tokens.
  /// @param _amount The amount of tokens to mint.
  function mint(address _to, uint256 _amount) external;

  /// @notice Burns receipt tokens from an account.
  /// @param _from The account whose tokens are burned.
  /// @param _amount The amount of tokens to burn.
  function burn(address _from, uint256 _amount) external;

  /// @notice Returns the leaf voter address.
  /// @return _leafVoter The address allowed to mint and burn receipt tokens.
  function LEAF_VOTER() external view returns (address _leafVoter);
}

V3/src/interfaces/voter/ILeafVoter.sol

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

import {IAccessControl} from '@openzeppelin/contracts/access/IAccessControl.sol';

import {ILeafMessageOrchestrator} from 'V3/interfaces/bridge/ILeafMessageOrchestrator.sol';
import {IFactoryRegistry} from 'V3/interfaces/factories/IFactoryRegistry.sol';
import {IReceiptTokenExtensions as IReceiptToken} from 'V3/interfaces/token/IReceiptTokenExtensions.sol';
import {IVoterCommon} from 'V3/interfaces/voter/IVoterCommon.sol';

/**
 * @title ILeafVoter
 * @notice Leaf-chain Voter: turns per-chain reward rates and per-tokenId allocations into per-gauge emission
 *         rates, and exposes the claim surface for gauges and the redeem surface for `ReceiptToken` holders.
 * @dev Root drives two paths through the Leaf MessageOrchestrator: `applyChainAllocation` sets the chain budget
 *      and emissions scalar (no cooldown), `applyGaugeAllocations` spreads it over gauges (cooldown per chain).
 * @dev An operator drives local redistributions through `allocateGauges`. Settlement state advances lazily.
 */
interface ILeafVoter is IVoterCommon, IAccessControl {
  /*//////////////////////////////////////////////////////////////
                                 STRUCTS
  //////////////////////////////////////////////////////////////*/

  /**
   * @notice Operational roles and fee collection gas initialized with the voter.
   * @dev Zero operational holders leave their role unassigned. A nonzero bootstrap admin holds only the
   *      factory registry and module admin roles while later deployment units register their components.
   * @param voterConfigurer Initial voter configuration role holder.
   * @param tokenWhitelister Initial token whitelist role holder.
   * @param chainStatusAuthority Initial chain status role holder.
   * @param factoryRegistryAdmin Initial factory registry admin role holder.
   * @param moduleAdmin Initial module admin role holder.
   * @param gasConfigurer Initial gas configuration role holder.
   * @param nativeWithdrawer Initial native withdrawal role holder.
   * @param bootstrapAdmin Temporary factory registry and module admin role holder, or zero.
   * @param collectFeesGasLimit Gas forwarded when a rewards manager collects gauge fees.
   */
  struct InitialConfiguration {
    address voterConfigurer;
    address tokenWhitelister;
    address chainStatusAuthority;
    address factoryRegistryAdmin;
    address moduleAdmin;
    address gasConfigurer;
    address nativeWithdrawer;
    address bootstrapAdmin;
    uint256 collectFeesGasLimit;
  }

  /**
   * @notice Dependencies, authorities and static configuration seeded during voter deployment.
   * @param governor Initial governance role holder.
   * @param configAdmin Initial configuration admin role holder.
   * @param leafMessageOrchestrator Local messaging orchestrator.
   * @param receiptToken Receipt token burned when emissions are redeemed.
   * @param factoryRegistry Registry resolving gauge factories and rewards.
   * @param gaugeManager Manager authorized to register and activate gauges.
   * @param allocationCooldown Minimum duration between local allocations.
   * @param minIncentiveDuration Minimum duration for incentive programs.
   * @param maxGauges Maximum gauges in a local allocation.
   * @param adapterAuthority Initial transport configuration role holder.
   * @param emissionsHandler Handler delivering minted emissions.
   * @param emergencyCouncil Initial emergency authority.
   * @param initialConfiguration Operational holders, registration bootstrap admin and fee collection gas.
   */
  struct ConstructorParams {
    address governor;
    address configAdmin;
    address leafMessageOrchestrator;
    address receiptToken;
    address factoryRegistry;
    address gaugeManager;
    uint48 allocationCooldown;
    uint48 minIncentiveDuration;
    uint256 maxGauges;
    address adapterAuthority;
    address emissionsHandler;
    address emergencyCouncil;
    InitialConfiguration initialConfiguration;
  }

  /**
   * @notice Per-gauge settlement state, kept in one mapping so `_settleGauge` touches contiguous slots.
   * @param ceiling Cumulative effective share credited to the gauge; only ever increases.
   * @param claimed Cumulative emissions minted by claims; only ever increases, capped at `ceiling - surplus`.
   * @param lastSettlement Timestamp of this gauge's last settlement.
   * @param isRegistered Produced by an approved factory; gates routing and makes `settleGauge` a no-op if unset.
   * @param isActivated Registered gauges start inactive and route as unregistered until this flips.
   * @param surplus Cumulative forfeited surplus, clamped per report; `ceiling >= claimed + surplus` always holds.
   * @param lastIndex Chain `index` at this gauge's last settlement.
   * @param lastTimeIndex Chain `timeIndex` at this gauge's last settlement.
   * @param point Decaying weight, resolved through `gaugeSlopeChanges` during settlement.
   */
  struct GaugeState {
    uint128 ceiling;
    uint128 claimed;
    uint48 lastSettlement;
    bool isRegistered;
    bool isActivated;
    uint128 surplus;
    uint256 lastIndex;
    uint256 lastTimeIndex;
    Point point;
  }

  /**
   * @notice Packed per-tokenId allocation state; the gating fields share one slot.
   * @param operator Address authorized to run the local `allocateGauges` for this tokenId.
   * @param lastAllocated Timestamp of the last allocation; the cooldown counts from here.
   * @param canVoteForZeroCapGauges Whether the tokenId may route weight onto activated gauges whose emission
   *                                cap is zero.
   * @param chainAllocation Chain budget the tokenId may distribute, from its last root allocation.
   */
  struct TokenState {
    address operator;
    uint48 lastAllocated;
    bool canVoteForZeroCapGauges;
    uint128 chainAllocation;
  }

  /**
   * @notice Per-gauge checkpoint entry returned by `_processAllocation` to drive the reward checkpoint.
   * @dev Self-contained: checkpoints are external calls in a loop, so storage is not re-read between them.
   * @dev `ZERO_GAUGE` never appears in the array.
   * @param gauge Gauge this entry checkpoints.
   * @param allocated Allocation checkpointed against, captured at record time so reentrancy cannot change it.
   * @param data Opaque payload for the reward checkpoint; empty when the entry only clears a position (zero).
   */
  struct CheckpointData {
    address gauge;
    uint128 allocated;
    bytes data;
  }

  /**
   * @notice Fee claim request forwarded through the LeafVoter.
   * @param votingRewardsManager VotingRewardsManager to claim fees from.
   * @param maxCheckpoints Maximum number of user checkpoints to process.
   */
  struct FeeClaim {
    address votingRewardsManager;
    uint256 maxCheckpoints;
  }

  /**
   * @notice Incentive claim request forwarded through the LeafVoter.
   * @param votingRewardsManager VotingRewardsManager to claim incentives from.
   * @param programId Incentive program ID to claim from.
   * @param maxCheckpoints Maximum number of user checkpoints to process.
   */
  struct IncentiveClaim {
    address votingRewardsManager;
    uint256 programId;
    uint256 maxCheckpoints;
  }

  /**
   * @notice Mutable context threaded by memory reference through one `_processAllocation` pass.
   * @param tokenId The tokenId being processed.
   * @param oldSnapshot Token state at entry; unwinds resolve against its `stakeEnd`.
   * @param newSnapshot Incoming token state; applies resolve against its `stakeEnd`.
   * @param expired True when the new stake already expired at `lastSettlement`; skips the apply side.
   * @param canVoteForZeroCapGauges Read once from the token state; lets `_processGauge` skip the emission cap
   *                                gate instead of redirecting the weight to `ZERO_GAUGE`.
   * @param list Result entries, sized to the union upper bound and trimmed at return.
   * @param entryCount Number of entries written to `list` so far.
   * @param bookedAmount Weight actually booked on real gauges; everything else parks on `ZERO_GAUGE`.
   * @param deallocAmount Weight routed to `DEALLOC_GAUGE`, returned to root after the pass; never persisted.
   */
  struct AllocationContext {
    uint256 tokenId;
    TokenSnapshot oldSnapshot;
    TokenSnapshot newSnapshot;
    bool expired;
    bool canVoteForZeroCapGauges;
    CheckpointData[] list;
    uint256 entryCount;
    uint128 bookedAmount;
    uint128 deallocAmount;
  }

  /*//////////////////////////////////////////////////////////////
                                 EVENTS
  //////////////////////////////////////////////////////////////*/

  /**
   * @notice Emitted when the gas limit used to flush gauge fees is set.
   * @param _gasLimit New gas limit shared by this chain's reward managers.
   */
  event CollectFeesGasLimitSet(uint256 _gasLimit);

  /**
   * @notice Emitted when a gauge completes a claim through `mintEmissions`.
   * @param _gauge Gauge that invoked `mintEmissions`.
   * @param _recipients Recipients passed by the gauge, typically the LP and the referral leg.
   * @param _amounts Per-leg amounts of `ReceiptToken` allocated to each recipient.
   */
  event EmissionsMinted(address indexed _gauge, address[] _recipients, uint128[] _amounts);

  /**
   * @notice Emitted when `ReceiptToken` is redeemed and the `Redeem` message is dispatched to root.
   * @param _redeemer Address whose `ReceiptToken` was burned.
   * @param _recipient Address that receives the minted `TOKEN` on root.
   * @param _amount Amount burned, equal to the `TOKEN` to mint on root.
   */
  event Redeemed(address indexed _redeemer, address indexed _recipient, uint256 _amount);

  /**
   * @notice Emitted when a fee claim targets an unregistered VotingRewardsManager and the LeafVoter continues.
   * @param _tokenId The veNFT token ID whose fee claim failed.
   * @param _votingRewardsManager VotingRewardsManager targeted by the failed fee claim.
   * @param _maxCheckpoints Maximum number of user checkpoints requested for the failed fee claim.
   */
  event FeeClaimFailed(uint256 indexed _tokenId, address indexed _votingRewardsManager, uint256 _maxCheckpoints);

  /**
   * @notice Emitted when a forwarded fee claim completes without reverting.
   * @param _tokenId The veNFT token ID whose fee claim succeeded.
   * @param _votingRewardsManager VotingRewardsManager targeted by the successful fee claim.
   * @param _recipient Address that received any claimed fees.
   * @param _maxCheckpoints Maximum number of user checkpoints requested for the fee claim.
   */
  event FeeClaimSucceeded(
    uint256 indexed _tokenId, address indexed _votingRewardsManager, address indexed _recipient, uint256 _maxCheckpoints
  );

  /**
   * @notice Emitted when an incentive claim targets an unregistered VotingRewardsManager and the LeafVoter continues.
   * @param _tokenId The veNFT token ID whose incentive claim failed.
   * @param _votingRewardsManager VotingRewardsManager targeted by the failed incentive claim.
   * @param _programId Incentive program ID whose claim failed.
   * @param _maxCheckpoints Maximum number of user checkpoints requested for the failed incentive claim.
   */
  event IncentiveClaimFailed(
    uint256 indexed _tokenId, address indexed _votingRewardsManager, uint256 indexed _programId, uint256 _maxCheckpoints
  );

  /**
   * @notice Emitted when a forwarded incentive claim completes without reverting.
   * @param _tokenId The veNFT token ID whose incentive claim succeeded.
   * @param _votingRewardsManager VotingRewardsManager targeted by the successful incentive claim.
   * @param _programId Incentive program ID whose claim succeeded.
   * @param _recipient Address that received any claimed incentives.
   * @param _maxCheckpoints Maximum number of user checkpoints requested for the incentive claim.
   */
  event IncentiveClaimSucceeded(
    uint256 indexed _tokenId,
    address indexed _votingRewardsManager,
    uint256 indexed _programId,
    address _recipient,
    uint256 _maxCheckpoints
  );

  /**
   * @notice Emitted when a token's parked `DEALLOC_GAUGE` balance is drained and sent back to root.
   * @param _tokenId veNFT id whose parked voting power was deallocated.
   * @param _amount Voting power returned to root's `CHAIN0`.
   */
  event Deallocated(uint256 indexed _tokenId, uint128 _amount);

  /**
   * @notice Emitted when an `EmergencyDeallocate` message re-syncs a token's position with root.
   * @param _tokenId veNFT id whose position on the chain was reduced.
   */
  event EmergencyDeallocationApplied(uint256 indexed _tokenId);

  /**
   * @notice Emitted when a gauge's settlement cursor advances.
   * @dev Shares cover the entire settled interval, summed across its weekly segments. Already settled gauges
   *      emit nothing. `ZERO_GAUGE` has a zero cap and credits its entire allocated share to surplus.
   * @param _gauge Gauge whose accrued emissions were settled.
   * @param _effectiveShare Emissions credited to the gauge during this settlement, in raw TOKEN units.
   * @param _surplusDelta Cap excess added to the chain surplus during this settlement, in raw TOKEN units.
   * @param _cap Resolved per-second emission cap used throughout the settlement, in raw TOKEN units.
   * @param _gaugeWeight Voting power at the settlement timestamp after any defensive clamp, before allocation changes.
   */
  event GaugeCapSettled(
    address indexed _gauge, uint128 _effectiveShare, uint128 _surplusDelta, uint128 _cap, uint256 _gaugeWeight
  );

  /**
   * @notice Emitted when `_walkGauge` clamps a sub-zero resolved weight; signals an ordering or arithmetic bug.
   * @param _gauge The gauge whose resolved weight underflowed.
   * @param _detectedWeight The negative resolved weight seen before clamping.
   */
  event GaugeWeightClamped(address indexed _gauge, int256 _detectedWeight);

  /**
   * @notice Emitted when a registered gauge forfeits surplus emissions it cannot distribute.
   * @param _gauge The gauge that forfeited the surplus.
   * @param _amount Surplus accrued after clamping, which may be less than the reported amount.
   */
  event EmissionsForfeited(address indexed _gauge, uint128 _amount);

  /**
   * @notice Emitted when the leaf message orchestrator updates a tokenId's operator.
   * @param _tokenId The tokenId whose operator was updated.
   * @param _operator The new operator address.
   */
  event OperatorSet(uint256 indexed _tokenId, address indexed _operator);

  /**
   * @notice Emitted when a `ReduceCooldown` message accrues a tokenId's cooldown reduction.
   * @param _tokenId The tokenId whose accumulated cooldown reduction increased.
   * @param _reduction Seconds added by this message.
   * @param _accumulated New total in seconds, clamped at `maxAccumulatedCooldownReduction`.
   */
  event CooldownReductionApplied(uint256 indexed _tokenId, uint48 _reduction, uint48 _accumulated);

  /**
   * @notice Emitted when a tokenId's can-vote-for-zero-cap-gauges flag is updated.
   * @param _tokenId The tokenId whose flag was updated.
   * @param _allowed The new flag value.
   */
  event CanVoteForZeroCapGaugesSet(uint256 indexed _tokenId, bool _allowed);

  /**
   * @notice Emitted when the local-voting master switch is set.
   * @param _enabled True once local `allocateGauges` is open.
   */
  event LocalVotingEnabledSet(bool _enabled);

  /**
   * @notice Emitted when the local allocation cooldown is updated.
   * @param _allocationCooldown The new cooldown duration in seconds.
   */
  event AllocationCooldownSet(uint48 _allocationCooldown);

  /**
   * @notice Emitted when the per-chain gauge-count cap is updated.
   * @param _maxGauges The new cap on gauges a tokenId may allocate to locally.
   */
  event MaxGaugesSet(uint256 _maxGauges);

  /**
   * @notice Emitted when the cap on a tokenId's accumulated cooldown reduction is updated.
   * @param _maxAccumulatedCooldownReduction New accumulation cap, in seconds.
   */
  event MaxAccumulatedCooldownReductionSet(uint48 _maxAccumulatedCooldownReduction);

  /**
   * @notice Emitted when the minimum incentive duration is updated.
   * @param _minIncentiveDuration The new minimum duration in seconds.
   */
  event MinIncentiveDurationSet(uint48 _minIncentiveDuration);

  /**
   * @notice Emitted when the chain's operational status is updated.
   * @param _status The new chain status.
   */
  event ChainStatusSet(ChainStatus _status);

  /**
   * @notice Emitted when a chain-allocation message is applied for a tokenId.
   * @param _tokenId The tokenId whose chain budget was updated.
   * @param _allocationDelta Additive delta this message applied (may be zero on a resync).
   * @param _chainAllocation The resulting chain budget.
   * @param _emissionsPerVP Stored scalar after the call, `PRECISION`-scaled; zero while `Suspended`.
   */
  event ChainAllocated(
    uint256 indexed _tokenId, uint128 _allocationDelta, uint128 _chainAllocation, uint256 _emissionsPerVP
  );

  /**
   * @notice Emitted when a tokenId's gauge distribution is applied, locally or bridged.
   * @param _tokenId The tokenId whose gauges were allocated.
   * @param _allocations Requested allocation; unroutable gauges may be redirected, so booked weight can differ.
   * @param _emissionsPerVP Stored scalar after the call, `PRECISION`-scaled; zero while `Suspended`.
   */
  event GaugesAllocated(uint256 indexed _tokenId, GaugeAllocation[] _allocations, uint256 _emissionsPerVP);

  /**
   * @notice Emitted when a gauge is registered, active or not.
   * @param gauge The registered gauge.
   * @param activated Whether the gauge activated at registration.
   * @param registrationCursor The chain `lastSettlement` the gauge's
   *                           settlement cursor was seeded from.
   */
  event GaugeRegistered(address indexed gauge, bool activated, uint48 registrationCursor);

  /**
   * @notice Emitted when a gauge is activated, either at registration or
   *         through delayed activation.
   * @param gauge The activated gauge.
   * @param activationCursor The effective activation cursor, the chain
   *                         `lastSettlement` the gauge was anchored to.
   */
  event GaugeActivated(address indexed gauge, uint48 activationCursor);

  /*//////////////////////////////////////////////////////////////
                                 ERRORS
  //////////////////////////////////////////////////////////////*/

  /// @notice Thrown when a gas limit setter receives zero.
  error ZeroGasLimit();

  /// @notice Thrown when the caller is neither the veNFT's registered operator nor the Leaf MessageOrchestrator.
  error NotAuthorized();

  /**
   * @notice Thrown when a cross-chain entrypoint is called by anything but the Leaf MessageOrchestrator.
   */
  error NotMessageOrchestrator();

  /**
   * @notice Thrown when the local `allocateGauges` is called by anything but the tokenId's operator.
   */
  error NotOperator();

  /**
   * @notice Thrown when a gauge allocation runs before the per-chain cooldown has elapsed.
   * @dev Gates on `allocationCooldown` minus the token's accumulated reduction, consumed on a passing call.
   */
  error CooldownActive();

  /**
   * @notice Thrown when the minimum incentive duration is set to zero.
   */
  error ZeroDuration();

  /**
   * @notice Thrown by `applyGaugeAllocations` past the root-stamped `expiry`; root must re-dispatch.
   */
  error AllocationExpired();

  /**
   * @notice Thrown when a gauge-lifecycle entrypoint is called by an address other than the GaugeManager.
   */
  error NotGaugeManager();

  /**
   * @notice Thrown by `registerGauge` when the gauge is already registered.
   */
  error GaugeAlreadyRegistered();

  /**
   * @notice Thrown by `activateGauge` when the gauge is already activated.
   */
  error GaugeAlreadyActivated();

  /**
   * @notice Thrown by `allocateGauges` while local voting is disabled, which is the default.
   */
  error LocalVotingDisabled();

  /**
   * @notice Thrown when a local `allocateGauges` runs before any chain allocation seeded the stake shape.
   * @dev Defense in depth: `applyChainAllocation` seeds the shape first, so this should be unreachable. It
   *      stops a distribution against the default permanent shape if that ordering ever breaks.
   */
  error StakeSnapshotMissing();

  /**
   * @notice Thrown when the allocated amounts do not exactly equal the tokenId's `chainAllocation`.
   * @dev Counts the `DEALLOC_GAUGE` sentinel and the explicit `ZERO_GAUGE` idle entry; there is no backfill.
   */
  error ChainAllocationMismatch();

  /**
   * @notice Thrown when a local allocation targets more gauges than `maxGauges`.
   * @dev The cap keeps a tokenId's gauge set within the bound root's reduction-message gas budgeting assumes.
   */
  error ExceedsMaxGauges();

  /**
   * @notice Thrown by `activateGauge` for an unregistered gauge, and by `forfeitEmissions` for a non-gauge caller.
   */
  error GaugeNotRegistered();

  /**
   * @notice Thrown when `mintEmissions` is invoked with `_recipients.length != _amounts.length`.
   */
  error ArrayLengthMismatch();

  /**
   * @notice Thrown when the redeem amount is smaller than `MIN_REDEEM_AMOUNT`.
   */
  error AmountTooLow();

  /**
   * @notice Thrown when `mintEmissions` claims more than `ceiling - claimed - surplus`.
   */
  error CeilingExceeded();

  /**
   * @notice Thrown when `mintEmissions`, `redeem` or `allocateGauges` is called while the chain status is
   *         neither `Active` nor `Sunset`.
   */
  error ChainNotActiveOrSunset();

  /*//////////////////////////////////////////////////////////////
                                EXTERNAL
  //////////////////////////////////////////////////////////////*/

  /**
   * @notice Sets gas forwarded by reward managers when flushing gauge fees.
   * @dev Requires GAS_CONFIGURER_ROLE. Must be nonzero; applies to every subsequent flush.
   * @param _gasLimit New gas limit shared by this chain's reward managers.
   */
  function setCollectFeesGasLimit(uint256 _gasLimit) external;

  /**
   * @notice Mints `ReceiptToken` to the `EmissionsHandler` and calls it back per recipient. Gauge only.
   * @dev Reverts `ChainNotActiveOrSunset` unless the chain is `Active` or `Sunset`, though the settled entitlement
   *      survives the pause. Reverts `GaugeNotRegistered` for other callers and `CeilingExceeded` above the
   *      gauge's headroom `ceiling - claimed - surplus`.
   * @dev `claimed` is raised before the mint; the callback MUST NOT rely on further `LeafVoter` writes.
   * @param _recipients Recipients for the per-leg delivery (LP, referral).
   * @param _amounts Per-leg amounts of `ReceiptToken`.
   */
  function mintEmissions(address[] calldata _recipients, uint128[] calldata _amounts) external;

  /**
   * @notice Burns the caller's `ReceiptToken` and dispatches a `Redeem` message to root to mint `TOKEN`.
   * @dev Reverts `ChainNotActiveOrSunset` unless the chain is `Active` or `Sunset`, and `AmountTooLow` below
   *      `MIN_REDEEM_AMOUNT`.
   * @dev `surplusAccrued` rides in the payload so root books it into `reportedSurplus`.
   * @param _amount Amount of `ReceiptToken` to burn and `TOKEN` to mint on root.
   * @param _recipient Address that receives the minted `TOKEN` on root.
   * @param _gasLimit Execution gas reserved for the destination handler.
   * @param _refundRecipient Address that receives native ETH refunds from the transport.
   */
  function redeem(uint256 _amount, address _recipient, uint256 _gasLimit, address _refundRecipient) external payable;

  /**
   * @notice Claims fee and incentive rewards through the LeafVoter in one transaction.
   * @dev Callable by the veNFT's registered operator or the Leaf MessageOrchestrator. Fee claims are processed
   *      before incentive claims. Unregistered managers are skipped; registered-manager reverts bubble to make an
   *      inbound claim message retryable.
   * @param _tokenId The veNFT token ID to claim for.
   * @param _recipient Address to receive the claimed rewards.
   * @param _feeClaims Fee claim requests to forward.
   * @param _incentiveClaims Incentive claim requests to forward.
   */
  function claimRewards(
    uint256 _tokenId,
    address _recipient,
    FeeClaim[] calldata _feeClaims,
    IncentiveClaim[] calldata _incentiveClaims
  ) external;

  /**
   * @notice Applies a chain-level allocation from root. Leaf MessageOrchestrator only.
   * @dev Additive, never an overwrite, so it cannot resurrect a budget `deallocate` already removed. Carries no
   *      gauges, is never cooldown-gated, and never reverts on a well-formed call. Runs while `Suspended` with
   *      the scalar forced to zero (root diverts that period to surplus); delta and snapshot still apply.
   * @dev While the token holds no gauge weight, the whole chain budget re-parks on `ZERO_GAUGE` anchored at the
   *      latest shape, so a park whose stored shape expired revives on the next message, poke included.
   * @param _tokenId Originating tokenId.
   * @param _allocationDelta Voting power added to the tokenId's chain budget (always an increase).
   * @param _emissionsPerVP New global emissions per voting power, `PRECISION`-scaled; zero while `Suspended`.
   * @param _refreshEmissionsPerVP Newest chain allocation seen; only then is `_emissionsPerVP` written.
   * @param _refreshShape Newest shape the token has seen; only then is `latestTokenSnapshot` updated.
   * @param _snapshot Live VE shape; stored as `latestTokenSnapshot` when newest.
   */
  function applyChainAllocation(
    uint256 _tokenId,
    uint128 _allocationDelta,
    uint256 _emissionsPerVP,
    bool _refreshEmissionsPerVP,
    bool _refreshShape,
    TokenSnapshot calldata _snapshot
  ) external;

  /**
   * @notice Applies a gauge distribution from root. Leaf MessageOrchestrator only.
   * @dev Full overwrite: omitted gauges are cleared and budget above `Σ _gauges` parks on `ZERO_GAUGE`.
   * @dev Reverts `CooldownActive` while the cooldown runs, so the transport redelivers later without spending
   *      the token's reduction, and `AllocationExpired` past `_expiry`.
   * @param _tokenId Originating tokenId.
   * @param _expiry Root-stamped deadline; the message expires once `block.timestamp` passes it.
   * @param _emissionsPerVP Global emissions-per-VP scalar at dispatch, `PRECISION`-scaled.
   * @param _refreshEmissionsPerVP Newest message the leaf has seen; only then is `_emissionsPerVP` written.
   * @param _refreshShape Newest shape the token has seen. If false, the vote books at the stored shape instead.
   * @param _newSnapshot Live sAERO position state at dispatch time.
   * @param _gauges Per-gauge allocations on this chain.
   * @return _callParamsList One entry per touched gauge whose reward checkpoint this call already drove.
   */
  function applyGaugeAllocations(
    uint256 _tokenId,
    uint48 _expiry,
    uint256 _emissionsPerVP,
    bool _refreshEmissionsPerVP,
    bool _refreshShape,
    TokenSnapshot calldata _newSnapshot,
    GaugeAllocation[] calldata _gauges
  ) external returns (CheckpointData[] memory _callParamsList);

  /**
   * @notice Adds `_reduction` to a tokenId's accumulated cooldown reduction. Leaf MessageOrchestrator only.
   * @dev Additive, so grants stack and order does not matter; the `uint48` add reverts on overflow.
   * @param _tokenId veNFT id whose accumulated cooldown reduction increases.
   * @param _reduction Seconds added.
   */
  function applyCooldownReduction(uint256 _tokenId, uint48 _reduction) external;

  /**
   * @notice Clears a token's gauge distribution here and cuts its chain budget. Leaf MessageOrchestrator only.
   * @dev Subtracts rather than zeroes, so order against `AllocateChain` deltas booked before the drain does not
   *      matter; the remaining budget parks on `ZERO_GAUGE`. Clamped at zero, so `_amount >= chainAllocation`
   *      is the full unwind. Runs whatever the chain status is.
   * @dev Clamping under-corrects a post-resume delta, so governance must not resume the chain until
   *      `EmergencyDeallocationApplied` signals delivery (see `IVoter.setChainStatus`).
   * @param _tokenId veNFT id whose position on the chain is reduced.
   * @param _amount Chain budget root drained; subtracted from `chainAllocation` (clamped at zero).
   */
  function applyEmergencyDeallocation(uint256 _tokenId, uint128 _amount) external;

  /**
   * @notice Sets a tokenId's operator. Leaf MessageOrchestrator only.
   * @dev Unconditional overwrite that never reverts on a well-formed call; `address(0)` clears it.
   * @param _tokenId The tokenId whose operator is being assigned.
   * @param _operator The new operator address, or `address(0)` to clear.
   */
  function setOperator(uint256 _tokenId, address _operator) external;

  /**
   * @notice Spreads the tokenId's `chainAllocation` budget across gauges. Operator only.
   * @dev Reverts `ChainNotActiveOrSunset`, `LocalVotingDisabled`, `NotOperator`, `CooldownActive`,
   *      `StakeSnapshotMissing`, `ExceedsMaxGauges`, and `ChainAllocationMismatch`. Entries must be strictly
   *      ascending with non-zero amounts. An expired stake may only submit the lone `DEALLOC_GAUGE` sentinel
   *      returning its whole budget; any other list reverts `StakeExpired`. A sunset chain accepts only that
   *      same lone sentinel; any other list, empty included, reverts `SunsetDeallocOnly`.
   * @dev `payable` because a `DEALLOC_GAUGE` entry returns that amount to root in the same call, so `msg.value`
   *      must cover the quoted transport fee (excess refunded). No sentinel, no value needed.
   * @param _tokenId The tokenId to allocate with.
   * @param _gauges Full overwrite: omitted gauges are cleared, budget above `Σ _gauges` parks on `ZERO_GAUGE`.
   */
  function allocateGauges(uint256 _tokenId, GaugeAllocation[] calldata _gauges) external payable;

  /**
   * @notice Register a gauge on the voter, initializing the gauge state that
   *         settlement and allocation read.
   * @dev GaugeManager only. Settles the chain index to `block.timestamp`, then
   *      seeds the gauge's settlement cursor from the chain cursor. Reverts on
   *      the zero address and an already-registered gauge. Relationship
   *      validation is owned by `FactoryRegistry.registerGauge` in the same
   *      transaction. Emits `GaugeRegistered`, plus `GaugeActivated` when the
   *      module activates at registration.
   * @param _gauge The gauge address to register.
   * @param _activate Whether the gauge activates at registration, from the
   *                  creating module's activation policy.
   */
  function registerGauge(address _gauge, bool _activate) external;

  /**
   * @notice Activate a registered gauge so later allocations reach it instead of `ZERO_GAUGE`. Activation is
   *         one-way.
   * @dev GaugeManager only. Settles the chain index to `block.timestamp`, then settles the gauge so its cursor
   *      advances from registration to activation. Inactive gauges are never routable, so the settled window is
   *      weightless. Reverts `GaugeNotRegistered` for an unregistered gauge and `ZERO_GAUGE`, and
   *      `GaugeAlreadyActivated` for an activated gauge. Emits `GaugeActivated` with the effective activation
   *      cursor.
   * @param _gauge The registered gauge address to activate.
   */
  function activateGauge(address _gauge) external;

  /**
   * @notice Settles the chain index and then `_gauge`, returning its cumulative reward share. Permissionless.
   * @dev Returns `0` without settling for an unregistered gauge, so it never reverts. Never calls the gauge.
   * @param _gauge The gauge to settle.
   * @return _cumulativeRewardShare Cumulative capped effective-share (TOKEN units) after settling.
   */
  function settleGauge(address _gauge) external returns (uint256 _cumulativeRewardShare);

  /**
   * @notice Forfeits surplus the caller cannot distribute (Idle Gauge, Early Exit). Registered gauge only.
   * @dev Reverts `GaugeNotRegistered`. `_amount` is clamped to the headroom `ceiling - claimed - surplus`, then
   *      added to the gauge's `surplus` and to the chain-level `surplusAccrued`.
   * @param _amount The surplus the calling gauge is forfeiting.
   */
  function forfeitEmissions(uint128 _amount) external;

  /**
   * @notice Sets whether a tokenId may route weight onto activated gauges whose emission cap is zero,
   *         positioning for fee recovery while the zero cap keeps the gauge's emissions in surplus. When unset,
   *         such allocations redirect to `ZERO_GAUGE`. Inactive gauges are never routable regardless of this
   *         flag.
   * @dev `TOKEN_WHITELIST_ROLE` only.
   * @param _tokenId The tokenId whose flag is being set.
   * @param _allowed The new flag value.
   */
  function setCanVoteForZeroCapGauges(uint256 _tokenId, bool _allowed) external;

  /**
   * @notice Opens or closes the local `allocateGauges` path. `VOTER_CONFIG_ROLE` only.
   * @dev Defaults to false; while closed `allocateGauges` reverts `LocalVotingDisabled`, bridged path unchanged.
   * @param _enabled New switch value.
   */
  function setLocalVotingEnabled(bool _enabled) external;

  /**
   * @notice Sets the minimum seconds between local allocations for a tokenId. `VOTER_CONFIG_ROLE` only.
   * @param _allocationCooldown The new cooldown duration in seconds.
   */
  function setAllocationCooldown(uint48 _allocationCooldown) external;

  /**
   * @notice Sets the cap on a tokenId's accumulated cooldown reduction. `VOTER_CONFIG_ROLE` only.
   * @dev `applyCooldownReduction` clamps here instead of reverting, so a redelivery never reverts forever.
   * @dev Zero is the default and disables reductions. Any cap at or above `allocationCooldown` is unbounded.
   * @param _maxAccumulatedCooldownReduction The new accumulation cap, in seconds.
   */
  function setMaxAccumulatedCooldownReduction(uint48 _maxAccumulatedCooldownReduction) external;

  /**
   * @notice Sets the minimum duration for new incentive programs. `VOTER_CONFIG_ROLE` only.
   * @param _minIncentiveDuration The new minimum duration in seconds.
   */
  function setMinIncentiveDuration(uint48 _minIncentiveDuration) external;

  /**
   * @notice Sets the per-chain cap on gauges a tokenId may allocate to locally. `VOTER_CONFIG_ROLE` only.
   * @dev Leaf-owned; root enforces nothing here. Zero is the default and bricks `allocateGauges`.
   * @param _maxGauges The new gauge-count cap.
   */
  function setMaxGauges(uint256 _maxGauges) external;

  /**
   * @notice Sets the chain's operational status. `CHAIN_STATUS_ROLE` only.
   * @dev Rejects a `None` target (`InvalidStatus`) and same-value writes; `Suspended` only exits to `Active`
   *      or `Sunset` and `Sunset` only exits to `Suspended` (`InvalidChainStatusTransition`). Settles the
   *      index at the old rate up to the flip; a pre-settling message can bank accrual past it, so the
   *      boundary is `max(flip, lastSettlement)`.
   * @dev Reactivating a sunset leaf routes through `Suspended` first, so the in-flight deallocation set can
   *      drain before the resume — see the procedure on `IVoter.setChainStatus`.
   * @dev Entering `Suspended` or `Sunset` forces `emissionsPerVP` to zero until the first root dispatch after
   *      a resume to `Active`. `allocateGauges`, `redeem` and `mintEmissions` stay open
   *      under `Active` and `Sunset` and close under everything else; `Deallocate` still dispatches. Flip leaf
   *      before root when suspending or sunsetting and resume root before leaf, so the gap under-emits.
   * @param _status The new chain status.
   */
  function setChainStatus(ChainStatus _status) external;

  /**
   * @notice Projects a gauge's cumulative reward share to `block.timestamp` without writing.
   * @dev Equals what `settleGauge(_gauge)` would return in this block. Returns `0` for an unregistered gauge.
   * @param _gauge The gauge to project.
   * @return _cumulativeRewardShare Projected cumulative capped effective-share (TOKEN units).
   */
  function projectedCumulativeRewardShare(address _gauge) external view returns (uint256 _cumulativeRewardShare);

  /*//////////////////////////////////////////////////////////////
                                VARIABLES
  //////////////////////////////////////////////////////////////*/

  /**
   * @notice Sink for weight aimed at gauges that cannot receive emissions; it accrues there as surplus.
   *         Allocations to unregistered or unactivated gauges, and to zero-cap gauges the tokenId is not
   *         whitelisted for, are redirected here.
   * @return _zeroGauge The sink address (`address(0)`).
   */
  function ZERO_GAUGE() external view returns (address _zeroGauge);

  /**
   * @notice Minimum redeem amount, `1_000_000` (one unit in pips), so the Splitter share cannot round to zero.
   * @return _minRedeemAmount The minimum redeem amount.
   */
  function MIN_REDEEM_AMOUNT() external view returns (uint256 _minRedeemAmount);

  /**
   * @notice Leaf-side messaging orchestrator this voter dispatches through. Set at deployment, immutable.
   * @return _orchestrator The bound leaf messaging orchestrator.
   */
  function ORCHESTRATOR() external view returns (ILeafMessageOrchestrator _orchestrator);

  /**
   * @notice `ReceiptToken` burned on redeem. Set at deployment, immutable.
   * @return _receiptToken The bound `ReceiptToken`.
   */
  function RECEIPT_TOKEN() external view returns (IReceiptToken _receiptToken);

  /**
   * @notice `EmissionsHandler` that receives `ReceiptToken` from `mintEmissions` and the callback.
   * @return _emissionsHandler Configured handler.
   */
  function EMISSIONS_HANDLER() external view returns (address _emissionsHandler);

  /**
   * @notice FactoryRegistry queried for per-gauge emission caps and reward
   *         contracts during settlement. Set at deployment, immutable.
   * @return _factoryRegistry The configured FactoryRegistry.
   */
  function FACTORY_REGISTRY() external view returns (IFactoryRegistry _factoryRegistry);

  /**
   * @notice GaugeManager authorized for the gauge-lifecycle writes,
   *         `registerGauge` and `activateGauge`. Set at deployment, immutable.
   * @return _gaugeManager The configured GaugeManager.
   */
  function GAUGE_MANAGER() external view returns (address _gaugeManager);

  /**
   * @notice Operational status, `Active` by default. `allocateGauges`, `redeem` and `mintEmissions` stay open
   *         under `Active` and `Sunset` and are blocked under every other value.
   * @return _status Current chain status.
   */
  function chainStatus() external view returns (ChainStatus _status);

  /**
   * @notice Latest emissions-per-VP scalar from root; written only on a fresh message, zero while `Suspended`
   *         or `Sunset`.
   * @return _emissionsPerVP Global emissions per unit voting power, `PRECISION`-scaled.
   */
  function emissionsPerVP() external view returns (uint256 _emissionsPerVP);

  /**
   * @notice Cumulative AERO rewards per unit of chain weight; only ever increases.
   * @return _index Current accumulator index.
   */
  function index() external view returns (uint256 _index);

  /**
   * @notice Time-weighted chain accumulator: `emissionsPerVP` integrated against absolute (unix-epoch) time,
   *         stored doubled. Paired with `index` it prices a decaying gauge's share exactly across a scalar
   *         change, matching root.
   * @return _timeIndex Current time-weighted accumulator value, doubled.
   */
  function timeIndex() external view returns (uint256 _timeIndex);

  /**
   * @notice Timestamp `index` is settled to. May be ahead of `block.timestamp` after a pre-settling message.
   * @return _ts Last chain settlement timestamp.
   */
  function lastSettlement() external view returns (uint48 _ts);

  /**
   * @notice Snapshot of `index` at each weekly boundary; per-gauge settlement reads it for per-segment shares.
   * @param _boundary Weekly-aligned timestamp.
   * @return _indexSnapshot Value of `index` snapshotted at `_boundary`.
   */
  function indexAtBoundary(uint48 _boundary) external view returns (uint256 _indexSnapshot);

  /**
   * @notice Snapshot of `timeIndex` at each weekly boundary; per-gauge settlement reads it for the slope correction.
   * @param _boundary Weekly-aligned timestamp.
   * @return _timeIndexSnapshot Value of `timeIndex` snapshotted at `_boundary`.
   */
  function timeIndexAtBoundary(uint48 _boundary) external view returns (uint256 _timeIndexSnapshot);

  /**
   * @notice Whether a gauge is activated for direct allocation routing. Cheaper than reading `gaugeStates`.
   * @param _gauge Gauge address to query.
   * @return _isActivated Whether the gauge is activated.
   */
  function isActivated(address _gauge) external view returns (bool _isActivated);

  /**
   * @notice Per-gauge settlement state.
   * @param _gauge Gauge address to query.
   * @return _ceiling Cumulative effective share credited to the gauge.
   * @return _claimed Cumulative emissions minted by the claim flow.
   * @return _lastSettlement Timestamp of the gauge's last settlement.
   * @return _isRegistered Whether the gauge was produced by an approved factory.
   * @return _isActivated Whether the gauge is activated for direct allocation routing.
   * @return _surplus Cumulative surplus attributed to the gauge.
   * @return _lastIndex Snapshot of `index` at the gauge's last settlement.
   * @return _lastTimeIndex Snapshot of `timeIndex` at the gauge's last settlement.
   * @return _point Decaying weight of the gauge.
   */
  function gaugeStates(address _gauge)
    external
    view
    returns (
      uint128 _ceiling,
      uint128 _claimed,
      uint48 _lastSettlement,
      bool _isRegistered,
      bool _isActivated,
      uint128 _surplus,
      uint256 _lastIndex,
      uint256 _lastTimeIndex,
      Point memory _point
    );

  /**
   * @notice Scheduled slope reduction for a gauge at a weekly expiry boundary.
   * @param _gauge Gauge address to query.
   * @param _expiry Expiry timestamp.
   * @return _slopeDelta Slope reduction scheduled at `_expiry`.
   */
  function gaugeSlopeChanges(address _gauge, uint48 _expiry) external view returns (int128 _slopeDelta);

  /**
   * @notice Packed per-tokenId allocation state.
   * @dev `chainAllocation` is raised by `applyChainAllocation`, cut by `applyEmergencyDeallocation` (clamped at
   *      zero), and bounds the incoming gauge sum.
   * @param _tokenId veNFT id to query.
   * @return _operator The tokenId's operator, or `address(0)` if unset.
   * @return _lastAllocated Last-allocated timestamp.
   * @return _canVoteForZeroCapGauges True when the token may route weight onto activated zero-cap gauges.
   * @return _chainAllocation Chain allocation budget for the tokenId.
   */
  function tokenStates(uint256 _tokenId)
    external
    view
    returns (address _operator, uint48 _lastAllocated, bool _canVoteForZeroCapGauges, uint128 _chainAllocation);

  /**
   * @notice Shape the token's booked gauge weight is measured with. Read by reward contracts at checkpoint.
   * @param _tokenId veNFT id to query.
   * @return _staked AERO staked in the position at dispatch time.
   * @return _stakeEnd Stake expiry; `0` for a permanent stake.
   * @return _isPermanent True for a permanent stake.
   */
  function tokenSnapshot(uint256 _tokenId) external view returns (uint128 _staked, uint48 _stakeEnd, bool _isPermanent);

  /**
   * @notice Newest root-dispatched `TokenSnapshot` for a tokenId, applied or not.
   * @dev Never behind `tokenSnapshot`; the next gauge-iterating operation consumes it and the two match again.
   * @param _tokenId veNFT id to query.
   * @return _staked AERO staked in the position at dispatch time.
   * @return _stakeEnd Stake expiry; `0` for a permanent stake.
   * @return _isPermanent True for a permanent stake.
   */
  function latestTokenSnapshot(uint256 _tokenId)
    external
    view
    returns (uint128 _staked, uint48 _stakeEnd, bool _isPermanent);

  /**
   * @notice Per-`(tokenId, effective gauge)` allocated weight; redirected weight aggregates on `ZERO_GAUGE`.
   * @param _tokenId veNFT id to query.
   * @param _gauge Effective gauge address to query.
   * @return _allocated Weight the tokenId currently has on the gauge.
   */
  function allocations(uint256 _tokenId, address _gauge) external view returns (uint128 _allocated);

  /**
   * @notice Cumulative AERO on this chain that will not be redeemed; only ever increases, sent in every REDEEM.
   * @return _surplus Cumulative surplus.
   */
  function surplusAccrued() external view returns (uint256 _surplus);

  /**
   * @notice Whether the local `allocateGauges` path is open. False until governance opens it.
   * @return _enabled Current switch value.
   */
  function localVotingEnabled() external view returns (bool _enabled);

  /**
   * @notice Minimum seconds between local allocations for a tokenId.
   * @return _cooldown Cooldown duration.
   */
  function allocationCooldown() external view returns (uint48 _cooldown);

  /**
   * @notice Cap on a tokenId's accumulated cooldown reduction. Zero, the default, disables reductions.
   * @return _maxAccumulatedCooldownReduction The accumulation cap, in seconds.
   */
  function maxAccumulatedCooldownReduction() external view returns (uint48 _maxAccumulatedCooldownReduction);

  /**
   * @notice Minimum duration for new incentive programs.
   * @return _minIncentiveDuration The minimum duration in seconds.
   */
  function minIncentiveDuration() external view returns (uint48 _minIncentiveDuration);

  /**
   * @notice Per-chain cap on gauges a tokenId may allocate to locally. Leaf-owned; root holds no equivalent.
   * @return _maxGauges The gauge-count cap.
   */
  function maxGauges() external view returns (uint256 _maxGauges);

  /**
   * @notice Reduction accrued for a tokenId, in seconds; the next allocation consumes it, clamped to the cooldown.
   * @param _tokenId veNFT id.
   * @return _reduction Accumulated reduction in seconds, or zero if none.
   */
  function accumulatedCooldownReduction(uint256 _tokenId) external view returns (uint48 _reduction);

  /*//////////////////////////////////////////////////////////////
                                  VIEWS
  //////////////////////////////////////////////////////////////*/

  /**
   * @notice Operator authorized to run the local `allocateGauges` for a tokenId.
   * @param _tokenId veNFT id to query.
   * @return _operator The tokenId's operator, or `address(0)` if unset.
   */
  function operator(uint256 _tokenId) external view returns (address _operator);

  /**
   * @notice Effective gauges the tokenId has weight on. Excludes `ZERO_GAUGE`: read parked weight with
   *         `allocations(_tokenId, ZERO_GAUGE)`.
   * @param _tokenId veNFT id to query.
   * @return _gauges The set's values as a memory array.
   */
  function allocatedGauges(uint256 _tokenId) external view returns (address[] memory _gauges);

  /**
   * @notice Returns the gas limit used by reward managers when flushing gauge fees.
   * @return _gasLimit The gauge fee collection gas limit.
   */
  function collectFeesGasLimit() external view returns (uint256 _gasLimit);
}

V3/src/interfaces/voter/IVoterCommon.sol

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

/**
 * @title IVoterCommon
 * @notice Types shared by `IVoter` (root) and `ILeafVoter` (leaf), so the same struct crosses chains unchanged.
 */
interface IVoterCommon {
  /*//////////////////////////////////////////////////////////////
                                  ENUMS
  //////////////////////////////////////////////////////////////*/

  /**
   * @notice Per-chain operational status shared by root and leaf voters.
   * @dev `None` is the enum default (0), so an unregistered chain never passes a status check; registration
   *      (root) and construction (leaf) set `Active`, and `setChainStatus` cannot set `None`. `Active` allows
   *      everything, `Paused` blocks the chain's operations.
   * @dev `Suspended` is the emissions kill switch: root rejects inbound messages and sends the chain's accrual to
   *      surplus, the leaf blocks outbound dispatch and user entrypoints but still applies root messages at rate
   *      zero, so its mirror repairs itself without accruing unfunded emissions.
   * @dev `Sunset` is the wind-down. Root stops accepting chain allocations, sends the chain's accrual to
   *      surplus like `Suspended`, and keeps processing redeems and deallocations. Gauge votes, operator
   *      updates and cooldown reductions still dispatch so booked voting power can exit through `DEALLOC_GAUGE`;
   *      the chain accrues nothing, so they move no emissions. The leaf parks its scalar at zero but keeps
   *      `allocateGauges`, `mintEmissions` and `redeem` open, so everything already earned stays claimable and
   *      redeemable. Its only exit is `Suspended`, the kill switch for a compromised or unreachable sunset
   *      chain and the mandatory first leg of a reactivation (see `IVoter.setChainStatus`).
   * @param None Uninitialized sentinel, the state of an unregistered chain.
   * @param Active Fully operational.
   * @param Paused Chain operations blocked on both sides; accrual continues.
   * @param Suspended Emissions kill switch; accrual goes to surplus and user entrypoints close.
   * @param Sunset Wind-down; accrual goes to surplus, exits stay open, chain allocations close.
   */
  enum ChainStatus {
    None,
    Active,
    Paused,
    Suspended,
    Sunset
  }

  /*//////////////////////////////////////////////////////////////
                                 STRUCTS
  //////////////////////////////////////////////////////////////*/

  /**
   * @notice Snapshot of decaying voting power at a point in time.
   * @param bias Current voting power; decays linearly.
   * @param slope Rate of decay per second.
   * @param ts Timestamp of last resolution.
   * @param permanentStakeBalance Non-decaying voting power from permanent stakes.
   */
  struct Point {
    int128 bias;
    int128 slope;
    uint48 ts;
    uint128 permanentStakeBalance;
  }

  /**
   * @notice One gauge leg of a tokenId's vote. Sent to the leaf in the dispatch payload; root keeps no copy.
   * @param gauge Target gauge address.
   * @param allocated Absolute AERO for this gauge, not a percentage; Σ within a chain equals that chain's total.
   * @param data Opaque per-gauge payload forwarded unchanged to the leaf.
   */
  struct GaugeAllocation {
    address gauge;
    uint128 allocated;
    bytes data;
  }

  /**
   * @notice VE state at dispatch, so the leaf can rebuild the tokenId's contribution shape locally.
   * @dev The leaf derives bias, slope and permanent balance from `_contribution(allocated, stakeEnd, isPermanent)`,
   *      settled at its own `block.timestamp`. `isPermanent` is the permanence discriminator, not `stakeEnd == 0`.
   * @param staked AERO staked in the veNFT at dispatch time.
   * @param stakeEnd Week-aligned stake expiry; `0` for a permanent stake.
   * @param isPermanent True for a permanent stake; the permanence signal the leaf reads.
   */
  struct TokenSnapshot {
    uint128 staked;
    uint48 stakeEnd;
    bool isPermanent;
  }

  /**
   * @notice Chain-level allocation from root to a leaf: sets the tokenId's budget on the chain and the chain's
   *         emissions scalar. No gauges and no cooldown — chain assignment always applies.
   * @dev Applied additively on the leaf, so it can never bring back a budget the leaf-first `deallocate` removed.
   *      Reductions go leaf-first through `deallocate`, never through this message.
   * @dev The MessageOrchestrator stamps `chainNonce` and `dispatchedAt` and wraps every message body below in
   *      the `(MessageType, chainNonce, dispatchedAt, bytes)` transport envelope; these structs are the
   *      Voter→Orchestrator body only.
   * @param tokenId Originating tokenId.
   * @param allocationDelta Voting power added to the token's budget here, drawn from `CHAIN0`; always an increase.
   * @param emissionsPerVP Global emissions per unit voting power, `PRECISION`-scaled; the leaf's index rate.
   * @param snapshot Live VE shape at dispatch, which anchors the token's booked shape on the leaf.
   */
  struct AllocateChainMessage {
    uint256 tokenId;
    uint128 allocationDelta;
    uint256 emissionsPerVP;
    TokenSnapshot snapshot;
  }

  /**
   * @notice Gauge distribution from root to a leaf, spreading the tokenId's chain budget across gauges.
   * @dev Cooldown-gated on the leaf: it reverts while the cooldown still runs and the transport redelivers later.
   * @param tokenId Originating tokenId.
   * @param expiry Absolute deadline stamped by root; past it the leaf reverts `AllocationExpired`.
   * @param emissionsPerVP Emissions per unit voting power, `PRECISION`-scaled; only the leaf's newest message
   *                       refreshes its scalar.
   * @param tokenSnapshot Live VE state at dispatch, used to shape each gauge's contribution.
   * @param allocations Per-gauge allocations on this chain. Empty clears the tokenId's gauge weight.
   */
  struct AllocateGaugeMessage {
    uint256 tokenId;
    uint48 expiry;
    uint256 emissionsPerVP;
    TokenSnapshot tokenSnapshot;
    GaugeAllocation[] allocations;
  }

  /**
   * @notice Cooldown reduction from root to a leaf. The leaf accrues it and the token's next gauge allocation,
   *         bridged or local, spends it clamped to `allocationCooldown`.
   * @dev Reductions accrue additively, so message order does not matter and no reduction-specific nonce gate is
   *      needed; the global replay gate applies each one exactly once.
   * @param tokenId veNFT id whose pending cooldown reduction is being increased.
   * @param reduction Seconds added to the tokenId's pending cooldown reduction on this chain.
   */
  struct ReduceCooldownMessage {
    uint256 tokenId;
    uint48 reduction;
  }

  /**
   * @notice Emergency unwind from root to a leaf after root drained `amount` from a `Suspended` chain: the leaf
   *         clears the tokenId's gauges and re-parks the remaining budget (`budget - amount`) on `ZERO_GAUGE`.
   * @dev It subtracts a fixed amount instead of zeroing, so `AllocateChain` deltas booked before the drain need
   *      no ordering gate; the leaf drops stale pre-drain deltas by message nonce.
   * @dev It over-subtracts if a POST-resume delta lands first, so resume is gated on delivery — see the
   *      precondition on `IVoter.setChainStatus`.
   * @param tokenId veNFT id whose position on the chain is being reduced.
   * @param amount Chain budget root drained to `CHAIN0`; the leaf subtracts it, clamped at zero.
   */
  struct EmergencyDeallocateMessage {
    uint256 tokenId;
    uint128 amount;
  }

  /**
   * @notice Redeem payload dispatched from a leaf to root.
   * @param amount Amount of `ReceiptToken` burned on the leaf and `TOKEN` to mint on root.
   * @param recipient Address that receives the minted `TOKEN` on root.
   * @param surplusAccrued Cumulative surplus accumulator snapshot reported by the leaf.
   */
  struct RedeemMessageBody {
    uint256 amount;
    address recipient;
    uint256 surplusAccrued;
  }

  /**
   * @notice Deallocation confirmation from a leaf to root, so root credits `CHAIN0` only once the leaf confirms.
   * @param tokenId veNFT id whose voting power was deallocated on the leaf.
   * @param amount Voting power deallocated on the leaf, to credit back to `CHAIN0` on root.
   */
  struct DeallocationMessageBody {
    uint256 tokenId;
    uint128 amount;
  }

  /**
   * @notice Operator assignment from root to a leaf, keeping the leaf's `operators[tokenId]` mirror in sync.
   * @param tokenId veNFT id whose operator is being set.
   * @param expiry Absolute deadline stamped by root; past it the leaf drops the message with
   * `ExpiredMessageDropped`.
   * @param operator New operator address. Zero clears the slot.
   */
  struct OperatorMessage {
    uint256 tokenId;
    uint48 expiry;
    address operator;
  }

  /*//////////////////////////////////////////////////////////////
                                 ERRORS
  //////////////////////////////////////////////////////////////*/

  /// @notice Thrown when `setChainStatus` is called with the chain's current status, a no-op write.
  error ChainStatusUnchanged();

  /**
   * @notice Thrown when `setChainStatus` moves a `Suspended` chain to `Paused`, or a `Sunset` chain to
   *         anything but `Suspended`. A `None` target reverts with `InvalidStatus` first.
   * @dev A `Paused` exit restarts ceiling accrual at the stored rate while the leaf still distributes nothing,
   *      and `Paused` blocks the vote pipeline, so no message could resync the leaf for that whole period.
   *      `Sunset` exits only through `Suspended`, so a reactivation always drains the in-flight deallocation
   *      set before any resume and a dead sunset chain keeps its kill switch.
   */
  error InvalidChainStatusTransition();

  /// @notice Thrown when `setChainStatus` is called with `None`, the uninitialized sentinel status.
  error InvalidStatus();

  /// @notice Thrown when a constructor receives a zero address argument.
  error ZeroAddress();

  /// @notice Thrown when the token's stake is expired.
  error StakeExpired();

  /// @notice Thrown when a vote on a sunset chain carries anything but the lone `DEALLOC_GAUGE` return.
  error SunsetDeallocOnly();

  /// @notice Thrown when an allocation entry carries a zero `allocated` amount.
  error ZeroAllocation();

  /// @notice Thrown when `msg.value` is attached but there is no return message to fund.
  error UnexpectedValue();

  /// @notice Thrown when an allocation's gauges are not strictly ascending by address, which also rejects
  ///         duplicates.
  error GaugesNotStrictlyAscending();
}

V3/src/libraries/Roles.sol

// SPDX-License-Identifier: LicenseRef-Dromos-Restricted-Use-1.0
pragma solidity 0.8.36;

/**
 * @title Roles
 * @notice Central registry of AccessControl role identifiers used by Voter and LeafVoter.
 */
library Roles {
  /// @notice Root governance authority.
  bytes32 public constant GOVERNANCE_ROLE = keccak256('GOVERNANCE_ROLE');

  /// @notice Admin of the operational config roles.
  bytes32 public constant CONFIG_ADMIN_ROLE = keccak256('CONFIG_ADMIN_ROLE');

  /// @notice Configures Voter-wide parameters.
  bytes32 public constant VOTER_CONFIG_ROLE = keccak256('VOTER_CONFIG_ROLE');

  /// @notice Registers and configures per-chain parameters.
  bytes32 public constant CHAIN_CONFIG_ROLE = keccak256('CHAIN_CONFIG_ROLE');

  /// @notice Flips per-chain status.
  bytes32 public constant CHAIN_STATUS_ROLE = keccak256('CHAIN_STATUS_ROLE');

  /// @notice Authorizes remote-adapter configuration on bridge adapters.
  bytes32 public constant ADAPTER_CONFIG_ROLE = keccak256('ADAPTER_CONFIG_ROLE');

  /// @notice Replaces the Splitter's recipient list, directing future team-share emissions.
  bytes32 public constant SPLITTER_CONFIG_ROLE = keccak256('SPLITTER_CONFIG_ROLE');

  /// @notice Whitelists tokenIds on the LeafVoter.
  bytes32 public constant TOKEN_WHITELIST_ROLE = keccak256('TOKEN_WHITELIST_ROLE');

  /// @notice Emergency actor authorized to zero a gauge's emission cap on the leaf.
  bytes32 public constant EMERGENCY_COUNCIL_ROLE = keccak256('EMERGENCY_COUNCIL_ROLE');

  /// @notice Registers and unregisters factories on the FactoryRegistry.
  bytes32 public constant FACTORY_REGISTRY_ADMIN_ROLE = keccak256('FACTORY_REGISTRY_ADMIN_ROLE');

  /// @notice Administers the GaugeManager's creation module set.
  bytes32 public constant MODULE_ADMIN_ROLE = keccak256('MODULE_ADMIN_ROLE');

  /// @notice Creates Relays on the RelayFactory.
  bytes32 public constant RELAY_DEPLOYER_ROLE = keccak256('RELAY_DEPLOYER_ROLE');

  /// @notice Configures operational gas limits, including messaging, gauge fee flushing and token symbol reads.
  bytes32 public constant GAS_CONFIGURER_ROLE = keccak256('GAS_CONFIGURER_ROLE');

  /// @notice Withdraws native currency from a contract (e.g. collected deallocation return fees on the
  ///         root Voter, or a leaf orchestrator's pre-funded return-message balance).
  bytes32 public constant NATIVE_WITHDRAWER_ROLE = keccak256('NATIVE_WITHDRAWER_ROLE');

  /// @notice Seizes token metadata NFTs on the TokenNFT.
  bytes32 public constant SEIZER_ROLE = keccak256('SEIZER_ROLE');
}

node_modules/@openzeppelin/contracts/access/IAccessControl.sol

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

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "V3/src/src/libraries/RewardsLogicLibrary.sol": {
      "RewardsLogicLibrary": "0x2b73DF2e7e957C77F1D8C01e0a71aD1fF38D6720"
    },
    "V3/src/src/libraries/LeafAllocationLibrary.sol": {
      "LeafAllocationLibrary": "0xC7E262e848fCa78C3C66Ee3c9835e4E65E3E0398"
    },
    "V3/src/src/libraries/VotingRewardsFactoryLibrary.sol": {
      "VotingRewardsFactoryLibrary": "0x1C3821772BFAAE08eE2D4ED8E2c29844CA49634e"
    }
  },
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "prague",
  "remappings": [
    "forge-std/=node_modules/forge-std/src/",
    "@hyperlane/contracts/=node_modules/@hyperlane-xyz/core/contracts/",
    "node_modules/@hyperlane-xyz/:@openzeppelin/contracts/=node_modules/@openzeppelin/contracts-v4/",
    "node_modules/@hyperlane-xyz/:@openzeppelin/contracts/=node_modules/@openzeppelin/contracts-v4/",
    "node_modules/@hyperlane-xyz/:@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable-v4/",
    "node_modules/@hyperlane-xyz/:@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable-v4/",
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
    "@openzeppelin4/contracts/=node_modules/@openzeppelin/contracts-v4/",
    "@solady/=node_modules/solady/src/",
    "@nomad-xyz/src/=node_modules/@nomad-xyz/excessively-safe-call/src/",
    "V3/=V3/src/",
    "V3-script/=V3/script/",
    "V3-test/=V3/test/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.