Перейти к содержимому
Проверенный контрактЧастичноеMIT

DiamondProxy

Адрес0xf199fc4f70a020745c41aa452a0dc43db9a2ca2d
Баланс

0 ETH

 

Транзакций

5

 

Компилятор

solc 0.8.35

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.35+commit.47b9dedd
Язык
solidity
Оптимизация
Да, 1 прогонов
Версия EVM
osaka
Через IR
да
Лицензия
MIT
Совпадение
Частичноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 233 811
Транзакция создания
0x1851e91042…0ce66cf9c0

src/generated/DiamondProxy.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.35;

/// ------------------------------------------------------------------------------------------------------------
///
/// NOTE: This file is auto-generated by Gemforge from `templates/DiamondProxy.sol`.
///
/// It replaces Gemforge's stock template because the OnRe Diamond is not ERC-173
/// owner-gated: `diamondCut` is gated on `LibOnReRoles.UPGRADER_ROLE`, so there is
/// no `OwnershipFacet` to install and no `contractOwner` slot to seed.
///
/// ------------------------------------------------------------------------------------------------------------

import { Diamond } from 'src/diamond/contracts/Diamond.sol';
import { LibDiamond } from 'src/diamond/contracts/libraries/LibDiamond.sol';
import { DiamondCutFacet } from 'src/diamond/contracts/facets/DiamondCutFacet.sol';
import { DiamondLoupeFacet } from 'src/diamond/contracts/facets/DiamondLoupeFacet.sol';
import { IDiamondCut } from 'src/diamond/contracts/interfaces/IDiamondCut.sol';
import { IDiamondLoupe } from 'src/diamond/contracts/interfaces/IDiamondLoupe.sol';
import { IERC165 } from 'src/diamond/contracts/interfaces/IERC165.sol';
import { LibOnReAccessControl } from '../libraries/LibOnReAccessControl.sol';
import { LibOnReRoles } from '../libraries/LibOnReRoles.sol';

contract DiamondProxy is Diamond {
  error BootstrapUpgraderIsZero();

  /// @param bootstrapUpgrader Address allowed to sign the first `diamondCut`.
  /// Gemforge passes the deployment wallet here, then immediately calls
  /// `diamondCut` with the application facets and `OnReDiamondInit.init`.
  /// `init` revokes this grant once the configured upgrader holds the role, so
  /// the authority is transient — see `OnReDiamondInit._handOffBootstrapUpgrader`.
  constructor(address bootstrapUpgrader) payable {
    if (bootstrapUpgrader == address(0)) {
      revert BootstrapUpgraderIsZero();
    }
    LibOnReAccessControl._grantRoleUnchecked(LibOnReRoles.UPGRADER_ROLE, bootstrapUpgrader);

    _initCoreFacets();

    // Only the standard, immutable interfaces are advertised here. The
    // application-level ids are registered by `OnReDiamondInit.init`.
    LibDiamond.DiamondStorage storage ds = LibDiamond._diamondStorage();
    ds.supportedInterfaces[type(IERC165).interfaceId] = true;
    ds.supportedInterfaces[type(IDiamondCut).interfaceId] = true;
    ds.supportedInterfaces[type(IDiamondLoupe).interfaceId] = true;
  }

  // Internal

  function _initCoreFacets() private {
    IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](2);

    bytes4[] memory f0 = new bytes4[](1);
    f0[0] = IDiamondCut.diamondCut.selector;
    cut[0] = IDiamondCut.FacetCut({
      facetAddress: address(new DiamondCutFacet()),
      action: IDiamondCut.FacetCutAction.Add,
      functionSelectors: f0
    });

    bytes4[] memory f1 = new bytes4[](5);
    f1[0] = IDiamondLoupe.facets.selector;
    f1[1] = IDiamondLoupe.facetFunctionSelectors.selector;
    f1[2] = IDiamondLoupe.facetAddresses.selector;
    f1[3] = IDiamondLoupe.facetAddress.selector;
    f1[4] = IERC165.supportsInterface.selector;
    cut[1] = IDiamondCut.FacetCut({
      facetAddress: address(new DiamondLoupeFacet()),
      action: IDiamondCut.FacetCutAction.Add,
      functionSelectors: f1
    });

    LibDiamond._diamondCut(cut, address(0), "");
  }
}

lib/openzeppelin-contracts/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;
}

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);
}

src/diamond/contracts/Diamond.sol

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

import {LibDiamond} from "./libraries/LibDiamond.sol";

