STBL_LT1_Vault

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "contracts/Assets/LT1/STBL_LT1_Vault.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts-upgradeable/metatx/ERC2771ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import "../../interfaces/ISTBL_Register.sol";
import "../../interfaces/ISTBL_Core.sol";

import "./interfaces/ISTBL_LT1_AssetIssuer.sol";
import "./interfaces/ISTBL_LT1_AssetVault.sol";
import "./interfaces/ISTBL_LT1_AssetYieldDistributor.sol";
import "./interfaces/ISTBL_LT1_AssetOracle.sol";

import "../../lib/STBL_AssetDefinitionLib.sol";
import "../../lib/STBL_Structs.sol";
import "../../lib/STBL_Errors.sol";
import "../../lib/STBL_DecimalConverter.sol";

import "./lib/STBL_OracleLib.sol";
import "./lib/STBL_LT1_Asset_Errors.sol";

/**
 * @title STBL LT1 Asset Vault
 * @notice Manages the secure storage and handling of USDY assets in the STBL Protocol
 * @dev Implements access control for asset custody, yield distribution, and fee management
 * @dev Inherits from iSTBL_AssetVault interface and ERC2771Context for meta-transaction support
 * @author STBL Protocol Team
 */
contract STBL_LT1_Vault is
    Initializable,
    iSTBL_LT1_AssetVault,
    ERC2771ContextUpgradeable,
    UUPSUpgradeable
{
    using SafeERC20 for IERC20;
    using STBL_AssetDefinitionLib for AssetDefinition;
    using STBL_OracleLib for iSTBL_LT1_AssetOracle;
    using DecimalConverter for uint256;

    /** @notice Role identifier for contract upgrade authorization */
    bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");

    /** @notice Current implementation version for upgrade tracking */
    uint256 private _version;

    /** @notice Protocol registry contract providing system configuration and access control */
    iSTBL_Register private registry;

    /** @notice Unique identifier for the asset type managed by this vault instance */
    uint256 private assetID;

    /** @notice Complete vault state including deposits, fees, yields, and tracking metrics */
    VaultStruct private VaultData;

    /** @dev Reserved storage slots for future contract upgrades (60 slots = 1920 bytes) */
    uint256[60] private __gap;

    /**
     * @notice Ensures the caller is the valid issuer for this asset
     * @dev Fetches asset data from registry and validates issuer permissions
     * @dev Reverts with STBL_Asset_InvalidIssuer if caller is not authorized
     */
    modifier isValidIssuer() {
        AssetDefinition memory AssetData = registry.fetchAssetData(assetID);
        if (!AssetData.isIssuer(msg.sender))
            revert STBL_Asset_InvalidIssuer(assetID);
        _;
    }

    /**
     * @notice Initializes the contract implementation without setting up state
     * @dev Constructor for upgradeable contracts - actual initialization happens in initialize()
     * @dev Sets up ERC2771Context with zero address (forwarder set later via registry)
     * @custom:oz-upgrades-unsafe-allow constructor
     */
    constructor() ERC2771ContextUpgradeable(address(0)) {}

    /**
     * @notice Initializes the vault with asset ID and registry configuration
     * @dev Sets up access control, UUPS upgradeability, and associates vault with specific asset
     * @dev Can only be called once during proxy deployment
     * @param _id Unique identifier of the asset this vault will manage
     * @param _registry Address of the protocol registry containing system configuration
     */
    function initialize(uint256 _id, address _registry) public initializer {
        __UUPSUpgradeable_init();

        registry = iSTBL_Register(_registry);
        assetID = _id;
    }

    /**
     * @notice Authorizes contract upgrades for addresses with UPGRADER_ROLE
     * @dev Validates upgrade permissions through registry and increments version counter
     * @dev Required by UUPS proxy pattern for upgrade authorization
     * @param newImplementation Address of the new implementation contract to upgrade to
     */
    function _authorizeUpgrade(address newImplementation) internal override {
        if (!registry.hasRole(UPGRADER_ROLE, _msgSender()))
            revert STBL_UnauthorizedCaller();
        _version = _version + 1;
        emit ContractUpgraded(newImplementation);
    }

    /**
     * @notice Returns the current contract implementation version
     * @dev Version increments with each successful upgrade for tracking purposes
     * @return Current version number of the contract implementation
     */
    function version() external view returns (uint256) {
        return _version;
    }

    /**
     * @notice Handles secure ERC20 token deposits into the asset vault
     * @dev Validates and processes token deposits with comprehensive metadata tracking
     * @dev Updates vault state including gross/net deposits, fees, and USD values
     * @dev Only callable by valid asset issuers
     * @param _from Address initiating the token deposit
     * @param MetaData Structured data containing deposit value, fees, haircuts and other token metadata
     * @custom:event depositEvent Emitted when a deposit is processed with comprehensive deposit details
     */
    function depositERC20(
        address _from,
        YLD_Metadata memory MetaData
    ) external isValidIssuer {
        AssetDefinition memory AssetData = registry.fetchAssetData(assetID);

        IERC20(AssetData.token).safeTransferFrom(
            _from,
            address(this),
            MetaData.assetValue.convertFrom18Decimals(
                DecimalConverter.getTokenDecimals(AssetData.token)
            )
        );

        uint256 depositFeesAssetValue = iSTBL_LT1_AssetOracle(AssetData.oracle)
            .fetchInversePrice(MetaData.depositfeeAmount);
        uint256 insuranceFeeAssetValue = iSTBL_LT1_AssetOracle(AssetData.oracle)
            .fetchInversePrice(MetaData.insurancefeeAmount);

        // Store asset Values gross and net
        VaultData.assetDepositGross += MetaData.assetValue;
        VaultData.assetDepositNet += (MetaData.assetValue -
            (depositFeesAssetValue + insuranceFeeAssetValue));

        //Aggregate Stable Value distributed
        VaultData.depositValueUSD +=
            MetaData.stableValueNet +
            MetaData.haircutAmount;

        //Aggregate fees Values added
        VaultData.depositFees += depositFeesAssetValue;
        VaultData.insuranceFees += insuranceFeeAssetValue;

        //Aggregate haircut Values added
        VaultData.cumilativeHairCutValue += MetaData.haircutAmount;

        emit depositEvent(
            AssetData.token,
            _from,
            MetaData.assetValue,
            MetaData.depositfeeAmount,
            MetaData.insurancefeeAmount,
            MetaData.haircutAmount,
            depositFeesAssetValue,
            insuranceFeeAssetValue
        );
    }

    /**
     * @notice Handles ERC20 token withdrawals from the vault
     * @dev Processes withdrawal requests with fee calculations and vault state updates
     * @dev Calculates withdrawal amounts using oracle pricing and applies withdrawal fees
     * @dev Only callable by valid asset issuers
     * @param _to Address to receive the withdrawn tokens
     * @param MetaData Structured data containing withdrawal value, fees, haircuts and other metadata
     * @custom:event withdrawEvent Emitted when a withdrawal is processed with comprehensive withdrawal details
     */
    function withdrawERC20(
        address _to,
        YLD_Metadata memory MetaData
    ) external isValidIssuer {
        AssetDefinition memory AssetData = registry.fetchAssetData(assetID);

        if (
            iSTBL_LT1_AssetOracle(AssetData.oracle).fetchForwardPrice(
                VaultData.assetDepositNet
            ) < (VaultData.depositValueUSD)
        )
            revert STBL_Asset_InsufficientVaultValue(
                iSTBL_LT1_AssetOracle(AssetData.oracle).fetchForwardPrice(
                    VaultData.assetDepositNet
                ),
                VaultData.depositValueUSD
            );

        // Calculate Withdraw asset value
        uint256 withdrawAssetValue = iSTBL_LT1_AssetOracle(AssetData.oracle)
            .fetchInversePrice(
                ((MetaData.stableValueNet + MetaData.haircutAmount) -
                    MetaData.withdrawfeeAmount)
            );

        uint256 withdrawFeeAssetValue = iSTBL_LT1_AssetOracle(AssetData.oracle)
            .fetchInversePrice(MetaData.withdrawfeeAmount);

        // Transfer Asset outward post decimal conversion
        IERC20(AssetData.token).safeTransfer(
            _to,
            withdrawAssetValue.convertFrom18Decimals(
                DecimalConverter.getTokenDecimals(AssetData.token)
            )
        );

        // Deduct Withdraw fees
        VaultData.withdrawFees += withdrawFeeAssetValue;

        // Deduct USD Value Withdrawn
        VaultData.depositValueUSD -=
            MetaData.stableValueNet +
            MetaData.haircutAmount;

        // Deduct Hair Cut values
        VaultData.cumilativeHairCutValue -= MetaData.haircutAmount; // look at this in depth

        //
        VaultData.assetDepositNet -= (withdrawAssetValue +
            withdrawFeeAssetValue);
        VaultData.assetDepositGross -= MetaData.assetValue;

        emit withdrawEvent(
            AssetData.token,
            _to,
            withdrawAssetValue,
            MetaData.withdrawfeeAmount,
            withdrawFeeAssetValue,
            MetaData.haircutAmount
        );
    }

    /**
     * @notice Calculates the price difference between current oracle value and tracked USD value
     * @dev Internal method to compute potential yield based on asset price appreciation
     * @dev Used to determine if there are profits available for yield distribution
     * @return priceDifferential The calculated price differential in USD (18 decimals), or 0 if no positive differential exists
     */
    function iCalculatePriceDifferentiation() internal view returns (uint256) {
        AssetDefinition memory AssetData = registry.fetchAssetData(assetID);

        uint256 USDValueOfDepositValue = iSTBL_LT1_AssetOracle(AssetData.oracle)
            .fetchForwardPrice(VaultData.assetDepositNet);

        if (USDValueOfDepositValue > VaultData.depositValueUSD) {
            return USDValueOfDepositValue - VaultData.depositValueUSD;
        } else {
            return (0);
        }
    }

    /**
     * @notice Distributes accumulated yield from asset appreciation to the reward distributor
     * @dev Calculates yield differentials, applies protocol yield fees, and transfers tokens to distributor
     * @dev Only distributes yield if there is a positive price differential
     * @dev Updates vault state to reflect yield distribution and fee collection
     * @custom:event YieldDistributed Emitted when yield is successfully distributed with comprehensive yield details
     */
    function distributeYield() external {
        AssetDefinition memory AssetData = registry.fetchAssetData(assetID);
        uint256 differentialUSD = iCalculatePriceDifferentiation();

        if (differentialUSD > 0) {
            (uint256 yield, uint256 yieldFee) = AssetData.calculateYieldFee(
                differentialUSD
            );

            uint256 yieldFeeAssetValue = iSTBL_LT1_AssetOracle(AssetData.oracle)
                .fetchInversePrice(yieldFee);

            uint256 yieldAssetValue = iSTBL_LT1_AssetOracle(AssetData.oracle)
                .fetchInversePrice(yield);

            VaultData.yieldFees += yieldFeeAssetValue;

            IERC20(AssetData.token).approve(
                AssetData.rewardDistributor,
                yieldAssetValue.convertFrom18Decimals(
                    DecimalConverter.getTokenDecimals(AssetData.token)
                )
            );

            VaultData.assetDepositNet -= yieldAssetValue + yieldFeeAssetValue;

            iSTBL_LT1_AssetYieldDistributor(AssetData.rewardDistributor)
                .distributeReward(
                    yieldAssetValue.convertFrom18Decimals(
                        DecimalConverter.getTokenDecimals(AssetData.token)
                    )
                );

            emit YieldDistributed(
                AssetData.token,
                AssetData.rewardDistributor,
                yield,
                yieldFee,
                yieldAssetValue
            );
        }
    }

    /**
     * @notice Public view function to calculate the price differentiation for the asset
     * @dev External wrapper for the internal price differentiation calculation
     * @dev Used by external contracts or interfaces to check yield potential
     * @return priceDifferential The calculated price differentiation value in USD (18 decimals)
     */
    function CalculatePriceDifferentiation() external view returns (uint256) {
        return iCalculatePriceDifferentiation();
    }

    /**
     * @notice Withdraws all accumulated fees to the protocol treasury
     * @dev Transfers deposit fees, withdrawal fees, yield fees, and insurance fees to treasury
     * @dev Resets all fee counters to zero after successful transfer
     * @dev Reverts if treasury address is not set in the registry
     * @custom:event FeesWithdrawn Emitted when fees are successfully withdrawn with detailed fee breakdown
     */
    function withdrawFees() external {
        AssetDefinition memory AssetData = registry.fetchAssetData(assetID);
        address treasury = registry.fetchTreasury();

        if (treasury == address(0)) revert STBL_InvalidTreasury();

        // Calculate fees Value
        uint256 Fees = VaultData.depositFees +
            VaultData.withdrawFees +
            VaultData.yieldFees +
            VaultData.insuranceFees;

        //Transfer Fees Outside
        IERC20(AssetData.token).safeTransfer(
            treasury,
            Fees.convertFrom18Decimals(
                DecimalConverter.getTokenDecimals(AssetData.token)
            )
        );
        emit FeesWithdrawn(
            treasury,
            VaultData.depositFees,
            VaultData.withdrawFees,
            VaultData.yieldFees,
            VaultData.insuranceFees,
            Fees
        );

        // Reset Counters
        VaultData.depositFees = 0;
        VaultData.withdrawFees = 0;
        VaultData.yieldFees = 0;
        VaultData.insuranceFees = 0;
    }

    /**
     * @notice Drains a specified amount of tokens from the vault to treasury during emergency situations
     * @dev Emergency function that transfers tokens directly to treasury when asset is disabled
     * @dev Can only be executed when the asset status is not ENABLED for security purposes
     * @dev Reduces the net asset deposit tracking by the withdrawn amount
     * @custom:event EmergencyFundsWithdraw Emitted with the amount of tokens withdrawn
     * @custom:security Only callable when asset is disabled and treasury address is valid
     */
    function emergencyWithdraw() external {
        AssetDefinition memory AssetData = registry.fetchAssetData(assetID);
        address treasury = registry.fetchTreasury();

        if (treasury == address(0)) revert STBL_InvalidTreasury();
        if (AssetData.status != AssetStatus.EMERGENCY_STOP)
            revert STBL_AssetActive();

        uint256 balance = IERC20(AssetData.token).balanceOf(address(this));

        IERC20(AssetData.token).safeTransfer(treasury, balance);
        emit EmergencyFundsWithdraw(balance);
    }

    /**
     * @notice Retrieves the asset ID managed by this vault instance
     * @dev Returns the unique identifier for the asset type this vault handles
     * @return The asset ID associated with this vault
     */
    function fetchAssetID() external view returns (uint256) {
        return assetID;
    }

    /**
     * @notice Retrieves the protocol registry contract address
     * @dev Returns the registry contract that provides system configuration and access control
     * @return The address of the protocol registry contract
     */
    function fetchRegistry() external view returns (address) {
        return address(registry);
    }

    /**
     * @notice Retrieves the complete vault state data
     * @dev Returns all vault metrics including deposits, fees, yields, and tracking values
     * @return VaultStruct containing comprehensive vault state information
     */
    function fetchVaultData() external view returns (VaultStruct memory) {
        return VaultData;
    }

    /**
     * @notice Returns the address of the trusted forwarder for meta-transactions
     * @dev Used by ERC2771Context to validate meta-transaction relayers
     * @dev Retrieves the trusted forwarder address from the registry
     * @return forwarder The address of the current trusted forwarder
     */
    function trustedForwarder() public view virtual override returns (address) {
        return registry.trustedForwarder();
    }

    /**
     * @notice Resolves message sender in the context of potential meta-transactions
     * @dev Overrides both Context and ERC2771Context to handle inheritance conflicts
     * @dev Returns the actual transaction originator when using meta-transactions via trusted forwarder
     * @return The address of the actual message sender, accounting for meta-transaction forwarding
     */
    function _msgSender()
        internal
        view
        override(ERC2771ContextUpgradeable)
        returns (address)
    {
        return ERC2771ContextUpgradeable._msgSender();
    }

    /**
     * @notice Resolves message data in the context of potential meta-transactions
     * @dev Overrides both Context and ERC2771Context to handle inheritance conflicts
     * @dev Returns the actual transaction calldata when using meta-transactions via trusted forwarder
     * @return The actual transaction calldata, accounting for meta-transaction forwarding
     */
    function _msgData()
        internal
        view
        override(ERC2771ContextUpgradeable)
        returns (bytes calldata)
    {
        return ERC2771ContextUpgradeable._msgData();
    }

    /**
     * @notice Returns the context suffix length for ERC2771 meta-transaction support
     * @dev Overrides both Context and ERC2771Context to handle inheritance conflicts
     * @dev Used internally by ERC2771Context to properly decode meta-transaction data
     * @return The length of the context suffix appended to meta-transaction calldata
     */
    function _contextSuffixLength()
        internal
        view
        override(ERC2771ContextUpgradeable)
        returns (uint256)
    {
        return ERC2771ContextUpgradeable._contextSuffixLength();
    }
}
"
    },
    "node_modules/@openzeppelin/contracts-upgradeable/metatx/ERC2771ContextUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (metatx/ERC2771Context.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Context variant with ERC-2771 support.
 *
 * WARNING: Avoid using this pattern in contracts that rely in a specific calldata length as they'll
 * be affected by any forwarder whose `msg.data` is suffixed with the `from` address according to the ERC-2771
 * specification adding the address size in bytes (20) to the calldata size. An example of an unexpected
 * behavior could be an unintended fallback (or another function) invocation while trying to invoke the `receive`
 * function only accessible if `msg.data.length == 0`.
 *
 * WARNING: The usage of `delegatecall` in this contract is dangerous and may result in context corruption.
 * Any forwarded request to this contract triggering a `delegatecall` to itself will result in an invalid {_msgSender}
 * recovery.
 */
abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable _trustedForwarder;

    /**
     * @dev Initializes the contract with a trusted forwarder, which will be able to
     * invoke functions on this contract on behalf of other accounts.
     *
     * NOTE: The trusted forwarder can be replaced by overriding {trustedForwarder}.
     */
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor(address trustedForwarder_) {
        _trustedForwarder = trustedForwarder_;
    }

    /**
     * @dev Returns the address of the trusted forwarder.
     */
    function trustedForwarder() public view virtual returns (address) {
        return _trustedForwarder;
    }

    /**
     * @dev Indicates whether any particular address is the trusted forwarder.
     */
    function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
        return forwarder == trustedForwarder();
    }

    /**
     * @dev Override for `msg.sender`. Defaults to the original `msg.sender` whenever
     * a call is not performed by the trusted forwarder or the calldata length is less than
     * 20 bytes (an address length).
     */
    function _msgSender() internal view virtual override returns (address) {
        uint256 calldataLength = msg.data.length;
        uint256 contextSuffixLength = _contextSuffixLength();
        if (calldataLength >= contextSuffixLength && isTrustedForwarder(msg.sender)) {
            unchecked {
                return address(bytes20(msg.data[calldataLength - contextSuffixLength:]));
            }
        } else {
            return super._msgSender();
        }
    }

    /**
     * @dev Override for `msg.data`. Defaults to the original `msg.data` whenever
     * a call is not performed by the trusted forwarder or the calldata length is less than
     * 20 bytes (an address length).
     */
    function _msgData() internal view virtual override returns (bytes calldata) {
        uint256 calldataLength = msg.data.length;
        uint256 contextSuffixLength = _contextSuffixLength();
        if (calldataLength >= contextSuffixLength && isTrustedForwarder(msg.sender)) {
            unchecked {
                return msg.data[:calldataLength - contextSuffixLength];
            }
        } else {
            return super._msgData();
        }
    }

    /**
     * @dev ERC-2771 specifies the context as being a single address (20 bytes).
     */
    function _contextSuffixLength() internal view virtual override returns (uint256) {
        return 20;
    }
}
"
    },
    "node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}
