Skip to content
Verified contractExactMIT

StakingMonitorView

Address0xbe1e75124c7f07d5b681839c42d8e751f0d0fcfc
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,263,339
Creation transaction
0xeefdba06c1…a05bb1c04e

src/StakingMonitorView.sol

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

import {Position, StakingViewLib} from "./lib/StakingViewLib.sol";

/// @dev Minimal external surface of TegridyStaking that the monitor sibling needs to
///      reconstruct off-chain views. Each method maps to a `public` storage variable on
///      TegridyStaking (auto-generated getter) — no new accessors required on the host.
interface ITegridyStakingMonitorRead {
    // Position storage — public mapping auto-getter returns fields in declaration order.
    function positions(uint256 tokenId) external view returns (
        uint256 amount,
        uint256 boostedAmount,
        int256 rewardDebt,
        uint64 lockEnd,
        uint16 boostBps,
        uint32 lockDuration,
        bool autoMaxLock,
        bool hasJbacBoost,
        uint64 stakeTimestamp,
        uint256 jbacTokenId,
        bool jbacDeposited
    );
    // Reward-math scalars.
    function rewardPerTokenStored() external view returns (uint256);
    function lastUpdateTime() external view returns (uint256);
    function rewardRate() external view returns (uint256);
    function totalBoostedStake() external view returns (uint256);
    function totalStaked() external view returns (uint256);
    function totalUnsettledRewards() external view returns (uint256);
    // Reward token (the auto-getter for the public IERC20 immutable returns the address).
    function rewardToken() external view returns (address);
    // Stake-cap scalar (public state var auto-getter) for the cap-utilization views.
    function maxTotalStaked() external view returns (uint256);
}

interface IMonitorERC20Balance {
    function balanceOf(address account) external view returns (uint256);
}

/// @title  StakingMonitorView
/// @notice EIP-170 sibling for TegridyStaking: re-exposes the heaviest off-chain views
///         (`earned`, `getPosition`) so the host can drop them from its bytecode. The
///         ABI signatures are byte-identical to the original on-host versions, so off-
///         chain consumers migrate by pointing at this contract's address instead of
///         the staking contract's.
///
///         Pure read-only — never writes state, holds no funds, has no privileged role.
///         The TegridyStaking reference is `immutable`, set once at construction.
///
/// @dev    DRY discipline: the per-position math lives in `StakingViewLib.earnedFromMem`
///         (a memory variant of the storage `earned` already used by the host). Both
///         the storage and memory variants must stay in lockstep — any future audit fix
///         to one MUST land in the other (the compiler does not share bodies).
contract StakingMonitorView {
    ITegridyStakingMonitorRead public immutable staking;

    constructor(address _staking) {
        require(_staking != address(0), "StakingMonitorView: zero staking");
        staking = ITegridyStakingMonitorRead(_staking);
    }

    /// @notice Pending rewards for a position. Byte-identical ABI to the removed
    ///         `TegridyStaking.earned(uint256)`.
    /// @dev    Inflates the Position struct from the public mapping tuple, pulls the
    ///         reward-math scalars, then defers to `StakingViewLib.earnedFromMem`.
    function earned(uint256 tokenId) external view returns (uint256) {
        Position memory p = _loadPosition(tokenId);
        ITegridyStakingMonitorRead s = staking;
        uint256 available = IMonitorERC20Balance(s.rewardToken()).balanceOf(address(s));
        return StakingViewLib.earnedFromMem(
            p,
            s.rewardPerTokenStored(),
            s.lastUpdateTime(),
            s.rewardRate(),
            s.totalBoostedStake(),
            available,
            s.totalStaked(),
            s.totalUnsettledRewards()
        );
    }

    /// @notice Position details. Byte-identical ABI to the removed
    ///         `TegridyStaking.getPosition(uint256)`.
    function getPosition(uint256 tokenId) external view returns (
        uint256 amount,
        uint256 boostBps,
        uint256 lockEnd,
        uint256 lockDuration,
        bool autoMaxLock,
        bool canWithdraw
    ) {
        // AUDIT 2026-05-30 [slither unused-return]: tuple destructuring with intentionally
        // skipped fields (boostedAmount, rewardDebt, hasJbacBoost, stakeTimestamp,
        // jbacTokenId, jbacDeposited) — this view only exposes the 6 fields its public
        // signature returns. Standard Solidity tuple-skip pattern; the detector flags any
        // tuple destructuring where any field is dropped.
        // slither-disable-next-line unused-return
        (
            uint256 amt,
            ,                  // boostedAmount
            ,                  // rewardDebt
            uint64 lockEndV,
            uint16 boostBpsV,
            uint32 lockDurV,
            bool autoMaxLockV,
            ,                  // hasJbacBoost
            ,                  // stakeTimestamp
            ,                  // jbacTokenId
                               // jbacDeposited
        ) = staking.positions(tokenId);
        return (
            amt,
            boostBpsV,
            uint256(lockEndV),
            uint256(lockDurV),
            autoMaxLockV,
            amt > 0 && block.timestamp >= uint256(lockEndV)
        );
    }

    /// @notice Global-stake-cap utilization in basis points. Byte-identical ABI to
    ///         the removed `TegridyStaking.stakeCapUtilizationBps()` — recomputes
    ///         from the host's public `maxTotalStaked` + `totalStaked`. Forta /
    ///         Defender alert at 8000 bps (80%); saturates at 10000.
    function stakeCapUtilizationBps() external view returns (uint256) {
        uint256 cap = staking.maxTotalStaked();
        if (cap == 0 || cap == type(uint256).max) return 0;
        uint256 staked = staking.totalStaked();
        if (staked >= cap) return 10000;
        return (staked * 10000) / cap;
    }

    /// @notice Remaining headroom under the global stake cap, in TOWELI wei.
    ///         Byte-identical ABI to the removed `TegridyStaking.stakeCapHeadroom()`.
    function stakeCapHeadroom() external view returns (uint256) {
        uint256 cap = staking.maxTotalStaked();
        if (cap == type(uint256).max) return type(uint256).max;
        uint256 staked = staking.totalStaked();
        return staked >= cap ? 0 : cap - staked;
    }

    // ─── Internal helpers ─────────────────────────────────────────────────

    /// @dev Pack the auto-getter tuple back into a Position memory struct so the lib's
    ///      memory-variant of `earned` can be reused without inlining its math here.
    function _loadPosition(uint256 tokenId) internal view returns (Position memory p) {
        (
            uint256 amount,
            uint256 boostedAmount,
            int256 rewardDebt,
            uint64 lockEnd,
            uint16 boostBps,
            uint32 lockDuration,
            bool autoMaxLock,
            bool hasJbacBoost,
            uint64 stakeTimestamp,
            uint256 jbacTokenId,
            bool jbacDeposited
        ) = staking.positions(tokenId);
        p.amount = amount;
        p.boostedAmount = boostedAmount;
        p.rewardDebt = rewardDebt;
        p.lockEnd = lockEnd;
        p.boostBps = boostBps;
        p.lockDuration = lockDuration;
        p.autoMaxLock = autoMaxLock;
        p.hasJbacBoost = hasJbacBoost;
        p.stakeTimestamp = stakeTimestamp;
        p.jbacTokenId = jbacTokenId;
        p.jbacDeposited = jbacDeposited;
    }
}

lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)

pragma solidity >=0.6.2;

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

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

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

pragma solidity >=0.4.16;

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

lib/solady/src/utils/EnumerableSetLib.sol

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

/// @notice Library for managing enumerable sets in storage.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/EnumerableSetLib.sol)
///
/// @dev Note:
/// In many applications, the number of elements in an enumerable set is small.
/// This enumerable set implementation avoids storing the length and indices
/// for up to 3 elements. Once the length exceeds 3 for the first time, the length
/// and indices will be initialized. The amortized cost of adding elements is O(1).
///
/// The AddressSet implementation packs the length with the 0th entry.
///
/// All enumerable sets except Uint8Set use a pop and swap mechanism to remove elements.
/// This means that the iteration order of elements can change between element removals.
library EnumerableSetLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The index must be less than the length.
    error IndexOutOfBounds();

    /// @dev The value cannot be the zero sentinel.
    error ValueIsZeroSentinel();

    /// @dev Cannot accommodate a new unique value with the capacity.
    error ExceedsCapacity();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The index to represent a value that does not exist.
    uint256 internal constant NOT_FOUND = type(uint256).max;

    /// @dev A sentinel value to denote the zero value in storage.
    /// No elements can be equal to this value.
    /// `uint72(bytes9(keccak256(bytes("_ZERO_SENTINEL"))))`.
    uint256 private constant _ZERO_SENTINEL = 0xfbb67fda52d4bfb8bf;

    /// @dev The storage layout is given by:
    /// ```
    ///     mstore(0x04, _ENUMERABLE_ADDRESS_SET_SLOT_SEED)
    ///     mstore(0x00, set.slot)
    ///     let rootSlot := keccak256(0x00, 0x24)
    ///     mstore(0x20, rootSlot)
    ///     mstore(0x00, shr(96, shl(96, value)))
    ///     let positionSlot := keccak256(0x00, 0x40)
    ///     let valueSlot := add(rootSlot, sload(positionSlot))
    ///     let valueInStorage := shr(96, sload(valueSlot))
    ///     let lazyLength := shr(160, shl(160, sload(rootSlot)))
    /// ```
    uint256 private constant _ENUMERABLE_ADDRESS_SET_SLOT_SEED = 0x978aab92;

    /// @dev The storage layout is given by:
    /// ```
    ///     mstore(0x04, _ENUMERABLE_WORD_SET_SLOT_SEED)
    ///     mstore(0x00, set.slot)
    ///     let rootSlot := keccak256(0x00, 0x24)
    ///     mstore(0x20, rootSlot)
    ///     mstore(0x00, value)
    ///     let positionSlot := keccak256(0x00, 0x40)
    ///     let valueSlot := add(rootSlot, sload(positionSlot))
    ///     let valueInStorage := sload(valueSlot)
    ///     let lazyLength := sload(not(rootSlot))
    /// ```
    uint256 private constant _ENUMERABLE_WORD_SET_SLOT_SEED = 0x18fb5864;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STRUCTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev An enumerable address set in storage.
    struct AddressSet {
        uint256 _spacer;
    }

    /// @dev An enumerable bytes32 set in storage.
    struct Bytes32Set {
        uint256 _spacer;
    }

    /// @dev An enumerable uint256 set in storage.
    struct Uint256Set {
        uint256 _spacer;
    }

    /// @dev An enumerable int256 set in storage.
    struct Int256Set {
        uint256 _spacer;
    }

    /// @dev An enumerable uint8 set in storage. Useful for enums.
    struct Uint8Set {
        uint256 data;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     GETTERS / SETTERS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the number of elements in the set.
    function length(AddressSet storage set) internal view returns (uint256 result) {
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            let rootPacked := sload(rootSlot)
            let n := shr(160, shl(160, rootPacked))
            result := shr(1, n)
            for {} iszero(or(iszero(shr(96, rootPacked)), n)) {} {
                result := 1
                if iszero(sload(add(rootSlot, result))) { break }
                result := 2
                if iszero(sload(add(rootSlot, result))) { break }
                result := 3
                break
            }
        }
    }

    /// @dev Returns the number of elements in the set.
    function length(Bytes32Set storage set) internal view returns (uint256 result) {
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            let n := sload(not(rootSlot))
            result := shr(1, n)
            for {} iszero(n) {} {
                result := 0
                if iszero(sload(add(rootSlot, result))) { break }
                result := 1
                if iszero(sload(add(rootSlot, result))) { break }
                result := 2
                if iszero(sload(add(rootSlot, result))) { break }
                result := 3
                break
            }
        }
    }

    /// @dev Returns the number of elements in the set.
    function length(Uint256Set storage set) internal view returns (uint256 result) {
        result = length(_toBytes32Set(set));
    }

    /// @dev Returns the number of elements in the set.
    function length(Int256Set storage set) internal view returns (uint256 result) {
        result = length(_toBytes32Set(set));
    }

    /// @dev Returns the number of elements in the set.
    function length(Uint8Set storage set) internal view returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            for { let packed := sload(set.slot) } packed { result := add(1, result) } {
                packed := xor(packed, and(packed, add(1, not(packed))))
            }
        }
    }

    /// @dev Returns whether `value` is in the set.
    function contains(AddressSet storage set, address value) internal view returns (bool result) {
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            value := shr(96, shl(96, value))
            if eq(value, _ZERO_SENTINEL) {
                mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
                revert(0x1c, 0x04)
            }
            if iszero(value) { value := _ZERO_SENTINEL }
            let rootPacked := sload(rootSlot)
            for {} 1 {} {
                if iszero(shr(160, shl(160, rootPacked))) {
                    result := 1
                    if eq(shr(96, rootPacked), value) { break }
                    if eq(shr(96, sload(add(rootSlot, 1))), value) { break }
                    if eq(shr(96, sload(add(rootSlot, 2))), value) { break }
                    result := 0
                    break
                }
                mstore(0x20, rootSlot)
                mstore(0x00, value)
                result := iszero(iszero(sload(keccak256(0x00, 0x40))))
                break
            }
        }
    }

    /// @dev Returns whether `value` is in the set.
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool result) {
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            if eq(value, _ZERO_SENTINEL) {
                mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
                revert(0x1c, 0x04)
            }
            if iszero(value) { value := _ZERO_SENTINEL }
            for {} 1 {} {
                if iszero(sload(not(rootSlot))) {
                    result := 1
                    if eq(sload(rootSlot), value) { break }
                    if eq(sload(add(rootSlot, 1)), value) { break }
                    if eq(sload(add(rootSlot, 2)), value) { break }
                    result := 0
                    break
                }
                mstore(0x20, rootSlot)
                mstore(0x00, value)
                result := iszero(iszero(sload(keccak256(0x00, 0x40))))
                break
            }
        }
    }

    /// @dev Returns whether `value` is in the set.
    function contains(Uint256Set storage set, uint256 value) internal view returns (bool result) {
        result = contains(_toBytes32Set(set), bytes32(value));
    }

    /// @dev Returns whether `value` is in the set.
    function contains(Int256Set storage set, int256 value) internal view returns (bool result) {
        result = contains(_toBytes32Set(set), bytes32(uint256(value)));
    }

    /// @dev Returns whether `value` is in the set.
    function contains(Uint8Set storage set, uint8 value) internal view returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := and(1, shr(and(0xff, value), sload(set.slot)))
        }
    }

    /// @dev Adds `value` to the set. Returns whether `value` was not in the set.
    function add(AddressSet storage set, address value) internal returns (bool result) {
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            value := shr(96, shl(96, value))
            if eq(value, _ZERO_SENTINEL) {
                mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
                revert(0x1c, 0x04)
            }
            if iszero(value) { value := _ZERO_SENTINEL }
            let rootPacked := sload(rootSlot)
            for { let n := shr(160, shl(160, rootPacked)) } 1 {} {
                mstore(0x20, rootSlot)
                if iszero(n) {
                    let v0 := shr(96, rootPacked)
                    if iszero(v0) {
                        sstore(rootSlot, shl(96, value))
                        result := 1
                        break
                    }
                    if eq(v0, value) { break }
                    let v1 := shr(96, sload(add(rootSlot, 1)))
                    if iszero(v1) {
                        sstore(add(rootSlot, 1), shl(96, value))
                        result := 1
                        break
                    }
                    if eq(v1, value) { break }
                    let v2 := shr(96, sload(add(rootSlot, 2)))
                    if iszero(v2) {
                        sstore(add(rootSlot, 2), shl(96, value))
                        result := 1
                        break
                    }
                    if eq(v2, value) { break }
                    mstore(0x00, v0)
                    sstore(keccak256(0x00, 0x40), 1)
                    mstore(0x00, v1)
                    sstore(keccak256(0x00, 0x40), 2)
                    mstore(0x00, v2)
                    sstore(keccak256(0x00, 0x40), 3)
                    rootPacked := or(rootPacked, 7)
                    n := 7
                }
                mstore(0x00, value)
                let p := keccak256(0x00, 0x40)
                if iszero(sload(p)) {
                    n := shr(1, n)
                    result := 1
                    sstore(p, add(1, n))
                    if iszero(n) {
                        sstore(rootSlot, or(3, shl(96, value)))
                        break
                    }
                    sstore(add(rootSlot, n), shl(96, value))
                    sstore(rootSlot, add(2, rootPacked))
                    break
                }
                break
            }
        }
    }

    /// @dev Adds `value` to the set. Returns whether `value` was not in the set.
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool result) {
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            if eq(value, _ZERO_SENTINEL) {
                mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
                revert(0x1c, 0x04)
            }
            if iszero(value) { value := _ZERO_SENTINEL }
            for { let n := sload(not(rootSlot)) } 1 {} {
                mstore(0x20, rootSlot)
                if iszero(n) {
                    let v0 := sload(rootSlot)
                    if iszero(v0) {
                        sstore(rootSlot, value)
                        result := 1
                        break
                    }
                    if eq(v0, value) { break }
                    let v1 := sload(add(rootSlot, 1))
                    if iszero(v1) {
                        sstore(add(rootSlot, 1), value)
                        result := 1
                        break
                    }
                    if eq(v1, value) { break }
                    let v2 := sload(add(rootSlot, 2))
                    if iszero(v2) {
                        sstore(add(rootSlot, 2), value)
                        result := 1
                        break
                    }
                    if eq(v2, value) { break }
                    mstore(0x00, v0)
                    sstore(keccak256(0x00, 0x40), 1)
                    mstore(0x00, v1)
                    sstore(keccak256(0x00, 0x40), 2)
                    mstore(0x00, v2)
                    sstore(keccak256(0x00, 0x40), 3)
                    n := 7
                }
                mstore(0x00, value)
                let p := keccak256(0x00, 0x40)
                if iszero(sload(p)) {
                    n := shr(1, n)
                    sstore(add(rootSlot, n), value)
                    sstore(p, add(1, n))
                    sstore(not(rootSlot), or(1, shl(1, add(1, n))))
                    result := 1
                    break
                }
                break
            }
        }
    }

    /// @dev Adds `value` to the set. Returns whether `value` was not in the set.
    function add(Uint256Set storage set, uint256 value) internal returns (bool result) {
        result = add(_toBytes32Set(set), bytes32(value));
    }

    /// @dev Adds `value` to the set. Returns whether `value` was not in the set.
    function add(Int256Set storage set, int256 value) internal returns (bool result) {
        result = add(_toBytes32Set(set), bytes32(uint256(value)));
    }

    /// @dev Adds `value` to the set. Returns whether `value` was not in the set.
    function add(Uint8Set storage set, uint8 value) internal returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(set.slot)
            let mask := shl(and(0xff, value), 1)
            sstore(set.slot, or(result, mask))
            result := iszero(and(result, mask))
        }
    }

    /// @dev Adds `value` to the set. Returns whether `value` was not in the set.
    /// Reverts if the set grows bigger than the custom on-the-fly capacity `cap`.
    function add(AddressSet storage set, address value, uint256 cap)
        internal
        returns (bool result)
    {
        if (result = add(set, value)) if (length(set) > cap) revert ExceedsCapacity();
    }

    /// @dev Adds `value` to the set. Returns whether `value` was not in the set.
    /// Reverts if the set grows bigger than the custom on-the-fly capacity `cap`.
    function add(Bytes32Set storage set, bytes32 value, uint256 cap)
        internal
        returns (bool result)
    {
        if (result = add(set, value)) if (length(set) > cap) revert ExceedsCapacity();
    }

    /// @dev Adds `value` to the set. Returns whether `value` was not in the set.
    /// Reverts if the set grows bigger than the custom on-the-fly capacity `cap`.
    function add(Uint256Set storage set, uint256 value, uint256 cap)
        internal
        returns (bool result)
    {
        if (result = add(set, value)) if (length(set) > cap) revert ExceedsCapacity();
    }

    /// @dev Adds `value` to the set. Returns whether `value` was not in the set.
    /// Reverts if the set grows bigger than the custom on-the-fly capacity `cap`.
    function add(Int256Set storage set, int256 value, uint256 cap) internal returns (bool result) {
        if (result = add(set, value)) if (length(set) > cap) revert ExceedsCapacity();
    }

    /// @dev Adds `value` to the set. Returns whether `value` was not in the set.
    /// Reverts if the set grows bigger than the custom on-the-fly capacity `cap`.
    function add(Uint8Set storage set, uint8 value, uint256 cap) internal returns (bool result) {
        if (result = add(set, value)) if (length(set) > cap) revert ExceedsCapacity();
    }

    /// @dev Removes `value` from the set. Returns whether `value` was in the set.
    function remove(AddressSet storage set, address value) internal returns (bool result) {
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            value := shr(96, shl(96, value))
            if eq(value, _ZERO_SENTINEL) {
                mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
                revert(0x1c, 0x04)
            }
            if iszero(value) { value := _ZERO_SENTINEL }
            let rootPacked := sload(rootSlot)
            for { let n := shr(160, shl(160, rootPacked)) } 1 {} {
                if iszero(n) {
                    result := 1
                    if eq(shr(96, rootPacked), value) {
                        sstore(rootSlot, sload(add(rootSlot, 1)))
                        sstore(add(rootSlot, 1), sload(add(rootSlot, 2)))
                        sstore(add(rootSlot, 2), 0)
                        break
                    }
                    if eq(shr(96, sload(add(rootSlot, 1))), value) {
                        sstore(add(rootSlot, 1), sload(add(rootSlot, 2)))
                        sstore(add(rootSlot, 2), 0)
                        break
                    }
                    if eq(shr(96, sload(add(rootSlot, 2))), value) {
                        sstore(add(rootSlot, 2), 0)
                        break
                    }
                    result := 0
                    break
                }
                mstore(0x20, rootSlot)
                mstore(0x00, value)
                let p := keccak256(0x00, 0x40)
                let position := sload(p)
                if iszero(position) { break }
                n := sub(shr(1, n), 1)
                if iszero(eq(sub(position, 1), n)) {
                    let lastValue := shr(96, sload(add(rootSlot, n)))
                    sstore(add(rootSlot, sub(position, 1)), shl(96, lastValue))
                    mstore(0x00, lastValue)
                    sstore(keccak256(0x00, 0x40), position)
                }
                sstore(rootSlot, or(shl(96, shr(96, sload(rootSlot))), or(shl(1, n), 1)))
                sstore(p, 0)
                result := 1
                break
            }
        }
    }

    /// @dev Removes `value` from the set. Returns whether `value` was in the set.
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool result) {
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            if eq(value, _ZERO_SENTINEL) {
                mstore(0x00, 0xf5a267f1) // `ValueIsZeroSentinel()`.
                revert(0x1c, 0x04)
            }
            if iszero(value) { value := _ZERO_SENTINEL }
            for { let n := sload(not(rootSlot)) } 1 {} {
                if iszero(n) {
                    result := 1
                    if eq(sload(rootSlot), value) {
                        sstore(rootSlot, sload(add(rootSlot, 1)))
                        sstore(add(rootSlot, 1), sload(add(rootSlot, 2)))
                        sstore(add(rootSlot, 2), 0)
                        break
                    }
                    if eq(sload(add(rootSlot, 1)), value) {
                        sstore(add(rootSlot, 1), sload(add(rootSlot, 2)))
                        sstore(add(rootSlot, 2), 0)
                        break
                    }
                    if eq(sload(add(rootSlot, 2)), value) {
                        sstore(add(rootSlot, 2), 0)
                        break
                    }
                    result := 0
                    break
                }
                mstore(0x20, rootSlot)
                mstore(0x00, value)
                let p := keccak256(0x00, 0x40)
                let position := sload(p)
                if iszero(position) { break }
                n := sub(shr(1, n), 1)
                if iszero(eq(sub(position, 1), n)) {
                    let lastValue := sload(add(rootSlot, n))
                    sstore(add(rootSlot, sub(position, 1)), lastValue)
                    mstore(0x00, lastValue)
                    sstore(keccak256(0x00, 0x40), position)
                }
                sstore(not(rootSlot), or(shl(1, n), 1))
                sstore(p, 0)
                result := 1
                break
            }
        }
    }

    /// @dev Removes `value` from the set. Returns whether `value` was in the set.
    function remove(Uint256Set storage set, uint256 value) internal returns (bool result) {
        result = remove(_toBytes32Set(set), bytes32(value));
    }

    /// @dev Removes `value` from the set. Returns whether `value` was in the set.
    function remove(Int256Set storage set, int256 value) internal returns (bool result) {
        result = remove(_toBytes32Set(set), bytes32(uint256(value)));
    }

    /// @dev Removes `value` from the set. Returns whether `value` was in the set.
    function remove(Uint8Set storage set, uint8 value) internal returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(set.slot)
            let mask := shl(and(0xff, value), 1)
            sstore(set.slot, and(result, not(mask)))
            result := iszero(iszero(and(result, mask)))
        }
    }

    /// @dev Shorthand for `isAdd ? set.add(value, cap) : set.remove(value)`.
    function update(AddressSet storage set, address value, bool isAdd, uint256 cap)
        internal
        returns (bool)
    {
        return isAdd ? add(set, value, cap) : remove(set, value);
    }

    /// @dev Shorthand for `isAdd ? set.add(value, cap) : set.remove(value)`.
    function update(Bytes32Set storage set, bytes32 value, bool isAdd, uint256 cap)
        internal
        returns (bool)
    {
        return isAdd ? add(set, value, cap) : remove(set, value);
    }

    /// @dev Shorthand for `isAdd ? set.add(value, cap) : set.remove(value)`.
    function update(Uint256Set storage set, uint256 value, bool isAdd, uint256 cap)
        internal
        returns (bool)
    {
        return isAdd ? add(set, value, cap) : remove(set, value);
    }

    /// @dev Shorthand for `isAdd ? set.add(value, cap) : set.remove(value)`.
    function update(Int256Set storage set, int256 value, bool isAdd, uint256 cap)
        internal
        returns (bool)
    {
        return isAdd ? add(set, value, cap) : remove(set, value);
    }

    /// @dev Shorthand for `isAdd ? set.add(value, cap) : set.remove(value)`.
    function update(Uint8Set storage set, uint8 value, bool isAdd, uint256 cap)
        internal
        returns (bool)
    {
        return isAdd ? add(set, value, cap) : remove(set, value);
    }

    /// @dev Returns all of the values in the set.
    /// Note: This can consume more gas than the block gas limit for large sets.
    function values(AddressSet storage set) internal view returns (address[] memory result) {
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            let zs := _ZERO_SENTINEL
            let rootPacked := sload(rootSlot)
            let n := shr(160, shl(160, rootPacked))
            result := mload(0x40)
            let o := add(0x20, result)
            let v := shr(96, rootPacked)
            mstore(o, mul(v, iszero(eq(v, zs))))
            for {} 1 {} {
                if iszero(n) {
                    if v {
                        n := 1
                        v := shr(96, sload(add(rootSlot, n)))
                        if v {
                            n := 2
                            mstore(add(o, 0x20), mul(v, iszero(eq(v, zs))))
                            v := shr(96, sload(add(rootSlot, n)))
                            if v {
                                n := 3
                                mstore(add(o, 0x40), mul(v, iszero(eq(v, zs))))
                            }
                        }
                    }
                    break
                }
                n := shr(1, n)
                for { let i := 1 } lt(i, n) { i := add(i, 1) } {
                    v := shr(96, sload(add(rootSlot, i)))
                    mstore(add(o, shl(5, i)), mul(v, iszero(eq(v, zs))))
                }
                break
            }
            mstore(result, n)
            mstore(0x40, add(o, shl(5, n)))
        }
    }

    /// @dev Returns all of the values in the set.
    /// Note: This can consume more gas than the block gas limit for large sets.
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory result) {
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            let zs := _ZERO_SENTINEL
            let n := sload(not(rootSlot))
            result := mload(0x40)
            let o := add(0x20, result)
            for {} 1 {} {
                if iszero(n) {
                    let v := sload(rootSlot)
                    if v {
                        n := 1
                        mstore(o, mul(v, iszero(eq(v, zs))))
                        v := sload(add(rootSlot, n))
                        if v {
                            n := 2
                            mstore(add(o, 0x20), mul(v, iszero(eq(v, zs))))
                            v := sload(add(rootSlot, n))
                            if v {
                                n := 3
                                mstore(add(o, 0x40), mul(v, iszero(eq(v, zs))))
                            }
                        }
                    }
                    break
                }
                n := shr(1, n)
                for { let i := 0 } lt(i, n) { i := add(i, 1) } {
                    let v := sload(add(rootSlot, i))
                    mstore(add(o, shl(5, i)), mul(v, iszero(eq(v, zs))))
                }
                break
            }
            mstore(result, n)
            mstore(0x40, add(o, shl(5, n)))
        }
    }

    /// @dev Returns all of the values in the set.
    /// Note: This can consume more gas than the block gas limit for large sets.
    function values(Uint256Set storage set) internal view returns (uint256[] memory result) {
        result = _toUints(values(_toBytes32Set(set)));
    }

    /// @dev Returns all of the values in the set.
    /// Note: This can consume more gas than the block gas limit for large sets.
    function values(Int256Set storage set) internal view returns (int256[] memory result) {
        result = _toInts(values(_toBytes32Set(set)));
    }

    /// @dev Returns all of the values in the set.
    function values(Uint8Set storage set) internal view returns (uint8[] memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let ptr := add(result, 0x20)
            let o := 0
            for { let packed := sload(set.slot) } packed {} {
                if iszero(and(packed, 0xffff)) {
                    o := add(o, 16)
                    packed := shr(16, packed)
                    continue
                }
                mstore(ptr, o)
                ptr := add(ptr, shl(5, and(packed, 1)))
                o := add(o, 1)
                packed := shr(1, packed)
            }
            mstore(result, shr(5, sub(ptr, add(result, 0x20))))
            mstore(0x40, ptr)
        }
    }

    /// @dev Returns the element at index `i` in the set. Reverts if `i` is out-of-bounds.
    function at(AddressSet storage set, uint256 i) internal view returns (address result) {
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            result := shr(96, sload(add(rootSlot, i)))
            result := mul(result, iszero(eq(result, _ZERO_SENTINEL)))
        }
        if (i >= length(set)) revert IndexOutOfBounds();
    }

    /// @dev Returns the element at index `i` in the set. Reverts if `i` is out-of-bounds.
    function at(Bytes32Set storage set, uint256 i) internal view returns (bytes32 result) {
        result = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(add(result, i))
            result := mul(result, iszero(eq(result, _ZERO_SENTINEL)))
        }
        if (i >= length(set)) revert IndexOutOfBounds();
    }

    /// @dev Returns the element at index `i` in the set. Reverts if `i` is out-of-bounds.
    function at(Uint256Set storage set, uint256 i) internal view returns (uint256 result) {
        result = uint256(at(_toBytes32Set(set), i));
    }

    /// @dev Returns the element at index `i` in the set. Reverts if `i` is out-of-bounds.
    function at(Int256Set storage set, uint256 i) internal view returns (int256 result) {
        result = int256(uint256(at(_toBytes32Set(set), i)));
    }

    /// @dev Returns the element at index `i` in the set. Reverts if `i` is out-of-bounds.
    function at(Uint8Set storage set, uint256 i) internal view returns (uint8 result) {
        /// @solidity memory-safe-assembly
        assembly {
            let packed := sload(set.slot)
            for {} 1 {
                mstore(0x00, 0x4e23d035) // `IndexOutOfBounds()`.
                revert(0x1c, 0x04)
            } {
                if iszero(lt(i, 256)) { continue }
                for { let j := 0 } iszero(eq(i, j)) {} {
                    packed := xor(packed, and(packed, add(1, not(packed))))
                    j := add(j, 1)
                }
                if iszero(packed) { continue }
                break
            }
            // Find first set subroutine, optimized for smaller bytecode size.
            let x := and(packed, add(1, not(packed)))
            let r := shl(7, iszero(iszero(shr(128, x))))
            r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            // For the lower 5 bits of the result, use a De Bruijn lookup.
            // forgefmt: disable-next-item
            result := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
        }
    }

    /// @dev Returns the index of `value`. Returns `NOT_FOUND` if the value does not exist.
    function indexOf(AddressSet storage set, address value)
        internal
        view
        returns (uint256 result)
    {
        result = NOT_FOUND;
        if (uint160(value) == _ZERO_SENTINEL) return result;
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(value) { value := _ZERO_SENTINEL }
            result := not(0)
            let rootPacked := sload(rootSlot)
            for {} 1 {} {
                if iszero(shr(160, shl(160, rootPacked))) {
                    if eq(shr(96, rootPacked), value) {
                        result := 0
                        break
                    }
                    if eq(shr(96, sload(add(rootSlot, 1))), value) {
                        result := 1
                        break
                    }
                    if eq(shr(96, sload(add(rootSlot, 2))), value) {
                        result := 2
                        break
                    }
                    break
                }
                mstore(0x20, rootSlot)
                mstore(0x00, value)
                result := sub(sload(keccak256(0x00, 0x40)), 1)
                break
            }
        }
    }

    /// @dev Returns the index of `value`. Returns `NOT_FOUND` if the value does not exist.
    function indexOf(Bytes32Set storage set, bytes32 value)
        internal
        view
        returns (uint256 result)
    {
        result = NOT_FOUND;
        if (uint256(value) == _ZERO_SENTINEL) return result;
        bytes32 rootSlot = _rootSlot(set);
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(value) { value := _ZERO_SENTINEL }
            for {} 1 {} {
                if iszero(sload(not(rootSlot))) {
                    if eq(sload(rootSlot), value) {
                        result := 0
                        break
                    }
                    if eq(sload(add(rootSlot, 1)), value) {
                        result := 1
                        break
                    }
                    if eq(sload(add(rootSlot, 2)), value) {
                        result := 2
                        break
                    }
                    break
                }
                mstore(0x20, rootSlot)
                mstore(0x00, value)
                result := sub(sload(keccak256(0x00, 0x40)), 1)
                break
            }
        }
    }

    /// @dev Returns the index of `value`. Returns `NOT_FOUND` if the value does not exist.
    function indexOf(Uint256Set storage set, uint256 i) internal view returns (uint256 result) {
        result = indexOf(_toBytes32Set(set), bytes32(i));
    }

    /// @dev Returns the index of `value`. Returns `NOT_FOUND` if the value does not exist.
    function indexOf(Int256Set storage set, int256 i) internal view returns (uint256 result) {
        result = indexOf(_toBytes32Set(set), bytes32(uint256(i)));
    }

    /// @dev Returns the index of `value`. Returns `NOT_FOUND` if the value does not exist.
    function indexOf(Uint8Set storage set, uint8 value) internal view returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := not(0)
            let packed := sload(set.slot)
            let m := shl(and(0xff, value), 1)
            if and(packed, m) {
                result := 0
                for { let p := and(packed, sub(m, 1)) } p {} {
                    p := xor(p, and(p, add(1, not(p))))
                    result := add(result, 1)
                }
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      PRIVATE HELPERS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the root slot.
    function _rootSlot(AddressSet storage s) private pure returns (bytes32 r) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x04, _ENUMERABLE_ADDRESS_SET_SLOT_SEED)
            mstore(0x00, s.slot)
            r := keccak256(0x00, 0x24)
        }
    }

    /// @dev Returns the root slot.
    function _rootSlot(Bytes32Set storage s) private pure returns (bytes32 r) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x04, _ENUMERABLE_WORD_SET_SLOT_SEED)
            mstore(0x00, s.slot)
            r := keccak256(0x00, 0x24)
        }
    }

    /// @dev Casts to a Bytes32Set.
    function _toBytes32Set(Uint256Set storage s) private pure returns (Bytes32Set storage c) {
        /// @solidity memory-safe-assembly
        assembly {
            c.slot := s.slot
        }
    }

    /// @dev Casts to a Bytes32Set.
    function _toBytes32Set(Int256Set storage s) private pure returns (Bytes32Set storage c) {
        /// @solidity memory-safe-assembly
        assembly {
            c.slot := s.slot
        }
    }

    /// @dev Casts to a uint256 array.
    function _toUints(bytes32[] memory a) private pure returns (uint256[] memory c) {
        /// @solidity memory-safe-assembly
        assembly {
            c := a
        }
    }

    /// @dev Casts to a int256 array.
    function _toInts(bytes32[] memory a) private pure returns (int256[] memory c) {
        /// @solidity memory-safe-assembly
        assembly {
            c := a
        }
    }
}