/// @notice EIP-2535 Diamond base: selector dispatch only.
/// @dev Deployment wiring (core facet cuts, ERC-165 registration, bootstrap
/// upgrader) lives in the Gemforge-generated `DiamondProxy`, which is rendered
/// from `templates/DiamondProxy.sol`. Keeping this contract free of
/// constructor logic is what lets Gemforge own the deployment entrypoint while
/// the dispatch and storage semantics stay first-party.
contract Diamond {
    error FunctionNotFound(bytes4 selector);

    fallback() external payable {
        address facet = LibDiamond._diamondStorage().selectorToFacetAndPosition[msg.sig].facetAddress;
        if (facet == address(0)) {
            revert FunctionNotFound(msg.sig);
        }

        // solhint-disable-next-line no-inline-assembly
        assembly ("memory-safe") {
            calldatacopy(0, 0, calldatasize())
            let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch result
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }
}

src/diamond/contracts/facets/DiamondCutFacet.sol

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

import {IDiamondCut} from "../interfaces/IDiamondCut.sol";
import {LibDiamond} from "../libraries/LibDiamond.sol";
import {LibOnReAccessControl} from "../../../libraries/LibOnReAccessControl.sol";
import {LibOnReRoles} from "../../../libraries/LibOnReRoles.sol";

contract DiamondCutFacet is IDiamondCut {
    function diamondCut(FacetCut[] calldata cut, address init, bytes calldata initCalldata) external override {
        LibOnReAccessControl._checkRole(LibOnReRoles.UPGRADER_ROLE);
        LibDiamond._diamondCut(cut, init, initCalldata);
    }
}

src/diamond/contracts/facets/DiamondLoupeFacet.sol

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

import {IERC165} from "../interfaces/IERC165.sol";
import {IDiamondLoupe} from "../interfaces/IDiamondLoupe.sol";
import {LibDiamond} from "../libraries/LibDiamond.sol";

contract DiamondLoupeFacet is IDiamondLoupe, IERC165 {
    function facets() external view override returns (Facet[] memory facets_) {
        LibDiamond.DiamondStorage storage ds = LibDiamond._diamondStorage();
        uint256 facetLength = ds.facetAddresses.length;
        facets_ = new Facet[](facetLength);
        for (uint256 i = 0; i < facetLength; ++i) {
            address facet = ds.facetAddresses[i];
            facets_[i] =
                Facet({facetAddress: facet, functionSelectors: ds.facetToFunctionSelectors[facet].functionSelectors});
        }
    }

    function facetFunctionSelectors(address facet) external view override returns (bytes4[] memory selectors) {
        selectors = LibDiamond._diamondStorage().facetToFunctionSelectors[facet].functionSelectors;
    }

    function facetAddresses() external view override returns (address[] memory facetAddresses_) {
        facetAddresses_ = LibDiamond._diamondStorage().facetAddresses;
    }

    function facetAddress(bytes4 functionSelector) external view override returns (address facetAddress_) {
        facetAddress_ = LibDiamond._diamondStorage().selectorToFacetAndPosition[functionSelector].facetAddress;
    }

    function supportsInterface(bytes4 interfaceId) external view override returns (bool) {
        return LibDiamond._diamondStorage().supportedInterfaces[interfaceId];
    }
}

src/diamond/contracts/interfaces/IDiamondCut.sol

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

interface IDiamondCut {
    enum FacetCutAction {
        Add,
        Replace,
        Remove
    }

    struct FacetCut {
        address facetAddress;
        FacetCutAction action;
        bytes4[] functionSelectors;
    }

    event DiamondCut(FacetCut[] diamondCut, address init, bytes initCalldata);

    function diamondCut(FacetCut[] calldata cut, address init, bytes calldata initCalldata) external;
}

src/diamond/contracts/interfaces/IDiamondLoupe.sol

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

interface IDiamondLoupe {
    struct Facet {
        address facetAddress;
        bytes4[] functionSelectors;
    }

    function facets() external view returns (Facet[] memory facets_);
    function facetFunctionSelectors(address facet) external view returns (bytes4[] memory selectors);
    function facetAddresses() external view returns (address[] memory facetAddresses_);
    function facetAddress(bytes4 functionSelector) external view returns (address facetAddress_);
}

src/diamond/contracts/interfaces/IERC165.sol

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

// Gemforge's non-overridable `IDiamondProxy` template imports IERC165 from
// `<paths.lib.diamond>/contracts/interfaces/IERC165.sol`, so a file must exist
// here. Re-exporting the OpenZeppelin declaration keeps a single IERC165 type
// across the build, so `type(IERC165).interfaceId` cannot drift between the
// generated proxy interface and the facets that register it.
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";

src/diamond/contracts/libraries/LibDiamond.sol

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

import {IDiamondCut} from "../interfaces/IDiamondCut.sol";

library LibDiamond {
    error EmptyFacetSelectors();
    error FacetHasNoCode(address facet);
    error FacetAddressIsZero();
    error FunctionAlreadyExists(bytes4 selector);
    error FunctionDoesNotExist(bytes4 selector);
    error FunctionIsImmutable(bytes4 selector);
    error FunctionAlreadyUsesFacet(bytes4 selector, address facet);
    error InvalidFacetCutAction(uint8 action);
    error InvalidInitialization(address init, bytes initCalldata);
    error InitializationReverted(address init, bytes initCalldata);
    error PositionOverflow(uint256 position);
    error RemoveFacetAddressMustBeZero(address facet);

    /// @custom:storage-location erc7201:onre.storage.Diamond
    struct DiamondStorage {
        mapping(bytes4 selector => FacetAddressAndPosition data) selectorToFacetAndPosition;
        mapping(address facet => FacetFunctionSelectors data) facetToFunctionSelectors;
        address[] facetAddresses;
        mapping(bytes4 interfaceId => bool supported) supportedInterfaces;
    }

    struct FacetAddressAndPosition {
        address facetAddress;
        uint32 functionSelectorPosition;
    }

    struct FacetFunctionSelectors {
        bytes4[] functionSelectors;
        uint32 facetAddressPosition;
    }

    // keccak256(abi.encode(uint256(keccak256("onre.storage.Diamond")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 internal constant DIAMOND_STORAGE_LOCATION =
        0xe7a65135aebfc21c80a162a36674f54347f18e2d3a36aad28796c9ad8e262e00;

    function _diamondStorage() internal pure returns (DiamondStorage storage ds) {
        bytes32 location = DIAMOND_STORAGE_LOCATION;
        // solhint-disable-next-line no-inline-assembly
        assembly ("memory-safe") {
            ds.slot := location
        }
    }

    function _diamondCut(IDiamondCut.FacetCut[] memory cut, address init, bytes memory initCalldata) internal {
        uint256 cutLength = cut.length;
        for (uint256 i = 0; i < cutLength; ++i) {
            IDiamondCut.FacetCut memory facetCut = cut[i];
            if (facetCut.action == IDiamondCut.FacetCutAction.Add) {
                _addFunctions(facetCut.facetAddress, facetCut.functionSelectors);
            } else if (facetCut.action == IDiamondCut.FacetCutAction.Replace) {
                _replaceFunctions(facetCut.facetAddress, facetCut.functionSelectors);
            } else if (facetCut.action == IDiamondCut.FacetCutAction.Remove) {
                _removeFunctions(facetCut.facetAddress, facetCut.functionSelectors);
            } else {
                revert InvalidFacetCutAction(uint8(facetCut.action));
            }
        }

        emit IDiamondCut.DiamondCut(cut, init, initCalldata);
        _initializeDiamondCut(init, initCalldata);
    }

    function _addFunctions(address facet, bytes4[] memory selectors) private {
        if (selectors.length == 0) {
            revert EmptyFacetSelectors();
        }
        if (facet == address(0)) {
            revert FacetAddressIsZero();
        }

        DiamondStorage storage ds = _diamondStorage();
        uint256 selectorPosition = ds.facetToFunctionSelectors[facet].functionSelectors.length;
        if (selectorPosition == 0) {
            _enforceHasContractCode(facet);
            ds.facetToFunctionSelectors[facet].facetAddressPosition = _toUint32(ds.facetAddresses.length);
            ds.facetAddresses.push(facet);
        }

        uint256 selectorLength = selectors.length;
        for (uint256 i = 0; i < selectorLength; ++i) {
            bytes4 selector = selectors[i];
            if (ds.selectorToFacetAndPosition[selector].facetAddress != address(0)) {
                revert FunctionAlreadyExists(selector);
            }
            ds.facetToFunctionSelectors[facet].functionSelectors.push(selector);
            ds.selectorToFacetAndPosition[selector] =
                FacetAddressAndPosition({facetAddress: facet, functionSelectorPosition: _toUint32(selectorPosition)});
            unchecked {
                ++selectorPosition;
            }
        }
    }

    function _replaceFunctions(address facet, bytes4[] memory selectors) private {
        if (selectors.length == 0) {
            revert EmptyFacetSelectors();
        }
        if (facet == address(0)) {
            revert FacetAddressIsZero();
        }

        DiamondStorage storage ds = _diamondStorage();
        uint256 selectorPosition = ds.facetToFunctionSelectors[facet].functionSelectors.length;
        if (selectorPosition == 0) {
            _enforceHasContractCode(facet);
            ds.facetToFunctionSelectors[facet].facetAddressPosition = _toUint32(ds.facetAddresses.length);
            ds.facetAddresses.push(facet);
        }

        uint256 selectorLength = selectors.length;
        for (uint256 i = 0; i < selectorLength; ++i) {
            bytes4 selector = selectors[i];
            address oldFacet = ds.selectorToFacetAndPosition[selector].facetAddress;
            if (oldFacet == address(0)) {
                revert FunctionDoesNotExist(selector);
            }
            if (oldFacet == facet) {
                revert FunctionAlreadyUsesFacet(selector, facet);
            }
            _removeFunction(oldFacet, selector);
            ds.facetToFunctionSelectors[facet].functionSelectors.push(selector);
            ds.selectorToFacetAndPosition[selector] =
                FacetAddressAndPosition({facetAddress: facet, functionSelectorPosition: _toUint32(selectorPosition)});
            unchecked {
                ++selectorPosition;
            }
        }
    }

    function _removeFunctions(address facet, bytes4[] memory selectors) private {
        if (selectors.length == 0) {
            revert EmptyFacetSelectors();
        }
        if (facet != address(0)) {
            revert RemoveFacetAddressMustBeZero(facet);
        }

        DiamondStorage storage ds = _diamondStorage();
        uint256 selectorLength = selectors.length;
        for (uint256 i = 0; i < selectorLength; ++i) {
            bytes4 selector = selectors[i];
            if (selector == IDiamondCut.diamondCut.selector) {
                revert FunctionIsImmutable(selector);
            }
            address oldFacet = ds.selectorToFacetAndPosition[selector].facetAddress;
            if (oldFacet == address(0)) {
                revert FunctionDoesNotExist(selector);
            }
            _removeFunction(oldFacet, selector);
        }
    }

    function _removeFunction(address facet, bytes4 selector) private {
        if (facet == address(this)) {
            revert FunctionIsImmutable(selector);
        }

        DiamondStorage storage ds = _diamondStorage();
        uint256 selectorPosition = ds.selectorToFacetAndPosition[selector].functionSelectorPosition;
        bytes4[] storage facetSelectors = ds.facetToFunctionSelectors[facet].functionSelectors;
        uint256 lastSelectorPosition = facetSelectors.length - 1;
        if (selectorPosition != lastSelectorPosition) {
            bytes4 lastSelector = facetSelectors[lastSelectorPosition];
            facetSelectors[selectorPosition] = lastSelector;
            ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = _toUint32(selectorPosition);
        }
        facetSelectors.pop();
        delete ds.selectorToFacetAndPosition[selector];

        if (lastSelectorPosition == 0) {
            uint256 facetPosition = ds.facetToFunctionSelectors[facet].facetAddressPosition;
            uint256 lastFacetPosition = ds.facetAddresses.length - 1;
            if (facetPosition != lastFacetPosition) {
                address lastFacet = ds.facetAddresses[lastFacetPosition];
                ds.facetAddresses[facetPosition] = lastFacet;
                ds.facetToFunctionSelectors[lastFacet].facetAddressPosition = _toUint32(facetPosition);
            }
            ds.facetAddresses.pop();
            delete ds.facetToFunctionSelectors[facet].facetAddressPosition;
        }
    }

    function _initializeDiamondCut(address init, bytes memory initCalldata) private {
        if (init == address(0)) {
            if (initCalldata.length != 0) {
                revert InvalidInitialization(init, initCalldata);
            }
            return;
        }
        if (initCalldata.length == 0) {
            revert InvalidInitialization(init, initCalldata);
        }
        if (init != address(this)) {
            _enforceHasContractCode(init);
        }

        (bool success, bytes memory returndata) = init.delegatecall(initCalldata);
        if (!success) {
            if (returndata.length == 0) {
                revert InitializationReverted(init, initCalldata);
            }
            // solhint-disable-next-line no-inline-assembly
            assembly ("memory-safe") {
                revert(add(returndata, 0x20), mload(returndata))
            }
        }
    }

    function _enforceHasContractCode(address target) private view {
        if (target.code.length == 0) {
            revert FacetHasNoCode(target);
        }
    }

    function _toUint32(uint256 position) private pure returns (uint32 result) {
        if (position > type(uint32).max) {
            revert PositionOverflow(position);
        }
        result = uint32(position);
    }
}

src/libraries/LibOnReAccessControl.sol

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

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {BossTransferCancelled, BossTransferStarted, BossTransferred} from "../types/OnReAppEvents.sol";
import {
    BossRoleManagedSeparatelyError,
    NoChangeError,
    NotPendingBossError,
    UnsupportedRoleError,
    ZeroAddressError
} from "../types/OnReAppErrors.sol";
import {LibOnReRoles} from "./LibOnReRoles.sol";

/// @notice Diamond-native role storage with the OpenZeppelin IAccessControl surface.
/// @dev Uses a dedicated ERC-7201 namespace so every facet observes the same roles.
library LibOnReAccessControl {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    /// @custom:storage-location erc7201:onre.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) roles;
        address boss;
        address pendingBoss;
    }

    // keccak256(abi.encode(uint256(keccak256("onre.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 internal constant ACCESS_CONTROL_STORAGE_POSITION =
        0xc22d749a08533429f9f6342546255c4b448fe8fd084608530dff3c1a7e045100;

    function _accessControlStorage() internal pure returns (AccessControlStorage storage s) {
        bytes32 position = ACCESS_CONTROL_STORAGE_POSITION;
        // solhint-disable-next-line no-inline-assembly
        assembly ("memory-safe") {
            s.slot := position
        }
    }

    function _hasRole(bytes32 role, address account) internal view returns (bool) {
        return _accessControlStorage().roles[role].hasRole[account];
    }

    function _checkRole(bytes32 role) internal view {
        _checkRole(role, msg.sender);
    }

    function _checkRole(bytes32 role, address account) internal view {
        if (!_hasRole(role, account)) {
            revert IAccessControl.AccessControlUnauthorizedAccount(account, role);
        }
    }

    function _getRoleAdmin(bytes32 role) internal view returns (bytes32) {
        return _accessControlStorage().roles[role].adminRole;
    }

    function _boss() internal view returns (address) {
        return _accessControlStorage().boss;
    }

    function _pendingBoss() internal view returns (address) {
        return _accessControlStorage().pendingBoss;
    }

    function _grantRole(bytes32 role, address account) internal {
        _requireSupportedRole(role);
        _requireNonBossRole(role);
        _checkRole(_getRoleAdmin(role));
        _grantRoleUnchecked(role, account);
    }

    function _revokeRole(bytes32 role, address account) internal {
        _requireSupportedRole(role);
        _requireNonBossRole(role);
        _checkRole(_getRoleAdmin(role));
        _revokeRoleUnchecked(role, account);
    }

    function _renounceRole(bytes32 role, address callerConfirmation) internal {
        _requireSupportedRole(role);
        _requireNonBossRole(role);
        if (callerConfirmation != msg.sender) {
            revert IAccessControl.AccessControlBadConfirmation();
        }
        _revokeRoleUnchecked(role, callerConfirmation);
    }

    function _initialize(address initialBoss, address admin, address worker, address upgrader) internal {
        _accessControlStorage().boss = initialBoss;
        _grantRoleUnchecked(LibOnReRoles.DEFAULT_ADMIN_ROLE, initialBoss);
        _grantRoleUnchecked(LibOnReRoles.ADMIN_ROLE, admin);
        _grantRoleUnchecked(LibOnReRoles.WORKER_ROLE, worker);
        _grantRoleUnchecked(LibOnReRoles.UPGRADER_ROLE, upgrader);
    }

    function _beginBossTransfer(address newBoss) internal {
        _checkRole(LibOnReRoles.DEFAULT_ADMIN_ROLE);
        if (newBoss == address(0)) revert ZeroAddressError();

        AccessControlStorage storage s = _accessControlStorage();
        if (newBoss == s.boss || newBoss == s.pendingBoss) revert NoChangeError();

        address previousPendingBoss = s.pendingBoss;
        if (previousPendingBoss != address(0)) {
            emit BossTransferCancelled(s.boss, previousPendingBoss);
        }
        s.pendingBoss = newBoss;
        emit BossTransferStarted(s.boss, newBoss);
    }

    function _cancelBossTransfer() internal {
        _checkRole(LibOnReRoles.DEFAULT_ADMIN_ROLE);

        AccessControlStorage storage s = _accessControlStorage();
        address cancelledPendingBoss = s.pendingBoss;
        if (cancelledPendingBoss == address(0)) revert NoChangeError();

        s.pendingBoss = address(0);
        emit BossTransferCancelled(s.boss, cancelledPendingBoss);
    }

    function _acceptBossTransfer() internal {
        AccessControlStorage storage s = _accessControlStorage();
        address newBoss = s.pendingBoss;
        if (msg.sender != newBoss) revert NotPendingBossError(msg.sender);

        address previousBoss = s.boss;
        s.pendingBoss = address(0);
        s.boss = newBoss;
        _revokeRoleUnchecked(LibOnReRoles.DEFAULT_ADMIN_ROLE, previousBoss);
        _grantRoleUnchecked(LibOnReRoles.DEFAULT_ADMIN_ROLE, newBoss);
        emit BossTransferred(previousBoss, newBoss);
    }

    function _requireSupportedRole(bytes32 role) private pure {
        if (!LibOnReRoles._isSupportedRole(role)) revert UnsupportedRoleError(role);
    }

    function _requireNonBossRole(bytes32 role) private pure {
        if (role == LibOnReRoles.DEFAULT_ADMIN_ROLE) {
            revert BossRoleManagedSeparatelyError();
        }
    }

    function _grantRoleUnchecked(bytes32 role, address account) internal returns (bool granted) {
        AccessControlStorage storage s = _accessControlStorage();
        if (!s.roles[role].hasRole[account]) {
            s.roles[role].hasRole[account] = true;
            emit IAccessControl.RoleGranted(role, account, msg.sender);
            granted = true;
        }
    }

    function _revokeRoleUnchecked(bytes32 role, address account) internal returns (bool revoked) {
        AccessControlStorage storage s = _accessControlStorage();
        if (s.roles[role].hasRole[account]) {
            s.roles[role].hasRole[account] = false;
            emit IAccessControl.RoleRevoked(role, account, msg.sender);
            revoked = true;
        }
    }
}