"
    },
    "node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}
"
    },
    "node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
    },
    "node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
"
    },
    "contracts/interfaces/ISTBL_Register.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/access/IAccessControl.sol";
import "../lib/STBL_Structs.sol";

/** @title STBL Register Interface
 * @notice Interface for managing asset registrations and configurations in the STBL protocol
 * @dev Inherits from OpenZeppelin's IAccessControl for role-based access control
 */
interface iSTBL_Register is IAccessControl {
    /** @notice Emitted when the Core contract address is updated
     * @param _Core The new Core contract address
     */
    event CoreUpdateEvent(address _Core);

    /** @notice Emitted when the treasury address is updated
     * @param _treasury The new treasury address
     */
    event TreasuryUpdateEvent(address _treasury);

    /** @notice Emitted when a new asset is added to the registry
     * @param _id The ID of the added asset
     * @param _Assetdata The asset definition data
     */
    event AddAssetEvent(uint256 indexed _id, AssetDefinition _Assetdata);

    /** @notice Emitted when an asset is setup with contract addresses and configuration
     * @param _id The ID of the setup asset
     * @param _Assetdata The complete asset definition containing all configuration parameters including
     * contract addresses, fee structures, limits, and durations
     */
    event SetupAssetEvent(uint256 indexed _id, AssetDefinition _Assetdata);

