Verified contractPartialMIT
STBL_PT1_Issuer
Address0x3aa40c6cd5b113e4ace117e2c7aa7077210de030
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.28
- Same code
1 more contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,334,095
- Creation transaction
- 0x56be3b813f…eb4f8b6978
30 files
- contracts/issuers/STBL_PT1_Issuer.solmain23.16 KB
- contracts/interfaces/ISTBL_Asset_Oracle.sol804 B
- contracts/interfaces/ISTBL_T1_Issuer.sol8.53 KB
- contracts/interfaces/ISTBL_T1_Vault.sol8.33 KB
- contracts/interfaces/ISTBL_T1_YieldDistributor.sol5.23 KB
- contracts/lib/STBL_Asset_Errors.sol3.4 KB
- contracts/lib/STBL_OracleLib.sol1.76 KB
- node_modules/@openzeppelin/contracts-upgradeable/metatx/ERC2771ContextUpgradeable.sol3.7 KB
- node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol9.28 KB
- node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol6.57 KB
- node_modules/@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.19 KB
- node_modules/@openzeppelin/contracts/access/IAccessControl.sol3.34 KB
- node_modules/@openzeppelin/contracts/interfaces/IERC1967.sol637 B
- node_modules/@openzeppelin/contracts/interfaces/draft-IERC1822.sol882 B
- node_modules/@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- node_modules/@openzeppelin/contracts/proxy/beacon/IBeacon.sol473 B
- node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol4.93 KB
- node_modules/@openzeppelin/contracts/utils/Address.sol6 KB
- node_modules/@openzeppelin/contracts/utils/Errors.sol896 B
- node_modules/@openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/interfaces/ISTBL_Core.sol3.47 KB
- node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/interfaces/ISTBL_Register.sol14.3 KB
- node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/interfaces/ISTBL_YLD.sol5.22 KB
- node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_AssetDefinitionLib.sol4.94 KB
- node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_DecimalConverter.sol5.18 KB
- node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_Errors.sol3.7 KB
- node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_MetadataLib.sol1.58 KB
- node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_Structs.sol7.89 KB
contracts/issuers/STBL_PT1_Issuer.sol
// 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 "@stbl-protocol/stbl-contracts-evm-core/contracts/interfaces/ISTBL_Register.sol";
import "@stbl-protocol/stbl-contracts-evm-core/contracts/interfaces/ISTBL_Core.sol";
import "@stbl-protocol/stbl-contracts-evm-core/contracts/interfaces/ISTBL_YLD.sol";
import "../interfaces/ISTBL_T1_Issuer.sol";
import "../interfaces/ISTBL_T1_Vault.sol";
import "../interfaces/ISTBL_T1_YieldDistributor.sol";
import "../interfaces/ISTBL_Asset_Oracle.sol";
import "@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_Structs.sol";
import "@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_AssetDefinitionLib.sol";
import "@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_MetadataLib.sol";
import "@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_Errors.sol";
import "@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_DecimalConverter.sol";
import "../lib/STBL_OracleLib.sol";
import "../lib/STBL_Asset_Errors.sol";
/**
* @title STBL Protocol Type 1 Issuer
* @notice Protocol Type 1 asset issuer contract that manages deposits and withdrawals
* @dev This contract serves as the primary interface for users to deposit assets and receive yield-bearing NFTs
* @author STBL Protocol
* @custom:security-contact [email protected]
*/
contract STBL_PT1_Issuer is
Initializable,
iSTBL_T1_Issuer,
ERC2771ContextUpgradeable,
UUPSUpgradeable
{
using STBL_AssetDefinitionLib for AssetDefinition;
using STBL_OracleLib for iSTBL_Asset_Oracle;
using STBL_MetadataLib for YLD_Metadata;
using DecimalConverter for uint256;
/** @notice Role identifier for contract upgrade authorization */
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
/** @notice Role identifier for Splitter role authorization */
bytes32 public constant SPLITTER_ROLE = keccak256("SPLITTER_ROLE");
/** @notice Current implementation version number for tracking upgrades */
uint256 private _version;
/** @notice Registry contract interface providing access to all system components and configuration */
iSTBL_Register private registry;
/** @notice Unique identifier for the specific asset type managed by this issuer instance */
uint256 private assetID;
/** @notice The type of asset managed by this issuer instance */
AssetType private assetType;
/**
* @dev Storage gap reserved for future state variables in upgradeable contracts
* @notice This gap ensures storage layout compatibility when adding new state variables in future versions
*/
uint256[63] private __gap;
/**
* @notice Ensures the asset is properly configured and active before allowing operations
* @dev Validates that the asset definition exists in the registry and is marked as active
* @custom:reverts STBL_Asset_NotInitialized if the asset is not properly initialized or has been deactivated
*/
modifier isSetupDone() {
AssetDefinition memory AssetData = registry.fetchAssetData(assetID);
if (!AssetData.isActive()) revert STBL_Asset_NotInitialized(assetID);
_;
}
/**
* @notice Contract constructor that initializes the ERC2771Context with a null trusted forwarder
* @dev The trusted forwarder will be configured during the initialize() call via the registry
* @custom:oz-upgrades-unsafe-allow constructor
*/
constructor() ERC2771ContextUpgradeable(address(0)) {}
/**
* @notice Initializes the issuer contract with asset configuration and access controls
* @dev Sets up UUPS upgradeability, access control roles, and links to the protocol registry
* @dev This function can only be called once during proxy deployment
* @param _id The unique asset identifier this issuer will manage
* @param _registry Address of the STBL protocol registry contract
* @custom:security Only the deployer receives initial admin and upgrader roles
*/
function initialize(uint256 _id, address _registry) public initializer {
__UUPSUpgradeable_init();
registry = iSTBL_Register(_registry);
assetID = _id;
assetType = AssetType.PT;
}
/**
* @notice Authorizes contract upgrades to new implementation addresses
* @dev Implements UUPS upgrade authorization pattern with role-based access control
* @dev Automatically increments version number on successful upgrades
* @param newImplementation Address of the new contract implementation to upgrade to
* @custom:security Requires UPGRADER_ROLE which is managed by the protocol registry
*/
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 Useful for tracking which version of the contract is currently deployed
* @return The version number, incremented with each upgrade
*/
function version() external view returns (uint256) {
return _version;
}
/**
* @notice Deposits real-world assets and mints a yield-bearing NFT to the caller
* @dev Wrapper function that calls iDeposit with the message sender as the recipient
* @param assetValue Amount of assets to deposit, specified in the asset's native decimal precision
* @return nftID The unique identifier of the minted NFT that represents ownership of the deposited assets
*/
function deposit(uint256 assetValue) external returns (uint256) {
return iDeposit(assetValue, _msgSender());
}
/**
* @notice Deposits real-world assets and mints a yield-bearing NFT to a specified sender
* @dev Wrapper function that calls iDeposit with a custom sender address
* @param assetValue Amount of assets to deposit, specified in the asset's native decimal precision
* @param _sender The address that will receive the ownership NFT
* @return nftID The unique identifier of the minted NFT that represents ownership of the deposited assets
*/
function deposit(
uint256 assetValue,
address _sender
) external returns (uint256) {}
/**
* @notice Withdraws deposited assets by burning the caller's yield-bearing NFT
* @dev Wrapper function that calls iWithdraw with the message sender as the owner
* @param _tokenID The unique identifier of the NFT to burn in exchange for withdrawing the underlying assets
*/
function withdraw(uint256 _tokenID) external {
iWithdraw(_tokenID, _msgSender());
}
/**
* @notice Withdraws deposited assets by burning a specified sender's yield-bearing NFT
* @dev Wrapper function that calls iWithdraw with a custom sender address
* @param _tokenID The unique identifier of the NFT to burn in exchange for withdrawing the underlying assets
* @param _sender The address of the account withdrawing assets
*/
function withdraw(uint256 _tokenID, address _sender) external {}
/**
* @notice Deposits real-world assets and mints a yield-bearing NFT representing ownership
* @dev Orchestrates the full deposit flow: validation, metadata generation, vault deposit, NFT minting, and staking setup
* @dev The deposited assets are transferred to the asset vault and an NFT is minted to represent ownership and yield rights
* @param _assetValue Amount of assets to deposit, specified in the asset's native decimal precision
* @param _sender The address of the account depositing assets and receiving the ownership NFT
* @return nftID The unique identifier of the minted NFT that represents ownership of the deposited assets
* @custom:requirements
* - Asset must be properly initialized and active in the registry
* - Deposit amount must be greater than zero
* - Caller must have sufficient asset token balance
* - Caller must have approved this contract to transfer the specified amount
* @custom:effects
* - Transfers asset tokens from caller to the protocol vault
* - Mints an NFT to the caller representing ownership and yield rights
* - Enables staking for the NFT in the yield distribution system
* - Records deposit metadata including fees, timestamps, and valuations
* @custom:emits depositAsset Event containing caller address, NFT ID, and complete metadata
*/
function iDeposit(
uint256 _assetValue,
address _sender
) internal isSetupDone returns (uint256) {
if (_assetValue == 0)
revert STBL_Asset_InvalidDepositAmount(assetID, _assetValue);
AssetDefinition memory AssetData = registry.fetchAssetData(assetID);
YLD_Metadata memory MetaData = generateMetaData(_assetValue);
iSTBL_T1_Vault(AssetData.vault).depositERC20(_sender, MetaData);
uint256 nftID = iSTBL_Core(registry.fetchCore()).put(_sender, MetaData);
iSTBL_T1_YieldDistributor(AssetData.rewardDistributor).enableStaking(
nftID,
MetaData.stableValueNet + MetaData.haircutAmount
);
emit depositAsset(_sender, nftID, MetaData);
return nftID;
}
/**
* @notice Withdraws assets by burning the corresponding NFT
* @dev Claims any pending rewards, withdraws assets from vault, disables staking, and burns NFT
* @param _tokenID ID of the NFT to burn and withdraw assets for
* @param _sender The address of the account withdrawing assets and receiving the ownership NFT
* @custom:requirements
* - Asset must be properly initialized and active
* - Caller must be the owner of the NFT
* - NFT must belong to this asset type
* - NFT must not be disabled
* - Minimum lock duration must have passed since deposit
* @custom:effects
* - Claims any pending yield rewards
* - Transfers assets from vault to caller
* - Disables staking for the NFT
* - Burns the NFT
* @custom:reverts STBL_Asset_InvalidAsset If NFT doesn't belong to this asset or caller is not owner
* @custom:reverts STBL_YLDDisabled If the NFT is disabled
* @custom:reverts STBL_Asset_WithdrawDurationNotReached If attempting to withdraw before lock duration expires
* @custom:emits withdrawAsset Emitted when assets are successfully withdrawn with sender address, NFT ID, and metadata
*/
function iWithdraw(uint256 _tokenID, address _sender) internal isSetupDone {
AssetDefinition memory AssetData = registry.fetchAssetData(assetID);
YLD_Metadata memory MetaData = iSTBL_YLD(registry.fetchYLDToken())
.getNFTData(_tokenID);
/** Check for Valid Asset ID */
if (MetaData.assetID != assetID)
revert STBL_Asset_InvalidAsset(MetaData.assetID);
/** Check for Owner of NFT */
if (iSTBL_YLD(registry.fetchYLDToken()).ownerOf(_tokenID) != _sender)
revert STBL_YLD_NotOwner(_tokenID);
/** Check if NFT is disabled */
if (MetaData.isDisabled) revert STBL_YLDDisabled(_tokenID);
/** Checks withdraw should happen post duration has passed */
if (
(MetaData.depositTimestamp + MetaData.Fees.yieldDuration) >
block.timestamp
) revert STBL_Asset_WithdrawDurationNotReached(assetID, _tokenID);
iSTBL_T1_YieldDistributor(AssetData.rewardDistributor).claim(_tokenID);
iSTBL_T1_Vault(AssetData.vault).withdrawERC20(_sender, MetaData);
iSTBL_T1_YieldDistributor(AssetData.rewardDistributor).disableStaking(
_tokenID,
MetaData.stableValueNet + MetaData.haircutAmount
);
iSTBL_Core(registry.fetchCore()).exit(
assetID,
_sender,
_tokenID,
MetaData.stableValueNet
);
emit withdrawAsset(_sender, _tokenID, MetaData);
}
/** @notice Allows treasury to withdraw expired assets by burning the corresponding NFT
* @dev Only callable by treasury after the lock duration has passed. Claims rewards if the NFT is disabled.
* @dev Blank function in PT Assets.
* @param _tokenID ID of the NFT to burn and withdraw assets for
* @custom:error STBL_Asset_InvalidAsset Thrown when the NFT's asset ID doesn't match this contract's asset ID
*/
function withdrawExpired(uint256 _tokenID) external {
revert STBL_Asset_WithdrawAssetDisabled(assetID, _tokenID);
}
/**
* @notice Enables yield generation for a specific NFT
* @dev Activates staking for an NFT in the yield distribution system to start earning rewards
* @param _tokenID The unique identifier of the NFT to enable yield generation for
* @custom:security Requires SPLITTER_ROLE for access control
*/
function enableYield(uint256 _tokenID) external {
if (!registry.hasRole(SPLITTER_ROLE, _msgSender()))
revert STBL_UnauthorizedCaller();
AssetDefinition memory AssetData = registry.fetchAssetData(assetID);
YLD_Metadata memory MetaData = iSTBL_YLD(registry.fetchYLDToken())
.getNFTData(_tokenID);
iSTBL_T1_YieldDistributor(AssetData.rewardDistributor).enableStaking(
_tokenID,
MetaData.stableValueNet + MetaData.haircutAmount
);
}
/**
* @notice Disables yield generation for a specific NFT
* @dev Deactivates staking for an NFT in the yield distribution system to stop earning rewards
* @param _tokenID The unique identifier of the NFT to disable yield generation for
* @custom:security Requires SPLITTER_ROLE for access control
*/
function disableYield(uint256 _tokenID) external {
if (!registry.hasRole(SPLITTER_ROLE, _msgSender()))
revert STBL_UnauthorizedCaller();
AssetDefinition memory AssetData = registry.fetchAssetData(assetID);
YLD_Metadata memory MetaData = iSTBL_YLD(registry.fetchYLDToken())
.getNFTData(_tokenID);
iSTBL_T1_YieldDistributor(AssetData.rewardDistributor).disableStaking(
_tokenID,
MetaData.stableValueNet + MetaData.haircutAmount
);
}
/**
* @notice Generates comprehensive metadata for a new asset deposit including fee calculations and valuations
* @dev Creates a complete YLD_Metadata structure capturing all deposit parameters, fee snapshots, and USD valuations at deposit time
* @dev This metadata is permanently stored with the NFT and used throughout the asset's lifecycle for calculations and withdrawals
* @param assetValue The amount of assets being deposited, specified in the asset's native decimal precision
* @return MetaData A fully populated YLD_Metadata structure containing:
* - Asset identification and deposit timestamp
* - Normalized asset value in 18-decimal format
* - Snapshot of all fee parameters at deposit time
* - USD gross valuation from oracle pricing
* - Calculated fee amounts in both asset and USD terms
* - Net USD value after all fee deductions
* @custom:calculations
* - Normalizes asset value from native decimals to standardized 18-decimal format
* - Queries asset oracle for current USD pricing information
* - Calculates deposit fees, withdrawal fees, haircut amounts, and insurance fees
* - Computes final net stable value that determines yield generation basis
*/
function generateMetaData(
uint256 assetValue
) internal view returns (YLD_Metadata memory MetaData) {
AssetDefinition memory AssetData = registry.fetchAssetData(assetID);
MetaData.assetID = assetID;
MetaData.assetValue = assetValue.normalizeToDecimals18(
DecimalConverter.getTokenDecimals(AssetData.token)
);
MetaData.depositTimestamp = block.timestamp;
MetaData.isDisabled = false;
/** Snapshot of values */
MetaData.Fees.depositFee = AssetData.depositFees;
MetaData.Fees.withdrawFee = AssetData.withdrawFees;
MetaData.Fees.hairCut = AssetData.cut;
MetaData.Fees.insuranceFee = AssetData.insuranceFees;
MetaData.Fees.duration = AssetData.duration;
MetaData.Fees.yieldDuration = AssetData.yieldDuration;
/** Determine USD Gross Value */
MetaData.stableValueGross = iSTBL_Asset_Oracle(AssetData.oracle)
.fetchForwardPrice(MetaData.assetValue);
/** Fees Priced in Stable Value */
MetaData = MetaData.calculateDepositFees();
MetaData.haircutAmountAssetValue = iSTBL_Asset_Oracle(AssetData.oracle)
.fetchInversePrice(MetaData.haircutAmount);
/** Determine USD Net Value (USST Minted) */
MetaData.stableValueNet = (MetaData.stableValueGross -
(MetaData.depositfeeAmount +
MetaData.haircutAmount +
MetaData.insurancefeeAmount));
return MetaData;
}
/**
* @notice Calculates the required asset deposit amount to achieve a desired net stable value
* @dev Performs inverse calculation to determine gross deposit needed after accounting for all fees
* @dev This function reverses the fee calculation logic to derive the original asset amount
* @param _amt The desired net stable value amount after all fees are deducted
* @return The gross asset value required to deposit to achieve the target net stable value
* @custom:formula assetValue = (_amt * FEES_CONSTANT) / (FEES_CONSTANT - totalFees)
* @custom:fees Accounts for deposit fees, haircut, and insurance fees in the calculation
*/
function deriveAssetValue(uint256 _amt) external view returns (uint256) {
AssetDefinition memory AssetData = registry.fetchAssetData(assetID);
uint256 oraclePrice = iSTBL_Asset_Oracle(AssetData.oracle).fetchPrice();
uint256 priceDecimals = iSTBL_Asset_Oracle(AssetData.oracle)
.getPriceDecimals();
// Convert USD amount to token amount: tokenAmount = usdAmount / pricePerToken
// Account for fees as well
uint256 cuts = AssetData.cut +
AssetData.depositFees +
AssetData.insuranceFees;
uint256 adjustedAmt = ((_amt * FEES_CONSTANT) /
(FEES_CONSTANT - cuts)) + 1;
// Divide by oracle price to get token amount
return
iSTBL_Asset_Oracle(AssetData.oracle)
.fetchInversePrice(adjustedAmt)
.convertFrom18Decimals(
DecimalConverter.getTokenDecimals(AssetData.token)
);
}
/**
* @notice Retrieves the trusted forwarder address for ERC2771 meta-transaction support
* @dev Delegates to the registry to get the current trusted forwarder configuration
* @dev The trusted forwarder enables gasless transactions by allowing approved relayers to submit transactions on behalf of users
* @return The address of the currently configured trusted forwarder contract
*/
function trustedForwarder() public view virtual override returns (address) {
return registry.trustedForwarder();
}
/**
* @notice Fetches metadata for a potential deposit without executing the deposit
* @dev Generates and returns the complete metadata structure that would be created for a given deposit amount
* @dev Useful for preview calculations and fee estimations before committing to a deposit
* @param _assetValue The amount of assets to simulate depositing, specified in the asset's native decimal precision
* @return MetaData A fully populated YLD_Metadata structure containing calculated fees, valuations, and parameters
*/
function fetchMetadata(
uint256 _assetValue
) external view returns (YLD_Metadata memory MetaData) {
return generateMetaData(_assetValue);
}
/**
* @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 asset type managed by this issuer
* @dev Returns the AssetType enum value indicating whether this issuer manages LT (Long-Term) or PT (Perpetual-Term) assets
* @return AssetType The asset type enum value (LT or PT) for this issuer instance
*/
function fetchAssetType() external view returns (AssetType) {
return assetType;
}
/**
* @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();
}
}
contracts/interfaces/ISTBL_Asset_Oracle.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title STBL Asset Price Oracle Interface
* @notice Interface for retrieving asset price information in the STBL protocol
* @dev This interface defines the standard methods for price oracles used by the STBL system
*/
interface iSTBL_Asset_Oracle {
/** @notice Gets the number of decimals for the price
* @return The number of decimals used for price representation (8 decimals)
*/
function getPriceDecimals() external view returns (uint256);
/** @notice Retrieves the current price of the USDY asset
* @return price The current price of the USDY asset with 8 decimal precision
* @dev Returns the stored price value for the USDY asset
*/
function fetchPrice() external view returns (uint256);
}
contracts/interfaces/ISTBL_T1_Issuer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_Structs.sol";
/**
* @title STBL Asset Issuer Interface
* @notice Interface for handling the issuance and redemption of stable assets in the STBL Protocol
* @dev Acts as an intermediary between users and the protocol's core components for asset management
*/
interface iSTBL_T1_Issuer {
/**
* @notice Emitted when an asset is deposited into the protocol
* @dev Contains detailed information about the deposit transaction and minted NFT
* @param user Address of the user making the deposit
* @param _tokenID Unique identifier of the NFT minted to represent the deposited asset
* @param _MetaData Metadata structure containing comprehensive details about the deposited asset
*/
event depositAsset(
address indexed user,
uint256 _tokenID,
YLD_Metadata _MetaData
);
/**
* @notice Emitted when an asset is withdrawn from the protocol
* @dev Triggered when a user burns their NFT to withdraw the underlying asset
* @param user Address of the user withdrawing the asset
* @param _tokenID ID of the NFT being burned during the withdrawal process
* @param _MetaData Metadata structure containing details about the withdrawn asset
*/
event withdrawAsset(
address indexed user,
uint256 _tokenID,
YLD_Metadata _MetaData
);
/**
* @notice Emitted when an asset is withdrawn from the protocol treasury
* @dev Used for administrative or treasury-related asset withdrawals
* @param user Address of the user or admin withdrawing the asset from treasury
* @param _tokenID ID of the NFT burned during the treasury withdrawal operation
* @param _MetaData Metadata structure containing comprehensive details about the withdrawn asset
*/
event withdrawAssetTreasury(
address indexed user,
uint256 _tokenID,
YLD_Metadata _MetaData
);
/**
* @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 Enum representing different asset types */
enum AssetType {
LT,
PT
}
/**
* @notice Returns the current contract implementation version
* @dev Useful for tracking which version of the contract is currently deployed
* @return The version number, incremented with each upgrade
*/
function version() external view returns (uint256);
/**
* @notice Deposits real-world assets and mints a yield-bearing NFT to the caller
* @dev Wrapper function that calls iDeposit with the message sender as the recipient
* @param assetValue Amount of assets to deposit, specified in the asset's native decimal precision
* @return nftID The unique identifier of the minted NFT that represents ownership of the deposited assets
*/
function deposit(uint256 assetValue) external returns (uint256);
/**
* @notice Deposits real-world assets and mints a yield-bearing NFT to a specified sender
* @dev Wrapper function that calls iDeposit with a custom sender address
* @param assetValue Amount of assets to deposit, specified in the asset's native decimal precision
* @param _sender The address that will receive the ownership NFT
* @return nftID The unique identifier of the minted NFT that represents ownership of the deposited assets
*/
function deposit(
uint256 assetValue,
address _sender
) external returns (uint256);
/**
* @notice Withdraws deposited assets by burning the caller's yield-bearing NFT
* @dev Wrapper function that calls iWithdraw with the message sender as the owner
* @param _tokenID The unique identifier of the NFT to burn in exchange for withdrawing the underlying assets
*/
function withdraw(uint256 _tokenID) external;
/**
* @notice Withdraws deposited assets by burning a specified sender's yield-bearing NFT
* @dev Wrapper function that calls iWithdraw with a custom sender address
* @param _tokenID The unique identifier of the NFT to burn in exchange for withdrawing the underlying assets
* @param _sender The address of the account withdrawing assets
*/
function withdraw(uint256 _tokenID, address _sender) external;
/** @notice Allows treasury to withdraw expired assets by burning the corresponding NFT
* @dev Only callable by treasury after the lock duration has passed. Claims rewards if the NFT is disabled.
* @param _tokenID ID of the NFT to burn and withdraw assets for
* @custom:error STBL_Asset_InvalidAsset Thrown when the NFT's asset ID doesn't match this contract's asset ID
* @custom:error STBL_InvalidTreasury Thrown when the caller is not the treasury
* @custom:error STBL_Asset_WithdrawDurationNotReached Thrown when attempting to withdraw before the lock duration has passed
* @custom:event withdrawAssetTreasury Emitted when assets are successfully withdrawn to treasury with treasury address, NFT ID, and metadata
*/
function withdrawExpired(uint256 _tokenID) external;
/**
* @notice Enables yield generation for a specific NFT
* @dev Activates staking for an NFT in the yield distribution system to start earning rewards
* @param _tokenID The unique identifier of the NFT to enable yield generation for
* @custom:security Requires SPLITTER_ROLE for access control
*/
function enableYield(uint256 _tokenID) external;
/**
* @notice Disables yield generation for a specific NFT
* @dev Deactivates staking for an NFT in the yield distribution system to stop earning rewards
* @param _tokenID The unique identifier of the NFT to disable yield generation for
* @custom:security Requires SPLITTER_ROLE for access control
*/
function disableYield(uint256 _tokenID) external;
/**
* @notice Calculates the required asset deposit amount to achieve a desired net stable value
* @dev Performs inverse calculation to determine gross deposit needed after accounting for all fees
* @dev This function reverses the fee calculation logic to derive the original asset amount
* @param _amt The desired net stable value amount after all fees are deducted
* @return The gross asset value required to deposit to achieve the target net stable value
* @custom:formula assetValue = (_amt * FEES_CONSTANT) / (FEES_CONSTANT - totalFees)
* @custom:fees Accounts for deposit fees, haircut, and insurance fees in the calculation
*/
function deriveAssetValue(uint256 _amt) external view returns (uint256);
/**
* @notice Fetches metadata for a potential deposit without executing the deposit
* @dev Generates and returns the complete metadata structure that would be created for a given deposit amount
* @dev Useful for preview calculations and fee estimations before committing to a deposit
* @param _assetValue The amount of assets to simulate depositing, specified in the asset's native decimal precision
* @return MetaData A fully populated YLD_Metadata structure containing calculated fees, valuations, and parameters
*/
function fetchMetadata(
uint256 _assetValue
) external view returns (YLD_Metadata memory MetaData);
/**
* @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);
/**
* @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);
/**
* @notice Retrieves the asset type managed by this issuer
* @dev Returns the AssetType enum value indicating whether this issuer manages LT (Long-Term) or PT (Perpetual-Term) assets
* @return AssetType The asset type enum value (LT or PT) for this issuer instance
*/
function fetchAssetType() external view returns (AssetType);
}
contracts/interfaces/ISTBL_T1_Vault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_Structs.sol";
/**
* @title Asset Vault Interface
* @notice Manages the secure storage and handling of assets in the STBL Protocol
* @dev Implements access control for asset custody and yield distribution
*/
interface iSTBL_T1_Vault {
/**
* @notice Emitted when tokens are deposited into the vault
* @param _token Address of the ERC20 token being deposited
* @param _from Address sending the tokens into the vault
* @param _depositValue Total amount of tokens deposited
* @param _depositFee Fee charged on the deposit transaction
* @param _hairCut Percentage reduction applied to deposit value
* @param _insuranceFee Additional fee for insurance protection
* @param _depositFeesAssetValue Asset value of the deposit fee amount
* @param _insuranceFeeAssetValue Asset value of the insurance fee amount
*/
event depositEvent(
address _token,
address _from,
uint256 _depositValue,
uint256 _depositFee,
uint256 _insuranceFee,
uint256 _hairCut,
uint256 _depositFeesAssetValue,
uint256 _insuranceFeeAssetValue
);
/**
* @notice Emitted when tokens are withdrawn from the vault
* @param _token Address of the ERC20 token being withdrawn
* @param _to Address receiving the tokens from the vault
* @param _netValue Net amount of tokens withdrawn after fees and haircuts
* @param _withdrawFee Fee charged on the withdrawal transaction
* @param _withdrawFeeAssetValue Asset value of the withdrawal fee amount
* @param _hairCut Percentage reduction applied to withdrawal value
*/
event withdrawEvent(
address _token,
address _to,
uint256 _netValue,
uint256 _withdrawFee,
uint256 _withdrawFeeAssetValue,
uint256 _hairCut
);
/**
* @notice Emitted when yield is distributed to participants
* @param token Address of the ERC20 token for which yield is distributed
* @param distributor Address that initiated the yield distribution
* @param netYield Net amount of yield distributed to participants
* @param yieldFee Fee charged on the yield distribution
* @param yieldValue Total gross yield value before fees
*/
event YieldDistributed(
address indexed token,
address indexed distributor,
uint256 netYield,
uint256 yieldFee,
uint256 yieldValue
);
/**
* @notice Event emitted when deposit, withdrawal, yield, and insurance fees are withdrawn to treasury
* @param treasury Address where token fees are withdrawn
* @param depositFees Total amount of deposit fees withdrawn
* @param withdrawFees Total amount of withdrawal fees withdrawn
* @param yieldFees Total amount of yield fees withdrawn
* @param insuranceFees Total amount of insurance fees withdrawn
* @param Fees Total Fees priced in asset value
*/
event FeesWithdrawn(
address indexed treasury,
uint256 depositFees,
uint256 withdrawFees,
uint256 yieldFees,
uint256 insuranceFees,
uint256 Fees
);
/**
* @notice Emitted when emergency funds are withdrawn from the vault
* @param _amt Amount of funds withdrawn during the emergency procedure
*/
event EmergencyFundsWithdraw(uint256 _amt);
/**
* @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 Returns the current contract implementation version
* @dev Useful for tracking which version of the contract is currently deployed
* @return The version number, incremented with each upgrade
*/
function version() external view returns (uint256);
/**
* @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;
/**
* @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;
/**
* @notice Distributes accumulated yield from asset appreciation to protocol reward distributor
* @dev Calculates yield differential, deducts protocol fees, and transfers tokens to distributor
* @dev Only executes distribution when positive price differential exists
* @dev Restricted to protocol treasury address for security
* @custom:event YieldDistributed Emitted with yield distribution details including fees and amounts
*/
function distributeYield() external;
/**
* @notice External view function exposing price differential calculation for yield potential
* @dev Public interface to check available yield without executing distribution
* @dev Used by external contracts, interfaces, and monitoring systems
* @return Price differential value in USD (18 decimals) representing distributable yield
*/
function CalculatePriceDifferentiation() external view returns (uint256);
/**
* @notice Transfers all accumulated protocol fees to the designated treasury address
* @dev Consolidates deposit, withdrawal, yield, and insurance fees for batch transfer
* @dev Resets all fee counters to zero after successful transfer completion
* @dev Validates treasury address existence before executing transfer
* @custom:event FeesWithdrawn Emitted with detailed breakdown of all withdrawn fee categories
*/
function withdrawFees() external;
/**
* @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;
/**
* @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);
/**
* @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 fetchRegistry() external view returns (address);
/**
* @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 fetchVaultData() external view returns (VaultStruct memory);
}
contracts/interfaces/ISTBL_T1_YieldDistributor.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_Structs.sol";
/**
* @title STBL Asset Yield Distributor Interface
* @notice Interface for managing reward distribution for staked assets in the STBL Protocol
* @dev Defines the contract interface for reward calculation, distribution, and tracking for yield-bearing assets
* @author STBL Protocol Team
*/
interface iSTBL_T1_YieldDistributor {
/**
* @notice Emitted when rewards are distributed to all stakers
* @param amount The total amount of rewards distributed
*/
event RewardDistributed(uint256 amount);
/**
* @notice Emitted when staking is enabled for a specific token
* @param id The token ID for which staking is enabled
* @param amount The amount being staked
*/
event StakingEnabled(uint256 indexed id, uint256 amount);
/**
* @notice Emitted when staking is disabled for a specific token
* @param id The token ID for which staking is disabled
* @param amount The amount being unstaked
*/
event StakingDisabled(uint256 indexed id, uint256 amount);
/**
* @notice Emitted when rewards are claimed by a token holder
* @param tokenId The token ID for which rewards are claimed
* @param amount The amount of rewards claimed
*/
event RewardClaimed(uint256 indexed tokenId, uint256 amount);
/**
* @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 Returns the current contract implementation version
* @dev Useful for tracking which version of the contract is currently deployed
* @return The version number, incremented with each upgrade
*/
function version() external view returns (uint256);
/**
* @notice Distributes yield rewards to all stakers
* @param reward Amount of reward tokens to distribute
* @dev Updates the global reward index and transfers tokens from vault to this contract.
* Only callable by the authorized vault contract after yield duration has passed.
* @custom:error STBL_AssetAlreadyDisabled Thrown if the asset is disabled
* @custom:error STBL_Asset_YieldDurationNotReached Thrown if the yield duration hasn't been reached
* @custom:error STBL_Asset_InvalidVault Thrown if the caller is not the authorized vault
* @custom:event RewardDistributed Emitted when rewards are successfully distributed
*/
function distributeReward(uint256 reward) external;
/**
* @notice Returns the total rewards earned for a specific token ID
* @param id Token ID to query
* @return Total rewards earned (both claimed and pending)
* @dev Combines already earned rewards with pending rewards
*/
function calculateRewardsEarned(uint256 id) external view returns (uint256);
/**
* @notice Enables staking for a token ID
* @param id Token ID to enable staking for
* @param value Amount of tokens to stake
* @dev Updates rewards before changing balance, increases total supply.
* Only callable by the authorized issuer contract.
* @custom:event StakingEnabled Emitted when staking is enabled for a token ID
*/
function enableStaking(uint256 id, uint256 value) external;
/**
* @notice Disables staking for a token ID
* @param id Token ID to disable staking for
* @param value Amount of tokens to unstake
* @dev Updates rewards before changing balance, decreases total supply.
* Only callable by the authorized issuer contract.
* @custom:event StakingDisabled Emitted when staking is disabled for a token ID
*/
function disableStaking(uint256 id, uint256 value) external;
/**
* @notice Claims accumulated rewards for a specific token ID
* @param id Token ID to claim rewards for
* @return Amount of rewards claimed and transferred
* @dev Transfers all accumulated rewards to the token owner, resets earned balance.
* Validates that both the asset and the specific token are not disabled.
* @custom:error STBL_AssetAlreadyDisabled Thrown if the asset is disabled
* @custom:error STBL_YLDDisabled Thrown if the specific token is disabled
* @custom:event RewardClaimed Emitted when rewards are claimed for a token ID
*/
function claim(uint256 id) external returns (uint256);
/**
* @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);
/**
* @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);
}
contracts/lib/STBL_Asset_Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @notice Thrown when the asset setup is not complete or inactive
* @param id The ID of the asset that is not properly setup
*/
error STBL_Asset_SetupNotComplete(uint256 id);
/**
* @notice Thrown when an unauthorized issuer attempts an operation
* @dev Used in the isValidIssuer modifier to restrict access
* @param id The ID of the asset with the invalid issuer
*/
error STBL_Asset_InvalidIssuer(uint256 id);
/**
* @notice Thrown when the calling address is not the valid vault contract
* @param id The ID of the asset with the invalid vault address
*/
error STBL_Asset_InvalidVault(uint256 id);
/**
* @notice Thrown when attempting to interact with an invalid asset
* @param id The ID of the invalid asset
*/
error STBL_Asset_InvalidAsset(uint256 id);
/**
* @notice Thrown when the provided owner does not match the expected owner
* @param _tokenID The token ID for which withdrawal was attempted too early
* @param owner The owner ID that was provided but is incorrect
*/
error STBL_Asset_IncorrectOwner(uint256 _tokenID, address owner);
/**
* @notice Thrown when attempting to call a function before contract initialization
* @param id The ID of the uninitialized asset
*/
error STBL_Asset_NotInitialized(uint256 id);
/**
* @notice Thrown when attempting to initialize an already initialized asset
* @param id The ID of the asset that is already initialized
*/
error STBL_Asset_Initialized(uint256 id);
/**
* @notice Thrown when attempting to withdraw before the required duration has passed
* @param id The ID of the asset where early withdrawal was attempted
* @param _tokenID The token ID for which withdrawal was attempted too early
*/
error STBL_Asset_WithdrawDurationNotReached(uint256 id, uint256 _tokenID);
/**
* @notice Thrown when attempting to claim yield before the required duration has passed
* @param id The ID of the asset where early yield claim was attempted
* @param duration The required duration that must be satisfied before claiming yield
*/
error STBL_Asset_YieldDurationNotReached(uint256 id, uint256 duration);
/**
* @notice Thrown when the vault value is insufficient compared to the asset value
* @param _assetValue The current asset value that is being compared
* @param _usdValue The USD value that is insufficient for the operation
*/
error STBL_Asset_InsufficientVaultValue(uint256 _assetValue, uint256 _usdValue);
/**
* @notice Thrown when an invalid deposit amount is provided
* @param assetID The ID of the asset for which the invalid deposit was attempted
* @param amount The invalid deposit amount that was provided
*/
error STBL_Asset_InvalidDepositAmount(uint256 assetID, uint256 amount);
/**
* @notice Thrown when the oracle price is stale or outdated
* @param price The stale price value returned by the oracle
* @param time The timestamp when the stale price was last updated
*/
error STBL_Asset_OracleStalePrice(uint256 price, uint256 time);
/**
* @notice Thrown when the oracle is disabled or not available
*/
error STBL_Asset_OracleDisabled();
/**
* @notice Thrown when attempting to withdraw from a disabled asset
* @param assetId The ID of the asset that has withdrawals disabled
* @param tokenId The token ID for which withdrawal was attempted
*/
error STBL_Asset_WithdrawAssetDisabled(uint256 assetId, uint256 tokenId);
contracts/lib/STBL_OracleLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_Structs.sol";
import "../interfaces/ISTBL_Asset_Oracle.sol";
/**
* @title Oracle Library Functions
* @notice Library providing utility functions for asset oracle price calculations
* @dev Contains functions for forward and inverse price calculations using oracle data
*/
library STBL_OracleLib {
/**
* @notice Fetches and calculates forward price from oracle contract
* @dev Multiplies oracle price by amount and adjusts for price decimals
* @param oracle The oracle contract implementing iSTBL_AssetOracle interface
* @param amount The amount to calculate price for (in token units)
* @return forwardPrice Calculated forward price adjusted for oracle decimals
*/
function fetchForwardPrice(
iSTBL_Asset_Oracle oracle,
uint256 amount
) internal view returns (uint256 forwardPrice) {
forwardPrice = ((oracle.fetchPrice() * amount) /
(10 ** oracle.getPriceDecimals()));
}
/**
* @notice Fetches and calculates inverse price from oracle contract
* @dev Divides amount by oracle price and adjusts for price decimals
* @param oracle The oracle contract implementing iSTBL_AssetOracle interface
* @param amount The amount to calculate inverse price for (in token units)
* @return inversePrice Calculated inverse price adjusted for oracle decimals
*/
function fetchInversePrice(
iSTBL_Asset_Oracle oracle,
uint256 amount
) internal view returns (uint256 inversePrice) {
inversePrice =
(amount * (10 ** oracle.getPriceDecimals())) /
oracle.fetchPrice();
}
}
node_modules/@openzeppelin/contracts-upgradeable/metatx/ERC2771ContextUpgradeable.sol
// 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
// 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
// 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-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
node_modules/@openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
node_modules/@openzeppelin/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)
pragma solidity >=0.4.11;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
node_modules/@openzeppelin/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)
pragma solidity >=0.4.16;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* 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.
*/
function proxiableUUID() external view returns (bytes32);
}
node_modules/@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
node_modules/@openzeppelin/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)
pragma solidity >=0.4.16;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol
// 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/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
node_modules/@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
} else {
revert Errors.FailedCall();
}
}
}
node_modules/@openzeppelin/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
node_modules/@openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
node_modules/@openzeppelin/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);
}
node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/interfaces/ISTBL_Core.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../lib/STBL_Structs.sol";
/**
* @title STBL Core Interface
* @notice Interface for core functionality of the STBL Protocol
* @dev Defines the main entry and exit points for assets in the protocol
*/
interface iSTBL_Core {
/**
* @notice Emitted when an asset is deposited into the protocol
* @param _id The asset identifier
* @param _to Address receiving the minted token
* @param _metadata Metadata associated with the YLD token
* @param _tokenID ID of the minted token
*/
event putEvent(
uint256 indexed _id,
address indexed _to,
YLD_Metadata _metadata,
uint256 _tokenID
);
/**
* @notice Emitted when an asset is withdrawn from the protocol
* @param _id The asset identifier
* @param _to Address receiving the withdrawn assets
* @param _value The value of the withdrawn assets
* @param _tokenID ID of the burned token
*/
event exitEvent(
uint256 indexed _id,
address indexed _to,
uint256 _value,
uint256 _tokenID
);
/**
* @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 Method to update trusted forwarder
* @param _newForwarder Address of the new trusted forwarder
* @dev Only callable by admin
*/
function updateTrustedForwarder(address _newForwarder) external;
/**
* @notice Issues X and Y tokens for a given asset
* @dev Only callable by the asset issuer
* @param _to Address to receive the tokens
* @param _metadata Metadata associated with the YLD Token
* @return nftID The ID of the minted Y token (NFT)
*/
function put(
address _to,
YLD_Metadata memory _metadata
) external returns (uint256);
/**
* @notice Withdraws assets from the protocol
* @param _assetID The identifier of the asset being withdrawn
* @param _from Address that owns the token being burned
* @param _tokenID ID of the token to burn
* @param _value The amount of X tokens to burn during redemption
*/
function exit(
uint256 _assetID,
address _from,
uint256 _tokenID,
uint256 _value
) external;
/**
* @notice Retrieves the USP token address
* @return The address of the USP token contract
*/
function fetchUSPToken() external view returns (address);
/**
* @notice Retrieves the USI token address
* @return The address of the USI token contract
*/
function fetchUSIToken() external view returns (address);
/**
* @notice Retrieves the registry address
* @return The address of the registry contract
*/
function fetchRegistry() external view returns (address);
}
node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/interfaces/ISTBL_Register.sol
// 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 from
* @param _flag The flag indicating which element to fetch
* @return The requested element value encoded as bytes
*/
function fetchAssetElement(
uint256 _id,
uint8 _flag
) external view returns (bytes memory);
/** @notice Fetches the USST-Pegged token contract address used in the system
* @dev This represents the main stablecoin contract address
* @return The contract address of the USD-Pegged token
*/
function fetchUSSTToken() external view returns (address);
/** @notice Fetches the USD-Interest token contract address used in the system
* @dev This represents the interest-bearing stablecoin contract address
* @return The contract address of the USD-Interest token
*/
function fetchYLDToken() external view returns (address);
/** @notice Retrieves the Core contract address
* @return The address of the Core contract
*/
function fetchCore() external view returns (address);
/** @notice Retrieves the treasury address
* @return The address of the treasury contract
*/
function fetchTreasury() external view returns (address);
/** @notice Retrieves the current counter value
* @dev The counter tracks the total number of assets added to the registry
* @return The current counter value
*/
function fetchCounter() external view returns (uint256);
/** @notice Retrieves the total deposit amount for a specific asset
* @param _assetID The ID of the asset to query
* @return The total amount deposited for the specified asset
*/
function fetchDeposits(uint256 _assetID) external view returns (uint256);
/** @notice Checks if adding a deposit amount would exceed the asset's deposit limit
* @param _assetID The ID of the asset to check deposit limit for
* @param _amount The amount proposed to be deposited
* @return True if the deposit limit would be exceeded, false otherwise
*/
function isDepositLimitReached(
uint256 _assetID,
uint256 _amount
) external view returns (bool);
/** @notice Returns the address of the trusted forwarder for meta-transactions
* @dev Used by ERC2771Context to validate meta-transaction relayers
* @return The address of the current trusted forwarder
*/
function trustedForwarder() external view returns (address);
}
node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/interfaces/ISTBL_YLD.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/access/IAccessControl.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "../lib/STBL_Structs.sol";
/**
* @title iSTBL_YLD Interface
* @notice Interface for the STBL YLD contract that manages yield-generating NFT tokens with lifecycle controls
* @dev Extends IAccessControl and IERC721 to provide role-based permissions and standard NFT functionality
* @author STBL Protocol Team
*/
interface iSTBL_YLD is IAccessControl, IERC721 {
/**
* @notice Emitted when the trusted forwarder address is updated
* @param previousForwarder Address of the previous trusted forwarder
* @param newForwarder Address of the new trusted forwarder
* @dev Used for meta-transaction support and gasless transactions
*/
event TrustedForwarderUpdated(
address indexed previousForwarder,
address indexed newForwarder
);
/**
* @notice Emitted when an NFT is disabled
* @param _id Token ID of the disabled NFT
* @dev Disabled NFTs cannot be transferred or used until re-enabled
*/
event NFTDisabled(uint256 indexed _id);
/**
* @notice Emitted when a disabled NFT is re-enabled
* @param _id Token ID of the enabled NFT
* @dev Re-enabled NFTs restore full functionality including transfers
*/
event NFTEnabled(uint256 indexed _id);
/**
* @notice Emitted when a new NFT is minted
* @param _addr Recipient address of the minted NFT
* @param _id Token ID of the newly minted NFT
* @param _nftMetadata Complete metadata structure for the NFT
* @dev Contains all relevant data for the newly created yield-bearing token
*/
event MintEvent(
address indexed _addr,
uint256 indexed _id,
YLD_Metadata _nftMetadata
);
/**
* @notice Emitted when an NFT is permanently burned
* @param _from Address that previously owned the burned NFT
* @param _id Token ID of the burned NFT
* @dev Burning permanently removes the token from circulation
*/
event BurnEvent(address indexed _from, uint256 indexed _id);
/**
* @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 Updates the base URI for token metadata
* @dev Changes the base URI used for constructing token metadata URLs
* @dev Only callable by addresses with DEFAULT_ADMIN_ROLE
* @param _uri The new base URI to set for token metadata
*/
function setBaseURI(string memory _uri) external;
/**
* @notice Pauses all contract functionality
* @dev Only callable by PAUSER_ROLE. Prevents transfers, minting, and burning
* @custom:security Emergency function to halt all operations
*/
function pause() external;
/**
* @notice Resumes all contract functionality
* @dev Only callable by PAUSER_ROLE. Restores normal operations after pause
* @custom:security Should only be called after emergency conditions are resolved
*/
function unpause() external;
/**
* @notice Retrieves complete metadata for a specific NFT
* @param _tokenID Token ID to query metadata for
* @return YLD_Metadata struct containing all token data
* @dev Reverts with NonexistentToken if tokenID does not exist
* @custom:view-function Pure read operation with no state changes
*/
function getNFTData(
uint256 _tokenID
) external view returns (YLD_Metadata memory);
/**
* @notice Creates a new NFT with specified metadata
* @param _to Recipient address for the new NFT
* @param _metadata Complete metadata structure for the NFT
* @return Token ID of the newly minted NFT
* @dev Only callable by MINTER_ROLE. Increments total supply
* @custom:security Validates recipient address and metadata integrity
*/
function mint(
address _to,
YLD_Metadata memory _metadata
) external returns (uint256);
/**
* @notice Permanently destroys an existing NFT
* @param _from Current owner address of the NFT
* @param _id Token ID to burn
* @dev Only callable by BURNER_ROLE. Decrements total supply
* @custom:security Validates ownership and token existence before burning
*/
function burn(address _from, uint256 _id) external;
/**
* @notice Disables an NFT, preventing transfers and usage
* @param _id Token ID to disable
* @dev Only callable by ADMIN_ROLE. NFT remains owned but non-transferable
* @custom:security Used for compliance or security concerns
*/
function disableNFT(uint256 _id) external;
/**
* @notice Re-enables a previously disabled NFT
* @param _id Token ID to enable
* @dev Only callable by ADMIN_ROLE. Restores full NFT functionality
* @custom:security Allows restoration of NFT after issues are resolved
*/
function enableNFT(uint256 _id) external;
}
node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_AssetDefinitionLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "./STBL_Structs.sol";
/**
* @title STBL_AssetDefinitionLib
* @notice Library providing utility functions for AssetDefinition struct operations
* @dev This library contains pure functions for validating, checking status, and calculating fees for asset definitions
*/
library STBL_AssetDefinitionLib {
/**
* @notice Checks if an asset definition is valid by verifying all required fields are set
* @dev Validates that id is non-zero, name is not empty, and all addresses are non-zero
* @param asset The asset definition to validate
* @return True if the asset definition is valid, false otherwise
*/
function isValid(
AssetDefinition memory asset
) internal pure returns (bool) {
return
asset.id != 0 &&
bytes(asset.name).length > 0 &&
asset.token != address(0) &&
asset.issuer != address(0) &&
asset.rewardDistributor != address(0) &&
asset.vault != address(0);
}
/**
* @notice Checks if an asset is active and available for use
* @dev An asset is considered active if it's setup and not disabled
* @param asset The asset definition to check
* @return True if the asset is active, false otherwise
*/
function isActive(
AssetDefinition memory asset
) internal pure returns (bool) {
return asset.status == AssetStatus.ENABLED;
}
/**
* @notice Calculates yield fees for a given amount
* @dev Calculates yield fee for given amount based on asset configuration using basis points (10000 = 100%)
* @param asset The asset definition with yield fee configuration
* @param amount The amount to calculate yield fee for
* @return netAmount The amount after deducting yield fee
* @return yieldFee The calculated yield fee amount
*/
function calculateYieldFee(
AssetDefinition memory asset,
uint256 amount
) internal pure returns (uint256, uint256) {
uint256 yieldFee = (amount * asset.yieldFees) / FEES_CONSTANT; // Assuming fee is in basis points
return (amount - yieldFee, yieldFee);
}
/**
* @notice Checks if an address matches the token address of an asset
* @dev Compares the provided account address with the asset's token address
* @param asset The asset definition to check
* @param account The address to compare
* @return True if the address matches the token address, false otherwise
*/
function isToken(
AssetDefinition memory asset,
address account
) internal pure returns (bool) {
return account == asset.token;
}
/**
* @notice Checks if an address matches the vault address of an asset
* @dev Compares the provided account address with the asset's vault address
* @param asset The asset definition to check
* @param account The address to compare
* @return True if the address matches the vault address, false otherwise
*/
function isVault(
AssetDefinition memory asset,
address account
) internal pure returns (bool) {
return account == asset.vault;
}
/**
* @notice Checks if an address matches the issuer address of an asset
* @dev Compares the provided account address with the asset's issuer address
* @param asset The asset definition to check
* @param account The address to compare
* @return True if the address matches the issuer address, false otherwise
*/
function isIssuer(
AssetDefinition memory asset,
address account
) internal pure returns (bool) {
return account == asset.issuer;
}
/**
* @notice Checks if an address matches the reward distributor address of an asset
* @dev Compares the provided account address with the asset's reward distributor address
* @param asset The asset definition to check
* @param account The address to compare
* @return True if the address matches the reward distributor address, false otherwise
*/
function isDistributor(
AssetDefinition memory asset,
address account
) internal pure returns (bool) {
return account == asset.rewardDistributor;
}
/**
* @notice Creates a string representation of the asset's contract type
* @dev Maps numeric contract type to human-readable string representation
* @param asset The asset definition
* @return The contract type as a string ("ERC20", "ERC721", "Custom", or "Unknown")
*/
function getContractTypeString(
AssetDefinition memory asset
) internal pure returns (string memory) {
if (asset.contractType == 0) return "ERC20";
if (asset.contractType == 1) return "ERC721";
if (asset.contractType == 2) return "Custom";
return "Unknown";
}
}
node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_DecimalConverter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title DecimalConverter
* @dev Library for converting token amounts between different decimal representations
* @notice Provides utility functions for handling decimal conversions between ERC20 tokens
* @author Smart Contract Developer
*/
library DecimalConverter {
/**
* @dev Convert token amount from source decimal to target decimal
* @notice Converts token amounts between different decimal precisions without overflow protection
* @param amount The token amount to convert
* @param sourceDecimals Decimal places of the source token (e.g., 6 for USDC)
* @param targetDecimals Decimal places of the target token (e.g., 18 for ETH)
* @return convertedAmount Converted token amount in target decimal precision
*/
function convertDecimals(
uint256 amount,
uint8 sourceDecimals,
uint8 targetDecimals
) internal pure returns (uint256 convertedAmount) {
// If decimals are the same, return original amount
if (sourceDecimals == targetDecimals) {
return amount;
}
// Handle conversion based on decimal difference
if (sourceDecimals > targetDecimals) {
// Reduce precision
uint256 decimalDifference = sourceDecimals - targetDecimals;
return amount / (10 ** decimalDifference);
} else {
// Increase precision
uint256 decimalDifference = targetDecimals - sourceDecimals;
return amount * (10 ** decimalDifference);
}
}
/**
* @dev Safely convert token amount with overflow protection
* @notice Converts token amounts between different decimal precisions with overflow protection
* @param amount The token amount to convert
* @param sourceDecimals Decimal places of the source token (e.g., 6 for USDC)
* @param targetDecimals Decimal places of the target token (e.g., 18 for ETH)
* @return convertedAmount Converted token amount in target decimal precision
* @custom:reverts "Decimal conversion would cause overflow" if multiplication would overflow uint256
*/
function safeConvertDecimals(
uint256 amount,
uint8 sourceDecimals,
uint8 targetDecimals
) internal pure returns (uint256 convertedAmount) {
// If decimals are the same, return original amount
if (sourceDecimals == targetDecimals) {
return amount;
}
// Handle conversion based on decimal difference
if (sourceDecimals > targetDecimals) {
// Reduce precision
uint256 decimalDifference = sourceDecimals - targetDecimals;
return amount / (10 ** decimalDifference);
} else {
// Increase precision with overflow check
uint256 decimalDifference = targetDecimals - sourceDecimals;
// Check for potential overflow
if (amount > type(uint256).max / (10 ** decimalDifference)) {
revert("Decimal conversion would cause overflow");
}
return amount * (10 ** decimalDifference);
}
}
/**
* @dev Get normalized amount based on standard 18 decimals
* @notice Converts any token amount to 18 decimal precision for standardized calculations
* @param amount Token amount to normalize in its native decimal precision
* @param tokenDecimals Decimal places of the token (e.g., 6 for USDC, 8 for WBTC)
* @return normalizedAmount Normalized amount in 18 decimal precision
*/
function normalizeToDecimals18(
uint256 amount,
uint8 tokenDecimals
) internal pure returns (uint256 normalizedAmount) {
return convertDecimals(amount, tokenDecimals, 18);
}
/**
* @dev Convert 18 decimal amount to specific token decimals
* @notice Converts standardized 18 decimal amounts back to token's native decimal precision
* @param amount Amount in 18 decimal precision
* @param tokenDecimals Target token decimal places (e.g., 6 for USDC, 8 for WBTC)
* @return convertedAmount Converted amount in target token's native decimal precision
*/
function convertFrom18Decimals(
uint256 amount,
uint8 tokenDecimals
) internal pure returns (uint256 convertedAmount) {
return convertDecimals(amount, 18, tokenDecimals);
}
/**
* @dev Get token's native decimal precision
* @notice Retrieves the decimal precision of an ERC20 token via low-level call
* @param tokenAddress Address of the ERC20 token contract
* @return decimals Token's decimal places (defaults to 18 if call fails)
*/
function getTokenDecimals(
address tokenAddress
) internal view returns (uint8 decimals) {
// Create minimal interface for decimals
(bool success, bytes memory data) = tokenAddress.staticcall(
abi.encodeWithSignature("decimals()")
);
// Return 18 as default if call fails
if (!success || data.length == 0) {
return 18;
}
return abi.decode(data, (uint8));
}
}
node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @notice Thrown when an unauthorized caller attempts to access a restricted function
*/
error STBL_UnauthorizedCaller();
/**
* @notice Thrown when attempting to set up an asset with invalid parameters
*/
error STBL_InvalidAssetSetup();
/**
* @notice Thrown when attempting to set up an asset with invalid parameters
*/
error STBL_InvalidAssetName();
/**
* @notice Thrown when the setup has already been completed
*/
error STBL_SetupAlreadyDone();
/**
* @notice Thrown when an asset is not active
*/
error STBL_AssetNotActive();
/**
* @notice Thrown when an asset is active
*/
error STBL_AssetActive();
/**
* @notice Thrown when an invalid address is provided
*/
error STBL_InvalidAddress();
/**
* @notice Thrown when an invalid Yield Duration and duration are provided
*/
error STBL_InvalidDuration();
/**
* @notice Thrown when an invalid treasury address is provided
*/
error STBL_InvalidTreasury();
/**
* @notice Thrown when an unauthorized issuer attempts an operation
*/
error STBL_UnauthorizedIssuer();
/**
* @notice Thrown when an invalid cut percentage is provided
* @param cut The invalid cut percentage that was provided
*/
error STBL_InvalidCutPercentage(uint256 cut);
/**
* @notice Thrown when a maximum limit has been reached
*/
error STBL_MaxLimitReached();
/**
* @notice Thrown when YLD functionality is disabled
* @param id The ID of the YLD that is disabled
*/
error STBL_YLDDisabled(uint256 id);
/**
* @notice Thrown when an invalid flag value is provided
* @param flag The invalid flag value that was provided
*/
error STBL_InvalidFlagValue(uint8 flag);
/**
* @notice Thrown when attempting to disable an already disabled asset
* @param id The ID of the asset that is already disabled
*/
error STBL_AssetDisabled(uint256 id);
/**
* @notice Thrown when attempting to enable an already enabled asset
* @param id The ID of the asset that is already enabled
*/
error STBL_AssetEnabled(uint256 id);
/**
* @notice Thrown when an invalid fee percentage is provided
* @param fee The invalid fee percentage that was provided
*/
error STBL_InvalidFeePercentage(uint256 fee);
/**
* @notice Thrown when attempting to disable an already disabled insurance
* @param id The ID of the insurance that is already disabled
*/
error STBL_IssuanceAlreadyDisabled(uint256 id);
/**
* @notice Thrown when attempting to enable an already enabled insurance
* @param id The ID of the insurance that is already enabled
*/
error STBL_IssuanceAlreadyEnabled(uint256 id);
/**
* @notice Thrown when the caller is not the owner of the NFT
* @param tokenId The ID of the token for which ownership is required
*/
error STBL_YLD_NotOwner(uint256 tokenId);
/**
* @notice Thrown when attempting to enable an already enabled NFT
* @param tokenId The ID of the token that is already enabled
*/
error STBL_YLD_AlreadyEnabled(uint256 tokenId);
/**
* @notice Thrown when attempting to disable an already disabled NFT
* @param tokenId The ID of the token that is already disabled
*/
error STBL_YLD_AlreadyDisabled(uint256 tokenId);
/**
* @notice Thrown when attempting to transfer a token that has transfers disabled
* @param tokenId The ID of the token that cannot be transferred
*/
error STBL_YLD_TransferDisabled(uint256 tokenId);
/**
* @notice Thrown when the sender address is blacklisted
* @param sender The blacklisted sender address
*/
error STBL_USST_SenderBlacklisted(address sender);
/**
* @notice Thrown when the recipient address is blacklisted
* @param recipient The blacklisted recipient address
*/
error STBL_USST_RecipientBlacklisted(address recipient);
node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_MetadataLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "./STBL_Structs.sol";
/**
* @title STBL_MetadataLib
* @notice Library providing utility functions for YLD_Metadata struct
*/
library STBL_MetadataLib {
/**
* @notice Checks if a token metadata is valid
* @param data The token metadata to validate
* @return bool True if the token metadata is valid
*/
function isValid(YLD_Metadata memory data) internal pure returns (bool) {
return data.assetID != 0 && data.isDisabled == false;
}
/**
* @notice Calculates and updates all fee amounts based on the gross stable value
* @param data The YLD_Metadata struct containing fee rates and gross value
* @return YLD_Metadata The updated metadata struct with calculated fee amounts
*/
function calculateDepositFees(
YLD_Metadata memory data
) internal pure returns (YLD_Metadata memory) {
data.depositfeeAmount =
(data.stableValueGross * data.Fees.depositFee) /
FEES_CONSTANT; // Assuming fee is in basis points
data.haircutAmount =
(data.stableValueGross * data.Fees.hairCut) /
FEES_CONSTANT; // Assuming fee is in basis points
data.insurancefeeAmount =
(data.stableValueGross * data.Fees.insuranceFee) /
FEES_CONSTANT; // Assuming fee is in basis points
data.withdrawfeeAmount =
(data.stableValueGross * data.Fees.withdrawFee) /
FEES_CONSTANT; // Assuming fee is in basis points
return data;
}
}
node_modules/@stbl-protocol/stbl-contracts-evm-core/contracts/lib/STBL_Structs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title STBL Protocol Structs
* @notice Core data structures used throughout the STBL Protocol
* @dev This file contains all the essential data structures that define the protocol's architecture
*/
/**
* @title YLD_Metadata
* @notice Metadata structure for yield-bearing tokens
* @dev Stores essential information about yield tokens including values, fees, and operational state
*/
struct YLD_Metadata {
/** @notice Unique identifier for the asset */
uint256 assetID;
/** @notice URI pointing to token metadata following standard metadata format */
string uri;
/** @notice Value representing the amount of the asset deposited in native asset units */
uint256 assetValue;
/** @notice The total USD value of tokens deposited in the protocol before any adjustments */
uint256 stableValueGross;
/** @notice The net USD value of USP tokens minted by the protocol after applying haircuts and fees */
uint256 stableValueNet;
/** @notice Block Timestamp when the deposit was made for time-based calculations */
uint256 depositTimestamp;
/** @notice Absolute fee amount charged on asset deposits in wei */
uint256 depositfeeAmount;
/** @notice Absolute haircut amount taken in USD terms as protocol fee */
uint256 haircutAmount;
/** @notice Absolute haircut amount taken in asset terms as protocol fee */
uint256 haircutAmountAssetValue;
/** @notice Absolute fee amount charged on asset withdrawals in wei */
uint256 withdrawfeeAmount;
/** @notice Absolute fee amount allocated to insurance pool in wei */
uint256 insurancefeeAmount;
/** @notice Snapshot of fee structure at the time of deposit for consistency */
FeeStruct Fees;
/** @notice Additional data buffer for future extensibility and upgrades */
bytes additionalBuffer;
/** @notice Flag indicating if token is disabled and cannot be used */
bool isDisabled;
}
/**
* @title AssetStatus
* @notice Enumeration defining the operational status of assets within the protocol
* @dev Used to track asset lifecycle and control operational permissions
* @param INACTIVE Asset is not yet configured or deployed
* @param INITIALIZED Asset is configured but not yet active for operations
* @param ENABLED Asset is fully operational and available for deposits/withdrawals
* @param DISABLED Asset is temporarily disabled but can be reactivated
* @param EMERGENCY_STOP Asset is in emergency state with all operations halted
*/
enum AssetStatus {
INACTIVE,
INITIALIZED,
ENABLED,
DISABLED,
EMERGENCY_STOP
}
/**
* @title AssetDefinition
* @notice Structure defining comprehensive properties of an asset in the protocol
* @dev Contains all configuration parameters, addresses, and operational settings for an asset
*/
struct AssetDefinition {
/** @notice Unique identifier assigned to the asset within the protocol */
uint256 id;
/** @notice Human-readable name of the asset for display purposes */
string name;
/** @notice Detailed description of the asset and its characteristics */
string description;
/** @notice Type of contract (ERC20 = 0, ERC721 = 1, Custom = 2) */
uint8 contractType;
/** @notice Flag indicating if yields are aggregated for this asset across all deposits */
bool isAggreagated;
/** @notice Current operational status of the asset (INACTIVE, INITIALIZED, ENABLED, DISABLED) */
AssetStatus status;
/** @notice Haircut percentage taken by the protocol in basis points */
uint256 cut;
/** @notice Maximum allowable deposit amount for this asset in native units */
uint256 limit;
/** @notice Contract address of the underlying token */
address token;
/** @notice Address responsible for asset issuance and management */
address issuer;
/** @notice Address responsible for distributing rewards to token holders */
address rewardDistributor;
/** @notice Address of the oracle providing price feeds and market data */
address oracle;
/** @notice Address of the custodian vault holding the actual assets */
address vault;
/** @notice Fee percentage charged on deposits in basis points */
uint256 depositFees;
/** @notice Fee percentage charged on withdrawals in basis points */
uint256 withdrawFees;
/** @notice Fee percentage charged on yield generation in basis points */
uint256 yieldFees;
/** @notice Percentage of fees allocated to insurance pool in basis points */
uint256 insuranceFees;
/** @notice Time duration in seconds for which asset must remain locked post deposit */
uint256 duration;
/** @notice Time interval in seconds between yield distribution events */
uint256 yieldDuration;
/** @notice Additional data buffer for future extensibility and protocol upgrades */
bytes additionalBuffer;
}
/**
* @title stakingStruct
* @notice Data structure tracking token staking details for protocol participants
* @dev Used to manage individual staking positions, rewards, and distribution tracking
* @custom:security Balance must never underflow, implement proper checks before withdrawals
* @custom:security RewardIndex must be properly synchronized with global reward calculations
*/
struct stakingStruct {
/** @notice Current staked balance of the participant in wei */
uint256 balance;
/** @notice Index tracking participant's position in yield distribution calculations */
uint256 rewardIndex;
/** @notice Total rewards earned but not yet claimed by the participant */
uint256 earned;
/** @notice Flag indicating if staking position is currently active and earning rewards */
bool isActive;
}
/**
* @title VaultStruct
* @notice Structure tracking protocol vault metrics and cumulative financial data
* @dev Comprehensive record of all fees, deposits, and protocol revenue streams
* @custom:security All fee calculations must prevent overflow and maintain precision
*/
struct VaultStruct {
/** @notice Total accumulated fees from asset deposits across all assets */
uint256 depositFees;
/** @notice Total accumulated fees from asset withdrawals across all assets */
uint256 withdrawFees;
/** @notice Total accumulated fees from insurance contributions */
uint256 insuranceFees;
/** @notice Total accumulated fees from yield generation activities */
uint256 yieldFees;
/** @notice Cumulative total of all haircut fees collected by protocol in USD */
uint256 cumilativeHairCutValue;
/** @notice Current USD value of all deposits held in the vault */
uint256 depositValueUSD;
/** @notice Total gross value of asset deposits before any deductions */
uint256 assetDepositGross;
/** @notice Net value of asset deposits after haircuts and fees are applied */
uint256 assetDepositNet;
}
/**
* @title FeeStruct
* @notice Structure defining fee configuration for various protocol operations
* @dev Contains granular fee settings and timing parameters for protocol actions
* @custom:security All fee percentages should be validated to prevent excessive fees
*/
struct FeeStruct {
/** @notice Fee percentage charged on asset deposits in basis points */
uint256 depositFee;
/** @notice Percentage of deposit value taken as protocol haircut in basis points */
uint256 hairCut;
/** @notice Fee percentage charged on asset withdrawals in basis points */
uint256 withdrawFee;
/** @notice Percentage of total fees allocated to insurance pool in basis points */
uint256 insuranceFee;
/** @notice Lock duration in seconds for deposited assets */
uint256 duration;
/** @notice Time interval in seconds between yield distribution events */
uint256 yieldDuration;
}
uint256 constant FEES_CONSTANT = 10 ** 9;
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris",
"remappings": [
"@openzeppelin/=node_modules/@openzeppelin/",
"forge-std/=lib/forge-std/src/",
"@stbl-protocol/=node_modules/@stbl-protocol/",
"eth-gas-reporter/=node_modules/eth-gas-reporter/",
"hardhat/=node_modules/hardhat/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.