src/libraries/LibOnReRoles.sol

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

/// @notice Application roles include the authority used for Diamond upgrades.
library LibOnReRoles {
    bytes32 internal constant DEFAULT_ADMIN_ROLE = bytes32(0);
    bytes32 internal constant ADMIN_ROLE = keccak256("ONRE_ADMIN_ROLE");
    bytes32 internal constant WORKER_ROLE = keccak256("ONRE_WORKER_ROLE");
    bytes32 internal constant UPGRADER_ROLE = keccak256("ONRE_UPGRADER_ROLE");

    function _isSupportedRole(bytes32 role) internal pure returns (bool) {
        return role == DEFAULT_ADMIN_ROLE || role == ADMIN_ROLE || role == WORKER_ROLE || role == UPGRADER_ROLE;
    }
}

src/types/OnReAppErrors.sol

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

error ZeroAddressError();
error InvalidAmountError();
error InvalidFeeError();
error InvalidBasisPointsError();
error InvalidTokenError();
error InvalidManagedTokenImplementationError(address implementation);
error InvalidDecimalsError();
error InvalidApprovalError();
error InvalidPermissionlessSettlementAccountError(address account);
error PermissionlessSettlementAccountNotSetError();
error InvalidOfferDirectionError();
error InvalidFlowQuoterError();
error UnsupportedOfferFlowError(uint8 flow);
error TakeOfferDeadlineExpiredError(uint64 deadline);
error MinimumAmountOutNotMetError(uint256 minimumAmountOut, uint256 actualAmountOut);
error WorkerOfferRequiresFulfillmentRequestError(bytes32 offerConfigId);
error KilledError();
error ExactAssetTransferRequiredError(address asset, uint256 expectedAmount, uint256 receivedAmount);
error ExactAssetDebitRequiredError(address asset, uint256 expectedAmount, uint256 debitedAmount);
error ExcludedSupplyAddressAlreadyExistsError(address managedToken, address account);
error ExcludedSupplyAddressNotFoundError(address managedToken, address account);
error TooManyExcludedSupplyAddressesError(address managedToken);
error TokenNotRegisteredError(address managedToken);
error TokenAlreadyRegisteredError(address managedToken);
error PricerAlreadyExistsError(bytes32 pricerId);
error PricerNotFoundError(bytes32 pricerId);
error PricerDisabledError(bytes32 pricerId);
error QuoterAlreadyExistsError(bytes32 quoterId);
error QuoterNotFoundError(bytes32 quoterId);
error QuoterDisabledError(bytes32 quoterId);
error PropAmmConfigurationRequiredError();
error InvalidQuoterKindError(bytes32 quoterId, uint8 expectedKind, uint8 actualKind);
error UnsupportedQuoterKindError(bytes32 quoterId, uint8 kind);
error InvalidPropAmmPairError(bytes32 quoterId, address tokenIn, address tokenOut);
error FeeConfigAlreadyExistsError(bytes32 feeConfigId);
error FeeConfigNotFoundError(bytes32 feeConfigId);
error FeeConfigDisabledError(bytes32 feeConfigId);
error ConfigurableVaultAlreadyExistsError(bytes32 vaultId);
error ConfigurableVaultNotFoundError(bytes32 vaultId);
error InvalidConfigurableVaultKindError(bytes32 vaultId, uint8 expectedKind, uint8 actualKind);
error UnsupportedConfigurableVaultKindError(uint8 kind);
error BufferAlreadyExistsError(address managedToken);
error BufferNotFoundError(address managedToken);
error InvalidBufferAprError(uint256 grossApr);
error InvalidBufferControllerError(address managedToken, address controller);
error BufferSupplyMismatchError(address managedToken, uint256 expectedSupply, uint256 actualSupply);
error BufferReserveExcludedFromSupplyError(address managedToken);
error InvalidAssetAdjustmentAmountError();
error NoBurnNeededError();
error MissingConfigurableVaultDestinationError(bytes32 vaultId);
error OfferConfigAlreadyExistsError(bytes32 offerConfigId);
error OfferConfigNotFoundError(bytes32 offerConfigId);
error OfferConfigDisabledError(bytes32 offerConfigId);
error FulfillmentRequestAlreadyExistsError(bytes32 fulfillmentRequestId);
error FulfillmentRequestNotFoundError(bytes32 fulfillmentRequestId);
error FulfillmentAmountExceedsRemainingError(bytes32 fulfillmentRequestId, uint256 amount, uint256 remaining);
error LiquidityVaultRequiredError(bytes32 offerConfigId);
error InsufficientLiquidityError(bytes32 vaultId, address token, uint256 availableAmount, uint256 requiredAmount);
error ZeroBalanceError();
error InsufficientBalanceError(uint256 availableAmount, uint256 requestedAmount);
error UnauthorizedError(address sender);
error UnsupportedRoleError(bytes32 role);
error BossRoleManagedSeparatelyError();
error NotPendingBossError(address account);
error BothApproversFilledError();
error ApproverAlreadyExistsError(address approver);
error NotApproverError(address approver);
error NoChangeError();
error TooManyVectorsError();
error DuplicateVectorStartTimeError(uint64 startTime);
error InvalidVectorOrderError();
error VectorBaseTimeAfterStartTimeError(uint64 baseTime, uint64 startTime);
error VectorStartTimeInPastError(uint64 startTime, uint64 currentTime);
error VectorNotFoundError(uint64 startTime);
error VectorIndexOutOfBoundsError(uint8 vectorIndex, uint8 vectorCount);
error NoActiveVectorError(bytes32 pricerId);