    /** @notice Emitted when an asset's cut percentage is updated
     * @param _id The ID of the asset
     * @param _cut The new cut percentage value
     */
    event CutUpdateEvent(uint256 indexed _id, uint256 _cut);

    /** @notice Emitted when an asset's limit is updated
     * @param _id The ID of the asset
     * @param _limit The new limit value
     */
    event LimitUpdateEvent(uint256 indexed _id, uint256 _limit);

    /** @notice Emitted when an asset's fees are updated
     * @param _id The ID of the asset
     * @param _depositFee The new deposit fee value in basis points
     * @param _withdrawFee The new withdrawal fee value in basis points
     * @param _insuranceFee The new insurance fee value in basis points
     * @param _yieldFees The new yield fee value in basis points
     */
    event FeeUpdateEvent(
        uint256 indexed _id,
        uint256 _depositFee,
        uint256 _withdrawFee,
        uint256 _insuranceFee,
        uint256 _yieldFees
    );

    /** @notice Emitted when an asset's duration parameters are updated
     * @param _id The ID of the asset
     * @param _duration The new main duration value in seconds
     * @param _yieldDuration The new yield duration value in seconds
     */
    event durationUpdateEvent(
        uint256 indexed _id,
        uint256 _duration,
        uint256 _yieldDuration
    );