src/lib/StakingViewLib.sol

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

// EIP-170 split (2026-05-30): swapped to Solady EnumerableSetLib (API-identical for
// UintSet → Uint256Set; smaller bytecode; verbatim battle-tested).
import {EnumerableSetLib} from "solady/utils/EnumerableSetLib.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";

/// @dev Minimal restaking-view surface used by `resolveJbac`. Mirrors the
///      ITegridyRestakingView.tokenIdToRestaker selector in TegridyStaking.
interface ITegridyRestakingView {
    function tokenIdToRestaker(uint256 tokenId) external view returns (address);
}

/// @notice Staking position struct. Relocated to file level (from inside
///         TegridyStaking) during the EIP-170 split so the linked view library
///         below can operate on `positions` storage. Layout is byte-identical to
///         the original in-contract struct — the `positions` public-getter ABI is
///         unchanged.
struct Position {
    uint256 amount;
    uint256 boostedAmount;
    int256 rewardDebt;
    uint64 lockEnd;
    uint16 boostBps;
    uint32 lockDuration;
    bool autoMaxLock;
    bool hasJbacBoost;
    uint64 stakeTimestamp;
    uint256 jbacTokenId;
    bool jbacDeposited;
}

/// @title StakingViewLib
/// @notice EIP-170 split (C1): read-only view/math extracted from TegridyStaking
///         into a linked (delegatecall) library. PURE SIZE REDUCTION — behaviour is
///         byte-for-byte identical to the original in-contract functions. Every
///         function here is read-only (view/pure); because the library is invoked
///         via delegatecall it shares the caller's storage, but holding zero write
///         paths means it cannot corrupt staking state. The caller (TegridyStaking)
///         keeps thin wrappers that apply the restaking/lending carve-out guards
///         then delegate the iteration/math here.
library StakingViewLib {
    using EnumerableSetLib for EnumerableSetLib.Uint256Set;

    // Mirror of the TegridyStaking constants used by the extracted math. These are
    // universal protocol constants (must equal the contract's values).
    uint256 internal constant BOOST_PRECISION = 10000;
    uint256 internal constant ACC_PRECISION = 1e18;

    /// @dev EIP-170 split + DRY: the JBAC re-validation block that was copy-pasted inline
    ///      in `getReward`, `toggleAutoMaxLock`, and `extendLock`. Behaviour byte-identical
    ///      to the three inline copies (F3-PERMA-STRIP preserved: transient lookup failure
    ///      leaves the cached flag intact). Collapsing 3 copies of security-critical code
    ///      to 1 body reduces attack surface AND removes drift risk between sites.
    ///      Caller pattern: if (jbacValid) newBoost += JBAC_BONUS_BPS;
    ///                      else if (clearStaleFlag) p.hasJbacBoost = false;
    /// @dev Visibility intentionally `internal`: the 3 callsites in TegridyStaking get
    ///      inlined at each callsite (same bytecode shape as the pre-refactor inline
    ///      copies), so the DRY consolidation is a SOURCE-LEVEL win for audit / review
    ///      without paying the ~250 B per-callsite delegatecall wrapper overhead that
    ///      `public` visibility would incur. Verified against measured sizes 2026-05-30.
    function resolveJbac(
        Position storage p,
        uint256 tokenId,
        address caller,
        address restakingContract,
        IERC721 jbacNFT
    ) internal view returns (bool jbacValid, bool clearStaleFlag) {
        address jbacHolder = caller;
        bool lookupOk = true;
        if (caller == restakingContract && restakingContract != address(0)) {
            try ITegridyRestakingView(restakingContract).tokenIdToRestaker(tokenId) returns (address depositor) {
                if (depositor != address(0)) jbacHolder = depositor;
            } catch {
                lookupOk = false;
            }
        }
        jbacValid = p.jbacDeposited || (p.hasJbacBoost && lookupOk && jbacNFT.balanceOf(jbacHolder) > 0);
        clearStaleFlag = !jbacValid && p.hasJbacBoost && lookupOk;
    }

    /// @dev Aggregated active voting power across every position in `set`.
    ///      Equivalent to the original TegridyStaking.votingPowerOf loop (post
    ///      restaking/lending carve-out, which the caller applies before delegating).
    /// @dev Visibility kept `public`: the for-loop body (~300 B inlined) is LARGER
    ///      than the ~250 B delegatecall wrapper it would replace. Measured 2026-05-30:
    ///      flipping to internal added +104 B to TegridyStaking. The trick only works
    ///      for cheaply-bodied functions (see resolveJbac).
    function votingPowerOf(
        EnumerableSetLib.Uint256Set storage set,
        mapping(uint256 => Position) storage positions
    ) public view returns (uint256 total) {
        uint256 len = set.length();
        uint256 nowTs = block.timestamp;
        for (uint256 i; i < len; ++i) {
            Position storage p = positions[set.at(i)];
            uint256 amount = p.amount;
            if (amount == 0) continue;
            if (nowTs >= p.lockEnd) continue;
            total += (amount * p.boostBps) / BOOST_PRECISION;
        }
    }

    /// @dev Amount-weighted average active boostBps. Mirrors
    ///      TegridyStaking.aggregateActiveBoostBps (post carve-out).
    /// @dev Visibility kept `public` — same for-loop-too-big trade-off as votingPowerOf.
    function aggregateActiveBoostBps(
        EnumerableSetLib.Uint256Set storage set,
        mapping(uint256 => Position) storage positions
    ) public view returns (uint256 weightedBps) {
        uint256 len = set.length();
        uint256 nowTs = block.timestamp;
        uint256 totalAmount;
        uint256 totalBoosted;
        for (uint256 i; i < len; ++i) {
            Position storage p = positions[set.at(i)];
            uint256 amt = p.amount;
            if (amt == 0) continue;
            if (nowTs >= p.lockEnd) continue;
            totalAmount += amt;
            totalBoosted += amt * p.boostBps;
        }
        if (totalAmount == 0) return 0;
        weightedBps = totalBoosted / totalAmount;
    }

    /// @dev Memory variant of `earned` for off-chain callers (external contracts) that
    ///      cannot pass `storage` pointers. Body byte-identical to the storage variant
    ///      below — kept side-by-side so any future audit fix to one MUST land in the
    ///      other (compiler enforces no shared body, so this comment is the discipline).
    ///      Caller pattern: read `positions(tokenId)` tuple from the staking contract,
    ///      pack into Position memory, pass here with the relevant scalar reads.
    function earnedFromMem(
        Position memory p,
        uint256 rewardPerTokenStored,
        uint256 lastUpdateTime,
        uint256 rewardRate,
        uint256 totalBoostedStake,
        uint256 available,
        uint256 totalStaked,
        uint256 totalUnsettledRewards
    ) internal view returns (uint256) {
        if (p.boostedAmount == 0) return 0;
        uint256 currentAcc = rewardPerTokenStored;
        if (block.timestamp > lastUpdateTime && totalBoostedStake > 0) {
            uint256 reward = (block.timestamp - lastUpdateTime) * rewardRate;
            uint256 reserved = totalStaked + totalUnsettledRewards;
            uint256 rewardPool = available > reserved ? available - reserved : 0;
            if (reward > rewardPool) reward = rewardPool;
            if (reward > 0) {
                currentAcc += (reward * ACC_PRECISION) / totalBoostedStake;
            }
        }
        uint256 v = (p.boostedAmount * currentAcc) / ACC_PRECISION;
        if (v > uint256(type(int256).max)) return 0;
        int256 diff = int256(v) - p.rewardDebt;
        return diff > 0 ? uint256(diff) : 0;
    }

    /// @dev Pending rewards for a position. Mirrors TegridyStaking.earned, including
    ///      the AUDIT FIX M-01 expired-position accrual semantics.
    function earned(
        Position storage p,
        uint256 rewardPerTokenStored,
        uint256 lastUpdateTime,
        uint256 rewardRate,
        uint256 totalBoostedStake,
        uint256 available,
        uint256 totalStaked,
        uint256 totalUnsettledRewards
    ) public view returns (uint256) {
        if (p.boostedAmount == 0) return 0;
        uint256 currentAcc = rewardPerTokenStored;
        if (block.timestamp > lastUpdateTime && totalBoostedStake > 0) {
            // AUDIT FIX (earned pool-cap): mirror StakingRewardLib.accumulateRewards —
            // the live accrual caps the elapsed reward to the unreserved pool
            // (balance - totalStaked - totalUnsettledRewards). Pre-fix this view advanced
            // currentAcc by the full `elapsed * rewardRate` with NO cap, over-reporting
            // claimable vs what `getReward` actually pays whenever the pool is under-funded.
            uint256 reward = (block.timestamp - lastUpdateTime) * rewardRate;
            uint256 reserved = totalStaked + totalUnsettledRewards;
            uint256 rewardPool = available > reserved ? available - reserved : 0;
            if (reward > rewardPool) reward = rewardPool;
            if (reward > 0) {
                currentAcc += (reward * ACC_PRECISION) / totalBoostedStake;
            }
        }
        // AUDIT FIX 2026-05-26 [M-18]: guard the int256 cast against the
        // `_safeInt256` invariant. Pre-fix, this view used a raw `int256(...)`
        // cast — at extreme reward-pool inputs (boostedAmount × currentAcc above
        // 2^255), the cast wraps to a large negative and `diff > 0` returns 0
        // (UI lies "no pending"). Practical caps make this unreachable today,
        // but the view violated the contract's own SafeCast discipline. Fix:
        // bail to 0 when the product exceeds int256.max — matches the host's
        // intent (view should never return >= int256.max as positive).
        uint256 v = (p.boostedAmount * currentAcc) / ACC_PRECISION;
        if (v > uint256(type(int256).max)) return 0;
        int256 diff = int256(v) - p.rewardDebt;
        return diff > 0 ? uint256(diff) : 0;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/uniswap-hooks/=lib/uniswap-hooks/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "ds-test/=lib/solmate/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solady/=lib/solady/src/",
    "solmate/=lib/solmate/src/",
    "uniswap-hooks/=lib/uniswap-hooks/src/",
    "v4-core/=lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/",
    "lib/v4-core:solmate/=lib/solmate/",
    "lib/v4-periphery:solmate/=lib/solmate/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.