src/types/OnReAppEvents.sol

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

import {ConfigurableVaultKind, OfferDirection, OfferFlow, PricingDenomination, QuoterKind} from "./OnReTypes.sol";

event ManagedTokenRegistered(address indexed managedToken, uint8 decimals);
event ManagedTokenDeployed(
    address indexed managedToken,
    address indexed admin,
    address indexed ccipAdmin,
    address implementation,
    string name,
    string symbol,
    uint8 decimals
);
event ManagedTokenEnabledSet(address indexed managedToken, bool enabled);
event ExcludedSupplyAddressAdded(address indexed managedToken, address indexed account);
event ExcludedSupplyAddressRemoved(address indexed managedToken, address indexed account);

event PricerCreated(bytes32 indexed pricerId, address indexed managedToken, PricingDenomination denomination);
event PricingVectorAdded(
    bytes32 indexed pricerId, uint64 startTime, uint64 baseTime, uint256 basePrice, uint256 apr, uint64 priceFixDuration
);
event PricingVectorDeleted(bytes32 indexed pricerId, uint64 startTime);
event PricingVectorEvicted(bytes32 indexed pricerId, uint64 startTime);
event AllPricingVectorsDeleted(bytes32 indexed pricerId, uint8 vectorsDeletedCount);
event PricerEnabledSet(bytes32 indexed pricerId, bool enabled);