    /** @notice Emitted when an additional buffer for an asset is updated
     * @param _id The ID of the asset
     * @param _data Additional buffer data stored as bytes
     */
    event AdditionalBufferUpdateEvent(uint256 indexed _id, bytes _data);

    /** @notice Emitted when an asset's oracle address is updated
     * @param _id The ID of the asset
     * @param _oracle The new oracle address for price feeds
     */
    event OracleUpdateEvent(uint256 indexed _id, address _oracle);

    /** @notice Emitted when an asset's state is updated
     * @param _id The ID of the asset
     * @param _state The new state of the asset (enum AssetStatus)
     */
    event AssetStateUpdateEvent(uint256 indexed _id, AssetStatus _state);

    /** @notice Event emitted when asset deposits are incremented
     * @param assetId The ID of the asset
     * @param amount The amount incremented
     */
    event AssetDepositIncrementEvent(uint256 indexed assetId, uint256 amount);

    /** @notice Event emitted when asset deposits are decremented
     * @param assetId The ID of the asset
     * @param amount The amount decremented
     */
    event AssetDepositDecrementEvent(uint256 indexed assetId, uint256 amount);

    /** @notice Event emitted when a trusted forwarder is updated
     * @param previousForwarder The address of the previous trusted forwarder
     * @param newForwarder The address of the new trusted forwarder
     * @dev Indicates a change in the trusted forwarder for meta-transactions
     */
    event TrustedForwarderUpdated(
        address indexed previousForwarder,
        address indexed newForwarder
    );