event QuoterCreated(bytes32 indexed quoterId, QuoterKind indexed kind, uint64 indexed instanceId);
event QuoterEnabledSet(bytes32 indexed quoterId, bool enabled);
event PropAmmConfigured(
    bytes32 indexed quoterId,
    address indexed assetToken,
    address indexed managedToken,
    uint16 curvePegHaircutBps,
    uint32 curveExponentScaled,
    uint32 cadenceThreshold,
    uint32 cadenceWaveScaled,
    uint64 epochDurationSeconds,
    uint32 wallSensitivityScaled
);

event FeeConfigCreated(
    bytes32 indexed feeConfigId,
    uint64 indexed instanceId,
    uint16 basisPoints,
    uint256 minimumFeeAmount,
    bytes32 feeVaultId
);
event FeeConfigUpdated(bytes32 indexed feeConfigId, uint16 basisPoints, uint256 minimumFeeAmount, bytes32 feeVaultId);
event FeeConfigEnabledSet(bytes32 indexed feeConfigId, bool enabled);

event OfferConfigCreated(
    bytes32 indexed offerConfigId,
    address indexed tokenIn,
    address indexed tokenOut,
    OfferFlow flow,
    OfferDirection direction,
    bytes32 quoterId,
    bytes32 feeConfigId,
    bytes32 proceedsVaultId,
    bytes32 liquidityVaultId
);
event OfferConfigReferencesUpdated(
    bytes32 indexed offerConfigId,
    bytes32 quoterId,
    bytes32 feeConfigId,
    bytes32 proceedsVaultId,
    bytes32 liquidityVaultId
);
event OfferConfigEnabledSet(bytes32 indexed offerConfigId, bool enabled);
event OfferExecuted(
    bytes32 indexed offerConfigId,
    address indexed user,
    OfferFlow indexed flow,
    uint256 grossInputAmount,
    uint256 feeAmount,
    uint256 netInputAmount,
    uint256 amountOut,
    uint256 price,
    uint256 liquidityRefillAmount,
    uint256 proceedsAmount
);

event FulfillmentRequested(
    bytes32 indexed fulfillmentRequestId,
    bytes32 indexed offerConfigId,
    address indexed user,
    uint64 requestId,
    uint256 inputAmount
);
event FulfillmentRequestCancelled(
    bytes32 indexed fulfillmentRequestId,
    bytes32 indexed offerConfigId,
    address indexed user,
    uint256 returnedAmount,
    address cancelledBy
);
event FulfillmentRequestFilled(
    bytes32 indexed fulfillmentRequestId,
    bytes32 indexed offerConfigId,
    address indexed user,
    uint256 fulfilledInputAmount,
    uint256 totalFulfilledInputAmount,
    uint256 feeAmount,
    uint256 amountOut,
    uint256 price,
    bool fullyFulfilled
);

event ConfigurableVaultCreated(
    bytes32 indexed vaultId,
    ConfigurableVaultKind indexed kind,
    uint64 indexed instanceId,
    address withdrawalDestination,
    uint16 refillTargetBps
);
event ConfigurableVaultUpdated(bytes32 indexed vaultId, address withdrawalDestination, uint16 refillTargetBps);
event ConfigurableVaultAccrued(bytes32 indexed vaultId, address indexed token, uint256 amount, uint256 newBalance);
event ConfigurableVaultWithdrawn(
    bytes32 indexed vaultId, address indexed token, address indexed destination, uint256 amount
);