    /**
     * @notice Emitted when the contract implementation is upgraded
     * @dev Triggered during an upgrade of the contract to a new implementation
     * @param newImplementation Address of the new implementation contract
     */
    event ContractUpgraded(address newImplementation);

    /** @notice Sets the Core contract address
     * @dev Only callable by admin role
     * @param _Core The new Core contract address
     */
    function setCore(address _Core) external;

    /** @notice Sets the treasury address
     * @dev Only callable by admin role
     * @param _treasury The new treasury address
     */
    function setTreasury(address _treasury) external;

    /** @notice Adds a new asset to the registry
     * @dev Only callable by admin role
     * @param _name The name of the asset
     * @param _desc Description of the asset
     * @param _type Asset type identifier
     * @param _aggType Aggregation type flag
     * @return The asset ID of the newly added asset
     */
    function addAsset(
        string memory _name,
        string memory _desc,
        uint8 _type,
        bool _aggType
    ) external returns (uint256);

    /** @notice Sets up an asset with contract addresses and configuration parameters
     * @dev Only callable by admin role and allows setting all key parameters for an asset
     * @param _id The unique identifier of the asset to configure
     * @param _contractAddr The primary token contract address for the asset
     * @param _issuanceAddr Address responsible for issuing the asset tokens
     * @param _distAddr Address of the reward distribution contract
     * @param _vaultAddr Address of the asset's vault contract
     * @param _oracle Address of the price oracle for the asset
     * @param _cut Percentage cut applied to the asset's transactions
     * @param _limit Maximum value/cap for the asset
     * @param _depositFee Fee charged for depositing the asset (in basis points)
     * @param _withdrawFee Fee charged for withdrawing the asset (in basis points)
     * @param _yieldFee Fee applied to yield generation (in basis points)
     * @param _insuranceFee Insurance fee applied (in basis points)
     * @param _duration Main duration parameter for protocol operations (in seconds)
     * @param _yieldDuration Duration specifically for yield calculations (in seconds)
     * @param _additionalBytes Additional configuration data stored as bytes
     * @custom:error Pi_SetupAlreadyDone if the asset has already been set up
     * @custom:error Pi_InvalidAssetSetup if the asset ID is invalid
     * @custom:error Pi_InvalidFeePercentage if any fee exceeds 100% (10000 basis points)
     * @custom:event SetupAssetEvent emitted when the asset is successfully set up
     */
    function setupAsset(
        uint256 _id,
        address _contractAddr,
        address _issuanceAddr,
        address _distAddr,
        address _vaultAddr,
        address _oracle,
        uint256 _cut,
        uint256 _limit,
        uint256 _depositFee,
        uint256 _withdrawFee,
        uint256 _yieldFee,
        uint256 _insuranceFee,
        uint256 _duration,
        uint256 _yieldDuration,
        bytes memory _additionalBytes
    ) external;