event BufferInitialized(
    address indexed managedToken,
    bytes32 indexed reserveVaultId,
    bytes32 managementFeeVaultId,
    bytes32 performanceFeeVaultId,
    uint64 timestamp
);
event BufferGrossAprUpdated(address indexed managedToken, uint64 oldGrossApr, uint64 newGrossApr);
event BufferFeeConfigUpdated(
    address indexed managedToken,
    uint16 oldManagementFeeBasisPoints,
    uint16 newManagementFeeBasisPoints,
    uint16 oldPerformanceFeeBasisPoints,
    uint16 newPerformanceFeeBasisPoints,
    bool oldPerformanceFeeHighWatermarkEnabled,
    bool newPerformanceFeeHighWatermarkEnabled
);
event BufferAccrued(
    address indexed managedToken,
    uint256 secondsElapsed,
    uint256 aprDelta,
    uint256 bufferMintAmount,
    uint256 reserveMintAmount,
    uint256 managementFeeMintAmount,
    uint256 performanceFeeMintAmount,
    uint256 oldPreviousSupply,
    uint256 newPreviousSupply,
    uint256 oldPerformanceFeeHighWatermark,
    uint256 newPerformanceFeeHighWatermark,
    uint256 currentNav,
    uint64 timestamp
);
event BufferSupplyChangeRecorded(
    address indexed managedToken,
    bool indexed isMint,
    uint256 amount,
    uint256 oldPreviousSupply,
    uint256 newPreviousSupply
);
event BufferBurnedForNav(
    address indexed managedToken,
    uint256 burnAmount,
    uint256 assetAdjustmentAmount,
    uint256 totalAssets,
    uint256 targetNav
);

event ApproverAdded(address indexed approver);
event ApproverRemoved(address indexed approver);
event PermissionlessSettlementAccountUpdated(address indexed previousAccount, address indexed newAccount);
event KillSwitchSet(bool isKilled);