    /** @notice Sets the cut percentage for an asset
     * @dev Only callable by admin role
     * @param _id The ID of the asset
     * @param _cut The new cut percentage
     */
    function setCut(uint256 _id, uint256 _cut) external;

    /** @notice Sets the limit for an asset
     * @dev Only callable by admin role
     * @param _id The ID of the asset
     * @param _limit The new limit value
     */
    function setLimit(uint256 _id, uint256 _limit) external;

    /** @notice Sets the fee structure for an asset
     * @dev Only callable by admin role, all fees are in basis points (10000 = 100%)
     * @param _id The ID of the asset
     * @param _depositFee The new deposit fee percentage in basis points
     * @param _withdrawFee The new withdrawal fee percentage in basis points
     * @param _yieldFee The new yield fee percentage in basis points
     * @param _insuranceFee The new insurance fee percentage in basis points
     * @custom:error Pi_InvalidFeePercentage if any fee exceeds 100% (10000 basis points)
     */
    function setFees(
        uint256 _id,
        uint256 _depositFee,
        uint256 _withdrawFee,
        uint256 _yieldFee,
        uint256 _insuranceFee
    ) external;

    /** @notice Sets the duration parameters for a specific asset
     * @dev Only callable by admin role
     * @param _id The ID of the asset to update durations for
     * @param _duration The main duration parameter for the asset's operations, measured in seconds
     * @param _yieldduration The duration parameter specifically for yield calculations, measured in seconds
     */
    function setDurations(
        uint256 _id,
        uint256 _duration,
        uint256 _yieldduration
    ) external;