event BossTransferStarted(address indexed currentBoss, address indexed pendingBoss);
event BossTransferCancelled(address indexed currentBoss, address indexed cancelledPendingBoss);
event BossTransferred(address indexed previousBoss, address indexed newBoss);

src/types/OnReTypes.sol

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

enum PricingDenomination {
    Usd
}

enum OfferFlow {
    Permissioned,
    Permissionless,
    Worker
}

enum OfferDirection {
    AssetToManaged,
    ManagedToAsset
}

enum QuoterKind {
    Nav,
    NavPermissionless,
    PropAmm
}

enum ConfigurableVaultKind {
    Fee,
    Proceeds,
    Liquidity,
    BufferReserve
}

struct InitializeParams {
    /// @dev Initial DEFAULT_ADMIN_ROLE holder with full application authority.
    address boss;
    /// @dev Initial ADMIN_ROLE holder; can only enable the kill switch.
    address admin;
    /// @dev Initial WORKER_ROLE holder; can fulfill or administratively cancel requests.
    address worker;
    /// @dev Initial UPGRADER_ROLE holder; can execute Diamond cuts.
    address upgrader;
    address[] approvers;
}

struct ManagedTokenConfig {
    uint8 decimals;
    bool enabled;
    bool exists;
}

struct PricingVector {
    uint64 startTime;
    uint64 baseTime;
    uint64 basePrice;
    uint64 apr;
    uint64 priceFixDuration;
}

struct Pricer {
    PricingVector[10] vectors;
    address managedToken;
    PricingDenomination denomination;
    uint8 vectorCount;
    bool enabled;
    bool exists;
}

struct Quoter {
    QuoterKind kind;
    uint64 instanceId;
    bool enabled;
    bool exists;
}

struct PropAmmConfig {
    uint64 epochDurationSeconds;
    uint32 curveExponentScaled;
    uint32 cadenceThreshold;
    uint32 cadenceWaveScaled;
    uint32 wallSensitivityScaled;
    uint16 curvePegHaircutBps;
}

struct PropAmmState {
    uint256 currentSellValueStable;
    uint256 currentBuyValueStable;
    uint256 previousNetSellValueStable;
    PropAmmConfig config;
    address managedToken;
    uint64 epochStart;
    uint32 currentSellTradeCount;
    address assetToken;
}

struct FeeConfig {
    bytes32 feeVaultId;
    uint64 feeConfigId;
    uint16 basisPoints;
    bool enabled;
    bool exists;
    uint256 minimumFeeAmount;
}

struct ConfigurableVault {
    ConfigurableVaultKind kind;
    uint64 vaultId;
    address withdrawalDestination;
    uint16 refillTargetBps;
    bool exists;
}

struct BufferState {
    bytes32 reserveVaultId;
    bytes32 managementFeeVaultId;
    bytes32 performanceFeeVaultId;
    uint256 previousSupply;
    uint256 performanceFeeHighWatermark;
    uint64 lastAccrualTimestamp;
    uint64 grossApr;
    uint16 managementFeeBasisPoints;
    uint16 performanceFeeBasisPoints;
    bool performanceFeeHighWatermarkEnabled;
    bool exists;
}

struct OfferConfig {
    address tokenIn;
    OfferFlow flow;
    OfferDirection direction;
    bytes32 quoterId;
    bytes32 feeConfigId;
    bytes32 proceedsVaultId;
    bytes32 liquidityVaultId;
    address tokenOut;
    uint8 tokenOutDecimals;
    uint8 tokenInDecimals;
    bool enabled;
    bool exists;
}

struct MakeOfferConfigParams {
    address tokenIn;
    address tokenOut;
    OfferFlow flow;
    bytes32 quoterId;
    bytes32 feeConfigId;
    bytes32 proceedsVaultId;
    bytes32 liquidityVaultId;
}

struct FulfillmentRequest {
    bytes32 offerConfigId;
    uint256 inputAmount;
    uint256 fulfilledInputAmount;
    uint64 requestId;
    address user;
    bool exists;
}

struct MarketStats {
    uint256 apy;
    uint256 circulatingSupply;
    uint256 nav;
    int256 navAdjustment;
    uint256 tvl;
    uint64 lastUpdatedAt;
    uint64 lastUpdatedBlock;
}

struct ApprovalMessage {
    address user;
    uint64 expiry;
}

struct TakeOfferParams {
    bytes32 offerConfigId;
    uint256 grossInputAmount;
    uint256 minimumAmountOut;
    uint64 deadline;
    ApprovalMessage approval;
    bytes signature;
}

struct QuoteResult {
    uint256 price;
    uint256 amountOut;
}

struct ExecutionAccounting {
    uint256 price;
    uint256 grossInputAmount;
    uint256 feeAmount;
    uint256 netInputAmount;
    uint256 amountOut;
    uint256 liquidityRefillAmount;
    uint256 proceedsAmount;
}
Настройки компилятораПоказать
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    "@chainlink/contracts-ccip/=lib/chainlink-ccip/chains/evm/",
    "@chainlink/contracts/=lib/chainlink-evm/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "src/=src/",
    "chainlink-ccip/=lib/chainlink-ccip/chains/evm/contracts/vendor/optimism/interop-lib/v0/src/",
    "chainlink-evm/=lib/chainlink-evm/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.