    /** @notice Sets additional buffer data for an asset
     * @dev Only callable by admin role
     * @param _id The ID of the asset
     * @param _data Additional buffer data to store as bytes
     */
    function setAdditionalBuffer(uint256 _id, bytes memory _data) external;

    /** @notice Sets the oracle address for an asset
     * @dev Only callable by admin role
     * @param _id The ID of the asset
     * @param _oracle The new oracle address
     */
    function setOracle(uint256 _id, address _oracle) external;

    /** @notice Disables an asset in the registry
     * @dev Only callable by admin role
     * @param _id Asset ID to disable
     */
    function disableAsset(uint256 _id) external;

    /** @notice Enables a previously disabled asset
     * @dev Only callable by admin role
     * @param _id Asset ID to enable
     */
    function enableAsset(uint256 _id) external;

    /** @notice Increments the total deposits for a specific asset
     * @dev Only callable by admin or authorized contracts
     * @param _id The ID of the asset to increment deposits for
     * @param _amount The amount to increment deposits by
     */
    function incrementAssetDeposits(uint256 _id, uint256 _amount) external;

    /** @notice Decrements the total deposits for a specific asset
     * @dev Only callable by Core contract
     * @param _id The ID of the asset to decrement deposits for
     * @param _amount The amount to decrement deposits by
     */
    function decrementAssetDeposits(uint256 _id, uint256 _amount) external;

    /** @notice Updates the trusted forwarder address for meta-transactions
     * @dev Only callable by admin role, updates the address used for ERC2771 meta-transactions
     * @param _newForwarder The new trusted forwarder address to be used
     * @custom:event Emits TrustedForwarderUpdated with previous and new forwarder addresses
     */
    function updateTrustedForwarder(address _newForwarder) external;

    /** @notice Retrieves the complete data for a specific asset
     * @param _id Asset ID to query
     * @return The AssetDefinition struct containing all asset data
     */
    function fetchAssetData(
        uint256 _id
    ) external view returns (AssetDefinition memory);

    /** @notice Retrieves specific element of asset data based on flag
     * @dev Flag values: 0=name, 1=description, 2=contractType, 3=isAggregated, 4=isDisabled,
     *                   5=isSetup, 6=cut, 7=limit, 8=token, 9=issuer, 10=rewardDistributor, 11=vault
     * @param _id The ID of the asset to fetch 

Tags:
ERC20, ERC165, Multisig, Staking, Yield, Voting, Upgradeable, Multi-Signature, Factory, Oracle|addr:0xb88366db3b35dcdba5c6ae60740992fdaab8ca00|verified:true|block:23483286|tx:0x7239ffb5c98440d96f11bf2655423d825ac0fd3d0b5fcf271fe28fadc7e8152b|first_check:1759332426

Submitted on: 2025-10-01 17:27:07

Comments

Log in to comment.

No comments yet.