Verified contractPartialLicenseRef-PolyForm-Perimeter-1.0.1
RoycoSeniorTranche
Address0x029b8117fd9be010e32b19d7d9e35dca9e44ae6e
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.35
- Same code
Only this contract
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- Language
- solidity
- Optimization
- Yes, 2,000 runs
- EVM version
- prague
- Via IR
- yes
- License
- LicenseRef-PolyForm-Perimeter-1.0.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,759,228
- Creation transaction
- 0x9938803954…38eb542141
45 files
- src/tranches/RoycoSeniorTranche.solmain1.8 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/manager/AccessManagedUpgradeable.sol5.97 KB
- lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol12.15 KB
- lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC20BurnableUpgradeable.sol1.51 KB
- lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC20PermitUpgradeable.sol3.16 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.22 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/NoncesUpgradeable.sol2.35 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol3.68 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/cryptography/EIP712Upgradeable.sol6.85 KB
- lib/openzeppelin-contracts/contracts/access/manager/AuthorityUtils.sol1.38 KB
- lib/openzeppelin-contracts/contracts/access/manager/IAccessManaged.sol1.11 KB
- lib/openzeppelin-contracts/contracts/access/manager/IAccessManager.sol16.58 KB
- lib/openzeppelin-contracts/contracts/access/manager/IAuthority.sol483 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol740 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol9.28 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol3.81 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13.31 KB
- lib/openzeppelin-contracts/contracts/utils/Bytes.sol14.74 KB
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol21.54 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol12.15 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol8.63 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.66 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol2.61 KB
- src/auth/RoycoAuth.sol1.44 KB
- src/base/RoycoBase.sol701 B
- src/interfaces/IRoycoAuth.sol344 B
- src/interfaces/IRoycoDayKernel.sol40.62 KB
- src/interfaces/IRoycoSeniorTranche.sol2.52 KB
- src/interfaces/IRoycoVaultTranche.sol11.79 KB
- src/libraries/Constants.sol2.09 KB
- src/libraries/Types.sol8.63 KB
- src/libraries/Units.sol12.49 KB
- src/libraries/logic/AssetLedgerLogic.sol9.74 KB
- src/libraries/logic/DispatchLogic.sol6.57 KB
- src/libraries/logic/ValuationLogic.sol11.48 KB
- src/tranches/base/RoycoVaultTranche.sol16.47 KB
src/tranches/RoycoSeniorTranche.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { IRoycoSeniorTranche } from "../interfaces/IRoycoSeniorTranche.sol";
import { IRoycoVaultTranche } from "../interfaces/IRoycoVaultTranche.sol";
import { TrancheType } from "../libraries/Types.sol";
import { RoycoVaultTranche } from "./base/RoycoVaultTranche.sol";
/**
* @title RoycoSeniorTranche
* @author Ankur Dubey, Shivaansh Kapoor, Tomer Ganor
* @notice Senior tranche implementation for Royco markets
*/
contract RoycoSeniorTranche is RoycoVaultTranche, IRoycoSeniorTranche {
/// @notice Initializes the Royco senior tranche
/// @param _stParams Deployment parameters including name, symbol, initial authority, kernel, and asset for the senior tranche
function initialize(RoycoTrancheInitParams calldata _stParams) external initializer {
// Initialize the Royco Senior Tranche
__RoycoTranche_init(_stParams);
}
/// @inheritdoc RoycoVaultTranche
function TRANCHE_TYPE() public pure virtual override(RoycoVaultTranche, IRoycoVaultTranche) returns (TrancheType) {
return TrancheType.SENIOR;
}
/// @inheritdoc IRoycoSeniorTranche
function mintLiquidityPremiumShares(uint256 _liquidityPremiumShares)
external
virtual
override(IRoycoSeniorTranche)
onlyKernel
returns (uint256 totalTrancheShares)
{
address kernel = kernel();
// Mint the precomputed liquidity premium shares to the kernel, which custodies them for the liquidity provider tranche
if (_liquidityPremiumShares != 0) _mint(kernel, _liquidityPremiumShares);
totalTrancheShares = totalSupply();
emit LiquidityPremiumSharesMinted(kernel, _liquidityPremiumShares, totalTrancheShares);
}
}
lib/openzeppelin-contracts-upgradeable/contracts/access/manager/AccessManagedUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/AccessManaged.sol)
pragma solidity ^0.8.20;
import {AuthorityUtils} from "@openzeppelin/contracts/access/manager/AuthorityUtils.sol";
import {IAccessManager} from "@openzeppelin/contracts/access/manager/IAccessManager.sol";
import {IAccessManaged} from "@openzeppelin/contracts/access/manager/IAccessManaged.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev This contract module makes available a {restricted} modifier. Functions decorated with this modifier will be
* permissioned according to an "authority": a contract like {AccessManager} that follows the {IAuthority} interface,
* implementing a policy that allows certain callers to access certain functions.
*
* IMPORTANT: The `restricted` modifier should never be used on `internal` functions, judiciously used in `public`
* functions, and ideally only used in `external` functions. See {restricted}.
*/
abstract contract AccessManagedUpgradeable is Initializable, ContextUpgradeable, IAccessManaged {
/// @custom:storage-location erc7201:openzeppelin.storage.AccessManaged
struct AccessManagedStorage {
address _authority;
bool _consumingSchedule;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessManaged")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessManagedStorageLocation = 0xf3177357ab46d8af007ab3fdb9af81da189e1068fefdc0073dca88a2cab40a00;
function _getAccessManagedStorage() private pure returns (AccessManagedStorage storage $) {
assembly {
$.slot := AccessManagedStorageLocation
}
}
/**
* @dev Initializes the contract connected to an initial authority.
*/
function __AccessManaged_init(address initialAuthority) internal onlyInitializing {
__AccessManaged_init_unchained(initialAuthority);
}
function __AccessManaged_init_unchained(address initialAuthority) internal onlyInitializing {
_setAuthority(initialAuthority);
}
/**
* @dev Restricts access to a function as defined by the connected Authority for this contract and the
* caller and selector of the function that entered the contract.
*
* [IMPORTANT]
* ====
* In general, this modifier should only be used on `external` functions. It is okay to use it on `public`
* functions that are used as external entry points and are not called internally. Unless you know what you're
* doing, it should never be used on `internal` functions. Failure to follow these rules can have critical security
* implications! This is because the permissions are determined by the function that entered the contract, i.e. the
* function at the bottom of the call stack, and not the function where the modifier is visible in the source code.
* ====
*
* [WARNING]
* ====
* Avoid adding this modifier to the https://docs.soliditylang.org/en/v0.8.20/contracts.html#receive-ether-function[`receive()`]
* function or the https://docs.soliditylang.org/en/v0.8.20/contracts.html#fallback-function[`fallback()`]. These
* functions are the only execution paths where a function selector cannot be unambiguously determined from the calldata
* since the selector defaults to `0x00000000` in the `receive()` function and similarly in the `fallback()` function
* if no calldata is provided. (See {_checkCanCall}).
*
* The `receive()` function will always panic whereas the `fallback()` may panic depending on the calldata length.
* ====
*/
modifier restricted() {
_checkCanCall(_msgSender(), _msgData());
_;
}
/// @inheritdoc IAccessManaged
function authority() public view virtual returns (address) {
AccessManagedStorage storage $ = _getAccessManagedStorage();
return $._authority;
}
/// @inheritdoc IAccessManaged
function setAuthority(address newAuthority) public virtual {
address caller = _msgSender();
if (caller != authority()) {
revert AccessManagedUnauthorized(caller);
}
if (newAuthority.code.length == 0) {
revert AccessManagedInvalidAuthority(newAuthority);
}
_setAuthority(newAuthority);
}
/// @inheritdoc IAccessManaged
function isConsumingScheduledOp() public view returns (bytes4) {
AccessManagedStorage storage $ = _getAccessManagedStorage();
return $._consumingSchedule ? this.isConsumingScheduledOp.selector : bytes4(0);
}
/**
* @dev Transfers control to a new authority. Internal function with no access restriction. Allows bypassing the
* permissions set by the current authority.
*/
function _setAuthority(address newAuthority) internal virtual {
AccessManagedStorage storage $ = _getAccessManagedStorage();
$._authority = newAuthority;
emit AuthorityUpdated(newAuthority);
}
/**
* @dev Reverts if the caller is not allowed to call the function identified by a selector. Panics if the calldata
* is less than 4 bytes long.
*/
function _checkCanCall(address caller, bytes calldata data) internal virtual {
AccessManagedStorage storage $ = _getAccessManagedStorage();
(bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
authority(),
caller,
address(this),
bytes4(data[0:4])
);
if (!immediate) {
if (delay > 0) {
$._consumingSchedule = true;
IAccessManager(authority()).consumeScheduledOp(caller, data);
$._consumingSchedule = false;
} else {
revert AccessManagedUnauthorized(caller);
}
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
struct ERC20Storage {
mapping(address account => uint256) _balances;
mapping(address account => mapping(address spender => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
assembly {
$.slot := ERC20StorageLocation
}
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC20Storage storage $ = _getERC20Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
$._totalSupply += value;
} else {
uint256 fromBalance = $._balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
$._balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
$._totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
$._balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
$._allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC20BurnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.20;
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {ContextUpgradeable} from "../../../utils/ContextUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal onlyInitializing {
}
function __ERC20Burnable_init_unchained() internal onlyInitializing {
}
/**
* @dev Destroys a `value` amount of tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 value) public virtual {
_burn(_msgSender(), value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, deducting from
* the caller's allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `value`.
*/
function burnFrom(address account, uint256 value) public virtual {
_spendAllowance(account, _msgSender(), value);
_burn(account, value);
}
}
lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.24;
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {EIP712Upgradeable} from "../../../utils/cryptography/EIP712Upgradeable.sol";
import {NoncesUpgradeable} from "../../../utils/NoncesUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20Permit, EIP712Upgradeable, NoncesUpgradeable {
bytes32 private constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Permit deadline has expired.
*/
error ERC2612ExpiredSignature(uint256 deadline);
/**
* @dev Mismatched signature.
*/
error ERC2612InvalidSigner(address signer, address owner);
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC-20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {}
/// @inheritdoc IERC20Permit
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > deadline) {
revert ERC2612ExpiredSignature(deadline);
}
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
if (signer != owner) {
revert ERC2612InvalidSigner(signer, owner);
}
_approve(owner, spender, value);
}
/// @inheritdoc IERC20Permit
function nonces(address owner) public view virtual override(IERC20Permit, NoncesUpgradeable) returns (uint256) {
return super.nonces(owner);
}
/// @inheritdoc IERC20Permit
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparatorV4();
}
}
lib/openzeppelin-contracts-upgradeable/contracts/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 "@openzeppelin/contracts/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;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/NoncesUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev Provides tracking nonces for addresses. Nonces will only increment.
*/
abstract contract NoncesUpgradeable is Initializable {
/**
* @dev The nonce used for an `account` is not the expected current nonce.
*/
error InvalidAccountNonce(address account, uint256 currentNonce);
/// @custom:storage-location erc7201:openzeppelin.storage.Nonces
struct NoncesStorage {
mapping(address account => uint256) _nonces;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Nonces")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant NoncesStorageLocation = 0x5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00;
function _getNoncesStorage() private pure returns (NoncesStorage storage $) {
assembly {
$.slot := NoncesStorageLocation
}
}
function __Nonces_init() internal onlyInitializing {
}
function __Nonces_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the next unused nonce for an address.
*/
function nonces(address owner) public view virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
return $._nonces[owner];
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
// decremented or reset. This guarantees that the nonce never overflows.
unchecked {
// It is important to do x++ and not ++x here.
return $._nonces[owner]++;
}
}
/**
* @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
*/
function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
uint256 current = _useNonce(owner);
if (nonce != current) {
revert InvalidAccountNonce(owner, current);
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
function __Pausable_init() internal onlyInitializing {
}
function __Pausable_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/cryptography/EIP712Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.24;
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: The upgradeable version of this contract does not use an immutable cache and recomputes the domain separator
* each time {_domainSeparatorV4} is called. This is cheaper than accessing a cached version in cold storage.
*/
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @custom:storage-location erc7201:openzeppelin.storage.EIP712
struct EIP712Storage {
bytes32 _hashedName;
bytes32 _hashedVersion;
string _name;
string _version;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;
function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
assembly {
$.slot := EIP712StorageLocation
}
}
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
EIP712Storage storage $ = _getEIP712Storage();
$._name = name;
$._version = version;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator();
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/// @inheritdoc IERC5267
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Name() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._name;
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Version() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._version;
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
*/
function _EIP712NameHash() internal view returns (bytes32) {
return keccak256(bytes(_EIP712Name()));
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
*/
function _EIP712VersionHash() internal view returns (bytes32) {
return keccak256(bytes(_EIP712Version()));
}
}
lib/openzeppelin-contracts/contracts/access/manager/AuthorityUtils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/manager/AuthorityUtils.sol)
pragma solidity ^0.8.20;
import {IAuthority} from "./IAuthority.sol";
library AuthorityUtils {
/**
* @dev Since `AccessManager` implements an extended IAuthority interface, invoking `canCall` with backwards compatibility
* for the preexisting `IAuthority` interface requires special care to avoid reverting on insufficient return data.
* This helper function takes care of invoking `canCall` in a backwards compatible way without reverting.
*/
function canCallWithDelay(
address authority,
address caller,
address target,
bytes4 selector
) internal view returns (bool immediate, uint32 delay) {
bytes memory data = abi.encodeCall(IAuthority.canCall, (caller, target, selector));
assembly ("memory-safe") {
mstore(0x00, 0x00)
mstore(0x20, 0x00)
if staticcall(gas(), authority, add(data, 0x20), mload(data), 0x00, 0x40) {
immediate := mload(0x00)
delay := mload(0x20)
// If delay does not fit in a uint32, return 0 (no delay)
// equivalent to: if gt(delay, 0xFFFFFFFF) { delay := 0 }
delay := mul(delay, iszero(shr(32, delay)))
}
}
}
}
lib/openzeppelin-contracts/contracts/access/manager/IAccessManaged.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAccessManaged.sol)
pragma solidity >=0.8.4;
interface IAccessManaged {
/**
* @dev Authority that manages this contract was updated.
*/
event AuthorityUpdated(address authority);
error AccessManagedUnauthorized(address caller);
error AccessManagedRequiredDelay(address caller, uint32 delay);
error AccessManagedInvalidAuthority(address authority);
/**
* @dev Returns the current authority.
*/
function authority() external view returns (address);
/**
* @dev Transfers control to a new authority. The caller must be the current authority.
*/
function setAuthority(address) external;
/**
* @dev Returns true only in the context of a delayed restricted call, at the moment that the scheduled operation is
* being consumed. Prevents denial of service for delayed restricted calls in the case that the contract performs
* attacker controlled calls.
*/
function isConsumingScheduledOp() external view returns (bytes4);
}
lib/openzeppelin-contracts/contracts/access/manager/IAccessManager.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (access/manager/IAccessManager.sol)
pragma solidity >=0.8.4;
interface IAccessManager {
/**
* @dev A delayed operation was scheduled.
*/
event OperationScheduled(
bytes32 indexed operationId,
uint32 indexed nonce,
uint48 schedule,
address caller,
address target,
bytes data
);
/**
* @dev A scheduled operation was executed.
*/
event OperationExecuted(bytes32 indexed operationId, uint32 indexed nonce);
/**
* @dev A scheduled operation was canceled.
*/
event OperationCanceled(bytes32 indexed operationId, uint32 indexed nonce);
/**
* @dev Informational labelling for a roleId.
*/
event RoleLabel(uint64 indexed roleId, string label);
/**
* @dev Emitted when `account` is granted `roleId`.
*
* NOTE: The meaning of the `since` argument depends on the `newMember` argument.
* If the role is granted to a new member, the `since` argument indicates when the account becomes a member of the role,
* otherwise it indicates the timestamp when the execution delay update takes effect for this account and roleId.
*/
event RoleGranted(uint64 indexed roleId, address indexed account, uint32 delay, uint48 since, bool newMember);
/**
* @dev Emitted when `account` membership or `roleId` is revoked. Unlike granting, revoking is instantaneous.
*/
event RoleRevoked(uint64 indexed roleId, address indexed account);
/**
* @dev Role acting as admin over a given `roleId` is updated.
*/
event RoleAdminChanged(uint64 indexed roleId, uint64 indexed admin);
/**
* @dev Role acting as guardian over a given `roleId` is updated.
*/
event RoleGuardianChanged(uint64 indexed roleId, uint64 indexed guardian);
/**
* @dev Grant delay for a given `roleId` will be updated to `delay` when `since` is reached.
*/
event RoleGrantDelayChanged(uint64 indexed roleId, uint32 delay, uint48 since);
/**
* @dev Target mode is updated (true = closed, false = open).
*/
event TargetClosed(address indexed target, bool closed);
/**
* @dev Role required to invoke `selector` on `target` is updated to `roleId`.
*/
event TargetFunctionRoleUpdated(address indexed target, bytes4 selector, uint64 indexed roleId);
/**
* @dev Admin delay for a given `target` will be updated to `delay` when `since` is reached.
*/
event TargetAdminDelayUpdated(address indexed target, uint32 delay, uint48 since);
error AccessManagerAlreadyScheduled(bytes32 operationId);
error AccessManagerNotScheduled(bytes32 operationId);
error AccessManagerNotReady(bytes32 operationId);
error AccessManagerExpired(bytes32 operationId);
error AccessManagerLockedRole(uint64 roleId);
error AccessManagerBadConfirmation();
error AccessManagerUnauthorizedAccount(address msgsender, uint64 roleId);
error AccessManagerUnauthorizedCall(address caller, address target, bytes4 selector);
error AccessManagerUnauthorizedConsume(address target);
error AccessManagerUnauthorizedCancel(address msgsender, address caller, address target, bytes4 selector);
error AccessManagerInvalidInitialAdmin(address initialAdmin);
/**
* @dev Check if an address (`caller`) is authorised to call a given function on a given contract directly (with
* no restriction). Additionally, it returns the delay needed to perform the call indirectly through the {schedule}
* & {execute} workflow.
*
* This function is usually called by the targeted contract to control immediate execution of restricted functions.
* Therefore we only return true if the call can be performed without any delay. If the call is subject to a
* previously set delay (not zero), then the function should return false and the caller should schedule the operation
* for future execution.
*
* If `allowed` is true, the delay can be disregarded and the operation can be immediately executed, otherwise
* the operation can be executed if and only if delay is greater than 0.
*
* NOTE: The IAuthority interface does not include the `uint32` delay. This is an extension of that interface that
* is backward compatible. Some contracts may thus ignore the second return argument. In that case they will fail
* to identify the indirect workflow, and will consider calls that require a delay to be forbidden.
*
* NOTE: This function does not report the permissions of the admin functions in the manager itself. These are defined by the
* {AccessManager} documentation.
*/
function canCall(
address caller,
address target,
bytes4 selector
) external view returns (bool allowed, uint32 delay);
/**
* @dev Expiration delay for scheduled proposals. Defaults to 1 week.
*
* IMPORTANT: Avoid overriding the expiration with 0. Otherwise every contract proposal will be expired immediately,
* disabling any scheduling usage.
*/
function expiration() external view returns (uint32);
/**
* @dev Minimum setback for all delay updates, with the exception of execution delays. It
* can be increased without setback (and reset via {revokeRole} in the event of an
* accidental increase). Defaults to 5 days.
*/
function minSetback() external view returns (uint32);
/**
* @dev Get whether the contract is closed disabling any access. Otherwise role permissions are applied.
*
* NOTE: When the manager itself is closed, admin functions are still accessible to avoid locking the contract.
*/
function isTargetClosed(address target) external view returns (bool);
/**
* @dev Get the role required to call a function.
*/
function getTargetFunctionRole(address target, bytes4 selector) external view returns (uint64);
/**
* @dev Get the admin delay for a target contract. Changes to contract configuration are subject to this delay.
*/
function getTargetAdminDelay(address target) external view returns (uint32);
/**
* @dev Get the id of the role that acts as an admin for the given role.
*
* The admin permission is required to grant the role, revoke the role and update the execution delay to execute
* an operation that is restricted to this role.
*/
function getRoleAdmin(uint64 roleId) external view returns (uint64);
/**
* @dev Get the role that acts as a guardian for a given role.
*
* The guardian permission allows canceling operations that have been scheduled under the role.
*/
function getRoleGuardian(uint64 roleId) external view returns (uint64);
/**
* @dev Get the role current grant delay.
*
* Its value may change at any point without an event emitted following a call to {setGrantDelay}.
* Changes to this value, including effect timepoint are notified in advance by the {RoleGrantDelayChanged} event.
*/
function getRoleGrantDelay(uint64 roleId) external view returns (uint32);
/**
* @dev Get the access details for a given account for a given role. These details include the timepoint at which
* membership becomes active, and the delay applied to all operations by this user that requires this permission
* level.
*
* Returns:
* [0] Timestamp at which the account membership becomes valid. 0 means role is not granted.
* [1] Current execution delay for the account.
* [2] Pending execution delay for the account.
* [3] Timestamp at which the pending execution delay will become active. 0 means no delay update is scheduled.
*/
function getAccess(
uint64 roleId,
address account
) external view returns (uint48 since, uint32 currentDelay, uint32 pendingDelay, uint48 effect);
/**
* @dev Check if a given account currently has the permission level corresponding to a given role. Note that this
* permission might be associated with an execution delay. {getAccess} can provide more details.
*/
function hasRole(uint64 roleId, address account) external view returns (bool isMember, uint32 executionDelay);
/**
* @dev Give a label to a role, for improved role discoverability by UIs.
*
* Requirements:
*
* - the caller must be a global admin
* - `roleId` must not be the `ADMIN_ROLE` or `PUBLIC_ROLE`
*
* Emits a {RoleLabel} event.
*/
function labelRole(uint64 roleId, string calldata label) external;
/**
* @dev Add `account` to `roleId`, or change its execution delay.
*
* This gives the account the authorization to call any function that is restricted to this role. An optional
* execution delay (in seconds) can be set. If that delay is non 0, the user is required to schedule any operation
* that is restricted to members of this role. The user will only be able to execute the operation after the delay has
* passed, before it has expired. During this period, admin and guardians can cancel the operation (see {cancel}).
*
* If the account has already been granted this role, the execution delay will be updated. This update is not
* immediate and follows the delay rules. For example, if a user currently has a delay of 3 hours, and this is
* called to reduce that delay to 1 hour, the new delay will take some time to take effect, enforcing that any
* operation executed in the 3 hours that follows this update was indeed scheduled before this update.
*
* Requirements:
*
* - the caller must be an admin for the role (see {getRoleAdmin})
* - granted role must not be the `PUBLIC_ROLE`
*
* Emits a {RoleGranted} event.
*/
function grantRole(uint64 roleId, address account, uint32 executionDelay) external;
/**
* @dev Remove an account from a role, with immediate effect. If the account does not have the role, this call has
* no effect.
*
* Requirements:
*
* - the caller must be an admin for the role (see {getRoleAdmin})
* - revoked role must not be the `PUBLIC_ROLE`
*
* Emits a {RoleRevoked} event if the account had the role.
*/
function revokeRole(uint64 roleId, address account) external;
/**
* @dev Renounce role permissions for the calling account with immediate effect. If the sender is not in
* the role this call has no effect.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* Emits a {RoleRevoked} event if the account had the role.
*/
function renounceRole(uint64 roleId, address callerConfirmation) external;
/**
* @dev Change admin role for a given role.
*
* Requirements:
*
* - the caller must be a global admin
* - `roleId` must not be the `ADMIN_ROLE` or `PUBLIC_ROLE`
*
* Emits a {RoleAdminChanged} event
*/
function setRoleAdmin(uint64 roleId, uint64 admin) external;
/**
* @dev Change guardian role for a given role.
*
* Requirements:
*
* - the caller must be a global admin
* - `roleId` must not be the `ADMIN_ROLE` or `PUBLIC_ROLE`
*
* Emits a {RoleGuardianChanged} event
*/
function setRoleGuardian(uint64 roleId, uint64 guardian) external;
/**
* @dev Update the delay for granting a `roleId`.
*
* Requirements:
*
* - the caller must be a global admin
* - `roleId` must not be the `PUBLIC_ROLE`
*
* Emits a {RoleGrantDelayChanged} event.
*/
function setGrantDelay(uint64 roleId, uint32 newDelay) external;
/**
* @dev Set the role required to call functions identified by the `selectors` in the `target` contract.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {TargetFunctionRoleUpdated} event per selector.
*/
function setTargetFunctionRole(address target, bytes4[] calldata selectors, uint64 roleId) external;
/**
* @dev Set the delay for changing the configuration of a given target contract.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {TargetAdminDelayUpdated} event.
*/
function setTargetAdminDelay(address target, uint32 newDelay) external;
/**
* @dev Set the closed flag for a contract.
*
* Closing the manager itself won't disable access to admin methods to avoid locking the contract.
*
* Requirements:
*
* - the caller must be a global admin
*
* Emits a {TargetClosed} event.
*/
function setTargetClosed(address target, bool closed) external;
/**
* @dev Return the timepoint at which a scheduled operation will be ready for execution. This returns 0 if the
* operation is not yet scheduled, has expired, was executed, or was canceled.
*/
function getSchedule(bytes32 id) external view returns (uint48);
/**
* @dev Return the nonce for the latest scheduled operation with a given id. Returns 0 if the operation has never
* been scheduled.
*/
function getNonce(bytes32 id) external view returns (uint32);
/**
* @dev Schedule a delayed operation for future execution, and return the operation identifier. It is possible to
* choose the timestamp at which the operation becomes executable as long as it satisfies the execution delays
* required for the caller. The special value zero will automatically set the earliest possible time.
*
* Returns the `operationId` that was scheduled. Since this value is a hash of the parameters, it can reoccur when
* the same parameters are used; if this is relevant, the returned `nonce` can be used to uniquely identify this
* scheduled operation from other occurrences of the same `operationId` in invocations of {execute} and {cancel}.
*
* Emits a {OperationScheduled} event.
*
* NOTE: It is not possible to concurrently schedule more than one operation with the same `target` and `data`. If
* this is necessary, a random byte can be appended to `data` to act as a salt that will be ignored by the target
* contract if it is using standard Solidity ABI encoding.
*/
function schedule(
address target,
bytes calldata data,
uint48 when
) external returns (bytes32 operationId, uint32 nonce);
/**
* @dev Execute a function that is delay restricted, provided it was properly scheduled beforehand, or the
* execution delay is 0.
*
* Returns the nonce that identifies the previously scheduled operation that is executed, or 0 if the
* operation wasn't previously scheduled (if the caller doesn't have an execution delay).
*
* Emits an {OperationExecuted} event only if the call was scheduled and delayed.
*/
function execute(address target, bytes calldata data) external payable returns (uint32);
/**
* @dev Cancel a scheduled (delayed) operation. Returns the nonce that identifies the previously scheduled
* operation that is cancelled.
*
* Requirements:
*
* - the caller must be the proposer, a guardian of the targeted function, or a global admin
*
* Emits a {OperationCanceled} event.
*/
function cancel(address caller, address target, bytes calldata data) external returns (uint32);
/**
* @dev Consume a scheduled operation targeting the caller. If such an operation exists, mark it as consumed
* (emit an {OperationExecuted} event and clean the state). Otherwise, throw an error.
*
* This is useful for contracts that want to enforce that calls targeting them were scheduled on the manager,
* with all the verifications that it implies.
*
* Emit a {OperationExecuted} event.
*/
function consumeScheduledOp(address caller, bytes calldata data) external;
/**
* @dev Hashing function for delayed operations.
*/
function hashOperation(address caller, address target, bytes calldata data) external view returns (bytes32);
/**
* @dev Changes the authority of a target managed by this manager instance.
*
* Requirements:
*
* - the caller must be a global admin
*/
function updateAuthority(address target, address newAuthority) external;
}
lib/openzeppelin-contracts/contracts/access/manager/IAuthority.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/manager/IAuthority.sol)
pragma solidity >=0.4.16;
/**
* @dev Standard interface for permissioning originally defined in Dappsys.
*/
interface IAuthority {
/**
* @dev Returns true if the caller can invoke on a target the function identified by a function selector.
*/
function canCall(address caller, address target, bytes4 selector) external view returns (bool allowed);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC5267.sol)
pragma solidity >=0.4.16;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
lib/openzeppelin-contracts/contracts/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
}
}
}
lib/openzeppelin-contracts/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);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also applies here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Bytes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/Bytes.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
/**
* @dev Bytes operations.
*/
library Bytes {
/**
* @dev Forward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the first instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return indexOf(buffer, s, 0);
}
/**
* @dev Forward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or after `pos`), returns the index of the next instance
* * If `s` is not present in the buffer (at or after `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
uint256 length = buffer.length;
for (uint256 i = pos; i < length; ++i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i)) == s) {
return i;
}
}
return type(uint256).max;
}
/**
* @dev Backward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the last instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return lastIndexOf(buffer, s, type(uint256).max);
}
/**
* @dev Backward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or before `pos`), returns the index of the previous instance
* * If `s` is not present in the buffer (at or before `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
unchecked {
uint256 length = buffer.length;
for (uint256 i = Math.min(Math.saturatingAdd(pos, 1), length); i > 0; --i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {
return i - 1;
}
}
return type(uint256).max;
}
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to the end of `buffer` into a new bytes object in
* memory.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return slice(buffer, start, buffer.length);
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to `end` (excluded) into a new bytes object in
* memory. The `end` argument is truncated to the length of the `buffer`.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
end = Math.min(end, buffer.length);
start = Math.min(start, end);
// allocate and copy
bytes memory result = new bytes(end - start);
assembly ("memory-safe") {
mcopy(add(result, 0x20), add(add(buffer, 0x20), start), sub(end, start))
}
return result;
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to the end of `buffer` to the start of that buffer,
* and shrinks the buffer length accordingly, effectively overriding the content of buffer with buffer[start:].
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
*/
function splice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return splice(buffer, start, buffer.length);
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to `end` (excluded) to the start of that buffer,
* and shrinks the buffer length accordingly, effectively overriding the content of buffer with buffer[start:end].
* The `end` argument is truncated to the length of the `buffer`.
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
*/
function splice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
end = Math.min(end, buffer.length);
start = Math.min(start, end);
// move and resize
assembly ("memory-safe") {
mcopy(add(buffer, 0x20), add(add(buffer, 0x20), start), sub(end, start))
mstore(buffer, sub(end, start))
}
return buffer;
}
/**
* @dev Replaces bytes in `buffer` starting at `pos` with all bytes from `replacement`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, buffer.length]`).
* If `pos >= buffer.length`, no replacement occurs and the buffer is returned unchanged.
*
* NOTE: This function modifies the provided buffer in place.
*/
function replace(bytes memory buffer, uint256 pos, bytes memory replacement) internal pure returns (bytes memory) {
return replace(buffer, pos, replacement, 0, replacement.length);
}
/**
* @dev Replaces bytes in `buffer` starting at `pos` with bytes from `replacement` starting at `offset`.
* Copies at most `length` bytes from `replacement` to `buffer`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, buffer.length]`, `offset` is
* clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
* buffer.length - pos))`. If `pos >= buffer.length` or `offset >= replacement.length`, no replacement occurs
* and the buffer is returned unchanged.
*
* NOTE: This function modifies the provided buffer in place.
*/
function replace(
bytes memory buffer,
uint256 pos,
bytes memory replacement,
uint256 offset,
uint256 length
) internal pure returns (bytes memory) {
// sanitize
pos = Math.min(pos, buffer.length);
offset = Math.min(offset, replacement.length);
length = Math.min(length, Math.min(replacement.length - offset, buffer.length - pos));
// replace
assembly ("memory-safe") {
mcopy(add(add(buffer, 0x20), pos), add(add(replacement, 0x20), offset), length)
}
return buffer;
}
/**
* @dev Concatenate an array of bytes into a single bytes object.
*
* For fixed bytes types, we recommend using the solidity built-in `bytes.concat` or (equivalent)
* `abi.encodePacked`.
*
* NOTE: this could be done in assembly with a single loop that expands starting at the FMP, but that would be
* significantly less readable. It might be worth benchmarking the savings of the full-assembly approach.
*/
function concat(bytes[] memory buffers) internal pure returns (bytes memory) {
uint256 length = 0;
for (uint256 i = 0; i < buffers.length; ++i) {
length += buffers[i].length;
}
bytes memory result = new bytes(length);
uint256 offset = 0x20;
for (uint256 i = 0; i < buffers.length; ++i) {
bytes memory input = buffers[i];
assembly ("memory-safe") {
mcopy(add(result, offset), add(input, 0x20), mload(input))
}
unchecked {
offset += input.length;
}
}
return result;
}
/**
* @dev Split each byte in `input` into two nibbles (4 bits each)
*
* Example: hex"01234567" → hex"0001020304050607"
*/
function toNibbles(bytes memory input) internal pure returns (bytes memory output) {
assembly ("memory-safe") {
let length := mload(input)
output := mload(0x40)
mstore(0x40, add(add(output, 0x20), mul(length, 2)))
mstore(output, mul(length, 2))
for {
let i := 0
} lt(i, length) {
i := add(i, 0x10)
} {
let chunk := shr(128, mload(add(add(input, 0x20), i)))
chunk := and(
0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff,
or(shl(64, chunk), chunk)
)
chunk := and(
0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff,
or(shl(32, chunk), chunk)
)
chunk := and(
0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff,
or(shl(16, chunk), chunk)
)
chunk := and(
0x00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff,
or(shl(8, chunk), chunk)
)
chunk := and(
0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f,
or(shl(4, chunk), chunk)
)
mstore(add(add(output, 0x20), mul(i, 2)), chunk)
}
}
}
/**
* @dev Returns true if the two byte buffers are equal.
*/
function equal(bytes memory a, bytes memory b) internal pure returns (bool) {
return a.length == b.length && keccak256(a) == keccak256(b);
}
/**
* @dev Reverses the byte order of a bytes32 value, converting between little-endian and big-endian.
* Inspired by https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel[Reverse Parallel]
*/
function reverseBytes32(bytes32 value) internal pure returns (bytes32) {
value = // swap bytes
((value >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((value & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
value = // swap 8-byte long pairs
((value >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((value & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
return (value >> 128) | (value << 128); // swap 16-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 128-bit values.
function reverseBytes16(bytes16 value) internal pure returns (bytes16) {
value = // swap bytes
((value & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) |
((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) |
((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) |
((value & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32);
return (value >> 64) | (value << 64); // swap 8-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 64-bit values.
function reverseBytes8(bytes8 value) internal pure returns (bytes8) {
value = ((value & 0xFF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF) << 8); // swap bytes
value = ((value & 0xFFFF0000FFFF0000) >> 16) | ((value & 0x0000FFFF0000FFFF) << 16); // swap 2-byte long pairs
return (value >> 32) | (value << 32); // swap 4-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 32-bit values.
function reverseBytes4(bytes4 value) internal pure returns (bytes4) {
value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); // swap bytes
return (value >> 16) | (value << 16); // swap 2-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 16-bit values.
function reverseBytes2(bytes2 value) internal pure returns (bytes2) {
return (value >> 8) | (value << 8);
}
/**
* @dev Counts the number of leading zero bits a bytes array. Returns `8 * buffer.length`
* if the buffer is all zeros.
*/
function clz(bytes memory buffer) internal pure returns (uint256) {
for (uint256 i = 0; i < buffer.length; i += 0x20) {
bytes32 chunk = _unsafeReadBytesOffset(buffer, i);
if (chunk != bytes32(0)) {
return Math.min(8 * i + Math.clz(uint256(chunk)), 8 * buffer.length);
}
}
return 8 * buffer.length;
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/Strings.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
import {Bytes} from "./Bytes.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
0xffffffff | // first 32 bits corresponding to the control characters (U+0000 to U+001F)
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(add(buffer, 0x20), length)
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Converts a `bytes` buffer to its ASCII `string` hexadecimal representation.
*/
function toHexString(bytes memory input) internal pure returns (string memory) {
unchecked {
bytes memory buffer = new bytes(2 * input.length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 0; i < input.length; ++i) {
uint8 v = uint8(input[i]);
buffer[2 * i + 2] = HEX_DIGITS[v >> 4];
buffer[2 * i + 3] = HEX_DIGITS[v & 0xf];
}
return string(buffer);
}
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return Bytes.equal(bytes(a), bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes backslashes (including those in \uXXXX sequences) and the characters in ranges
* defined in section 2.5 of RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). All control characters in U+0000
* to U+001F are escaped (\b, \t, \n, \f, \r use short form; others use \u00XX). ECMAScript's `JSON.parse` does
* recover escaped unicode characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
// Put output at the FMP. Memory will be reserved later when we figure out the actual length of the escaped
// string. All write are done using _unsafeWriteBytesOffset, which avoid the (expensive) length checks for
// each character written.
bytes memory output;
assembly ("memory-safe") {
output := mload(0x40)
}
uint256 outputLength = 0;
for (uint256 i = 0; i < buffer.length; ++i) {
uint8 char = uint8(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (((SPECIAL_CHARS_LOOKUP & (1 << char)) != 0)) {
_unsafeWriteBytesOffset(output, outputLength++, "\\");
if (char == 0x08) _unsafeWriteBytesOffset(output, outputLength++, "b");
else if (char == 0x09) _unsafeWriteBytesOffset(output, outputLength++, "t");
else if (char == 0x0a) _unsafeWriteBytesOffset(output, outputLength++, "n");
else if (char == 0x0c) _unsafeWriteBytesOffset(output, outputLength++, "f");
else if (char == 0x0d) _unsafeWriteBytesOffset(output, outputLength++, "r");
else if (char == 0x5c) _unsafeWriteBytesOffset(output, outputLength++, "\\");
else if (char == 0x22) {
// solhint-disable-next-line quotes
_unsafeWriteBytesOffset(output, outputLength++, '"');
} else {
// U+0000 to U+001F without short form: output \u00XX
_unsafeWriteBytesOffset(output, outputLength++, "u");
_unsafeWriteBytesOffset(output, outputLength++, "0");
_unsafeWriteBytesOffset(output, outputLength++, "0");
_unsafeWriteBytesOffset(output, outputLength++, HEX_DIGITS[char >> 4]);
_unsafeWriteBytesOffset(output, outputLength++, HEX_DIGITS[char & 0x0f]);
}
} else {
_unsafeWriteBytesOffset(output, outputLength++, bytes1(char));
}
}
// write the actual length and reserve memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, add(outputLength, 0x20)))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
/**
* @dev Write a bytes1 to a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeWriteBytesOffset(bytes memory buffer, uint256 offset, bytes1 value) private pure {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
mstore8(add(add(buffer, 0x20), offset), shr(248, value))
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature is invalid.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
*
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Variant of {tryRecover} that takes a signature in calldata
*/
function tryRecoverCalldata(
bytes32 hash,
bytes calldata signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, calldata slices would work here, but are
// significantly more expensive (length check) than using calldataload in assembly.
assembly ("memory-safe") {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Variant of {recover} that takes a signature in calldata
*/
function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)
* formats. Returns (0,0,0) for invalid signatures.
*
* For 64-byte signatures, `v` is automatically normalized to 27 or 28.
* For 65-byte signatures, `v` is returned as-is and MUST already be 27 or 28 for use with ecrecover.
*
* Consider validating the result before use, or use {tryRecover}/{recover} which perform full validation.
*/
function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch mload(signature)
// - case 65: r,s,v signature (standard)
case 65 {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Variant of {parse} that takes a signature in calldata
*/
function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch signature.length
// - case 65: r,s,v signature (standard)
case 65 {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
r := calldataload(signature.offset)
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.24;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
error ERC5267ExtensionsNotSupported();
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
*/
function toDataWithIntendedValidatorHash(
address validator,
bytes32 messageHash
) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, hex"19_00")
mstore(0x02, shl(96, validator))
mstore(0x16, messageHash)
digest := keccak256(0x00, 0x36)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns the EIP-712 domain separator constructed from an `eip712Domain`. See {IERC5267-eip712Domain}
*
* This function dynamically constructs the domain separator based on which fields are present in the
* `fields` parameter. It contains flags that indicate which domain fields are present:
*
* * Bit 0 (0x01): name
* * Bit 1 (0x02): version
* * Bit 2 (0x04): chainId
* * Bit 3 (0x08): verifyingContract
* * Bit 4 (0x10): salt
*
* Arguments that correspond to fields which are not present in `fields` are ignored. For example, if `fields` is
* `0x0f` (`0b01111`), then the `salt` parameter is ignored.
*/
function toDomainSeparator(
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt
) internal pure returns (bytes32 hash) {
return
toDomainSeparator(
fields,
keccak256(bytes(name)),
keccak256(bytes(version)),
chainId,
verifyingContract,
salt
);
}
/// @dev Variant of {toDomainSeparator-bytes1-string-string-uint256-address-bytes32} that uses hashed name and version.
function toDomainSeparator(
bytes1 fields,
bytes32 nameHash,
bytes32 versionHash,
uint256 chainId,
address verifyingContract,
bytes32 salt
) internal pure returns (bytes32 hash) {
bytes32 domainTypeHash = toDomainTypeHash(fields);
assembly ("memory-safe") {
// align fields to the right for easy processing
fields := shr(248, fields)
// FMP used as scratch space
let fmp := mload(0x40)
mstore(fmp, domainTypeHash)
let ptr := add(fmp, 0x20)
if and(fields, 0x01) {
mstore(ptr, nameHash)
ptr := add(ptr, 0x20)
}
if and(fields, 0x02) {
mstore(ptr, versionHash)
ptr := add(ptr, 0x20)
}
if and(fields, 0x04) {
mstore(ptr, chainId)
ptr := add(ptr, 0x20)
}
if and(fields, 0x08) {
mstore(ptr, verifyingContract)
ptr := add(ptr, 0x20)
}
if and(fields, 0x10) {
mstore(ptr, salt)
ptr := add(ptr, 0x20)
}
hash := keccak256(fmp, sub(ptr, fmp))
}
}
/// @dev Builds an EIP-712 domain type hash depending on the `fields` provided, following https://eips.ethereum.org/EIPS/eip-5267[ERC-5267]
function toDomainTypeHash(bytes1 fields) internal pure returns (bytes32 hash) {
if (fields & 0x20 == 0x20) revert ERC5267ExtensionsNotSupported();
assembly ("memory-safe") {
// align fields to the right for easy processing
fields := shr(248, fields)
// FMP used as scratch space
let fmp := mload(0x40)
mstore(fmp, "EIP712Domain(")
let ptr := add(fmp, 0x0d)
// name field
if and(fields, 0x01) {
mstore(ptr, "string name,")
ptr := add(ptr, 0x0c)
}
// version field
if and(fields, 0x02) {
mstore(ptr, "string version,")
ptr := add(ptr, 0x0f)
}
// chainId field
if and(fields, 0x04) {
mstore(ptr, "uint256 chainId,")
ptr := add(ptr, 0x10)
}
// verifyingContract field
if and(fields, 0x08) {
mstore(ptr, "address verifyingContract,")
ptr := add(ptr, 0x1a)
}
// salt field
if and(fields, 0x10) {
mstore(ptr, "bytes32 salt,")
ptr := add(ptr, 0x0d)
}
// if any field is enabled, remove the trailing comma
ptr := sub(ptr, iszero(iszero(and(fields, 0x1f))))
// add the closing brace
mstore8(ptr, 0x29) // add closing brace
ptr := add(ptr, 1)
hash := keccak256(fmp, sub(ptr, fmp))
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory buffer) private pure returns (bool) {
uint256 chunk;
for (uint256 i = 0; i < buffer.length; i += 0x20) {
// See _unsafeReadBytesOffset from utils/Bytes.sol
assembly ("memory-safe") {
chunk := mload(add(add(buffer, 0x20), i))
}
if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
/**
* @dev Counts the number of leading zero bits in a uint256.
*/
function clz(uint256 x) internal pure returns (uint256) {
return ternary(x == 0, 256, 255 - log2(x));
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev A uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
src/auth/RoycoAuth.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { AccessManagedUpgradeable } from "../../lib/openzeppelin-contracts-upgradeable/contracts/access/manager/AccessManagedUpgradeable.sol";
import { PausableUpgradeable } from "../../lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol";
import { IRoycoAuth } from "../interfaces/IRoycoAuth.sol";
/**
* @title RoycoAuth
* @author Ankur Dubey, Shivaansh Kapoor, Tomer Ganor
* @notice Abstract contract that provides access control and pausability functionality for Royco contracts
* @dev Combines OpenZeppelin's AccessManager-based access control (`restricted` gating) with pausability
*/
abstract contract RoycoAuth is AccessManagedUpgradeable, PausableUpgradeable, IRoycoAuth {
/// @notice Initializes the access control and pausability state
/// @param _initialAuthority The initial authority (AccessManager) that governs the restricted functions
function __RoycoAuth_init(address _initialAuthority) internal onlyInitializing {
require(_initialAuthority != address(0), NULL_ADDRESS());
__AccessManaged_init(_initialAuthority);
__Pausable_init();
}
/// @inheritdoc IRoycoAuth
function pause() external virtual restricted {
_pause();
}
/// @inheritdoc IRoycoAuth
function unpause() external virtual restricted {
_unpause();
}
}
src/base/RoycoBase.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { RoycoAuth } from "../auth/RoycoAuth.sol";
/**
* @title RoycoBase
* @author Ankur Dubey, Shivaansh Kapoor, Tomer Ganor
* @notice Abstract base contract for upgradeable Royco protocol contracts
*/
abstract contract RoycoBase is RoycoAuth {
/// @dev Disable the initializers
constructor() {
_disableInitializers();
}
/// @notice Initializes the Royco base contract
/// @param _initialAuthority The initial authority for the contract
function __RoycoBase_init(address _initialAuthority) internal onlyInitializing {
__RoycoAuth_init(_initialAuthority);
}
}
src/interfaces/IRoycoAuth.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
interface IRoycoAuth {
/// @dev Thrown when an address is set to the null address
error NULL_ADDRESS();
/// @notice Pauses the contract
function pause() external;
/// @notice Unpauses the contract
function unpause() external;
}
src/interfaces/IRoycoDayKernel.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { AssetClaims, DispatchMode, Operation, SyncedAccountingState, TrancheType } from "../libraries/Types.sol";
import { NAV_UNIT, TRANCHE_UNIT } from "../libraries/Units.sol";
/**
* @title IRoycoDayKernel
* @notice Interface for the base Royco kernel contract
* @dev The kernel contract is responsible for orchestrating all operations for every tranche (senior, junior, and liquidity) in a Royco market
*/
interface IRoycoDayKernel {
/**
* @notice Initialization parameters for the Royco Kernel
* @custom:field initialAuthority - The access manager for this kernel
* @custom:field seniorTranche - The address of the Royco senior tranche associated with this kernel
* @custom:field juniorTranche - The address of the Royco junior tranche associated with this kernel
* @custom:field liquidityProviderTranche - The address of the Royco liquidity provider tranche associated with this kernel
* @custom:field collateralAsset - The address of the coinvested collateral asset both the senior and junior tranches deposit
* @custom:field lptAsset - The base asset of the liquidity provider tranche (the liquidity venue's market-making position token)
* @custom:field quoteAsset - The quote asset paired against the senior share in the liquidity venue, validated against the venue's registration
* @custom:field accountant - The address of the accountant for the Royco market
* @custom:field protocolFeeRecipient - The market's protocol fee recipient
* @custom:field stSelfLiquidationBonusWAD - The market's configured ST self-liquidation bonus remitted to redeeming ST LPs when liquidation coverageUtilization threshold has been breached, scaled to WAD precision
* @custom:field roycoBlacklist - The market's blacklist contract consulted on tranche balance updates (the null address disables blacklist screening)
* @custom:field collateralAssetOracle - The collateral asset oracle pricing 1 whole collateral asset in NAV units (staleness is enforced inside the oracle, per hop, via its construction immutables)
* @custom:field sequencerUptimeFeed - The L2 sequencer uptime feed used to gate price queries (the null address when not applicable)
* @custom:field gracePeriodSeconds - The grace period in seconds after the L2 sequencer is back up before oracle prices are trusted again
*/
struct RoycoDayKernelInitParams {
address initialAuthority;
address seniorTranche;
address juniorTranche;
address liquidityProviderTranche;
address collateralAsset;
address lptAsset;
address quoteAsset;
address accountant;
address protocolFeeRecipient;
uint64 stSelfLiquidationBonusWAD;
address roycoBlacklist;
address collateralAssetOracle;
address sequencerUptimeFeed;
uint48 gracePeriodSeconds;
}
/**
* @notice Storage state for the Royco Day Kernel
* @custom:storage-location erc7201:Royco.storage.RoycoDayKernelState
* @custom:field seniorTranche - The address of the Royco senior tranche associated with the kernel
* @custom:field stSelfLiquidationBonusWAD - The market's configured ST self-liquidation bonus remitted to redeeming ST LPs when liquidation coverageUtilization threshold has been breached, scaled to WAD precision
* @custom:field juniorTranche - The address of the Royco junior tranche associated with the kernel
* @custom:field liquidityProviderTranche - The address of the Royco liquidity provider tranche associated with the kernel
* @custom:field collateralAsset - The address of the coinvested collateral asset both the senior and junior tranches deposit
* @custom:field lptAsset - The base asset of the liquidity provider tranche (the liquidity venue's market-making position token)
* @custom:field lptAssetDecimals - The LPT asset's decimals, from which one whole LPT asset (10 ** decimals) is derived
* @custom:field quoteAsset - The quote asset paired against the senior share in the liquidity venue
* @custom:field accountant - The address of the accountant for the Royco market
* @custom:field protocolFeeRecipient - The market's configured protocol fee recipient
* @custom:field roycoBlacklist - The market's blacklist contract consulted on tranche balance updates (the null address disables blacklist screening)
* @custom:field collateralAssetOracle - The collateral asset oracle pricing 1 whole collateral asset in NAV units, also the clock the kernel pokes on every price-cached operation (staleness is enforced inside the oracle, per hop, via its construction immutables)
* @custom:field collateralAssetDecimals - The collateral asset's decimals, from which one whole collateral asset (10 ** decimals) is derived
* @custom:field sequencerUptimeFeed - The L2 sequencer uptime feed used to gate price queries (the null address when not applicable)
* @custom:field gracePeriodSeconds - The grace period in seconds after the L2 sequencer is back up before oracle prices are trusted again
* @custom:field totalCollateralAssets - The coinvested collateral assets held for the senior and junior tranches, in the collateral asset's units
* @custom:field totalLPTAssets - The yield bearing assets held by the liquidity provider tranche, in LPT's asset units
* @custom:field lptOwnedSeniorTrancheShares - The senior tranche shares held by the liquidity provider tranche (accumulated liquidity premium payments)
*/
struct RoycoDayKernelState {
// Slot 0
address seniorTranche;
uint64 stSelfLiquidationBonusWAD;
// Slot 1
address juniorTranche;
// Slot 2
address liquidityProviderTranche;
// Slot 3
address collateralAsset;
uint64 oneWholeCollateralAsset;
// Slot 4
address lptAsset;
uint64 oneWholeLPTAsset;
// Slot 5
address quoteAsset;
// Slot 6
address accountant;
// Slot 7
address protocolFeeRecipient;
// Slot 8
address roycoBlacklist;
// Slot 9
address collateralAssetOracle;
// Slot 10
address sequencerUptimeFeed;
uint48 gracePeriodSeconds;
// Slot 11-13
TRANCHE_UNIT totalCollateralAssets;
TRANCHE_UNIT totalLPTAssets;
uint256 lptOwnedSeniorTrancheShares;
}
/**
* @notice Immutable state variables for the Royco Day Kernel
* @custom:field seniorTranche - The address of the Royco senior tranche associated with the kernel
* @custom:field juniorTranche - The address of the Royco junior tranche associated with the kernel
* @custom:field collateralAsset - The address of the coinvested collateral asset both the senior and junior tranches deposit
* @custom:field liquidityProviderTranche - The address of the Royco liquidity provider tranche associated with the kernel
* @custom:field lptAsset - The base asset of the liquidity provider tranche (the liquidity venue's market-making position token)
* @custom:field quoteAsset - The quote asset paired against the senior share in the liquidity venue
* @custom:field accountant - The address of the accountant for the Royco market
*/
struct RoycoDayKernelImmutableState {
address seniorTranche;
address juniorTranche;
address collateralAsset;
address liquidityProviderTranche;
address lptAsset;
address quoteAsset;
address accountant;
}
/// @notice Emitted when the protocol fee recipient is updated
/// @param protocolFeeRecipient The new protocol fee recipient
event ProtocolFeeRecipientUpdated(address protocolFeeRecipient);
/// @notice Emitted when the ST self-liquidation bonus is updated
/// @param stSelfLiquidationBonusWAD The new ST self-liquidation bonus remitted to redeeming ST LPs when liquidation coverageUtilization threshold has been breached
event SeniorTrancheSelfLiquidationBonusUpdated(uint64 stSelfLiquidationBonusWAD);
/// @notice Emitted when the market's blacklist contract is updated
/// @param roycoBlacklist The new blacklist contract address (the null address if screening is disabled)
event RoycoBlacklistUpdated(address roycoBlacklist);
/**
* @notice Emitted when the collateral asset oracle is updated
* @param collateralAssetOracle The new collateral asset oracle pricing 1 whole collateral asset in NAV units
*/
event CollateralAssetOracleUpdated(address indexed collateralAssetOracle);
/**
* @notice Emitted when the L2 sequencer uptime feed (and its grace period) used to gate price queries is updated
* @param sequencerUptimeFeed The new L2 sequencer uptime feed (the null address if the check is disabled)
* @param gracePeriodSeconds The new grace period seconds
*/
event SequencerUptimeFeedUpdated(address indexed sequencerUptimeFeed, uint48 gracePeriodSeconds);
/// @notice Emitted when a pre-operation tranche accounting synchronization settles
/// @param resultingState The resulting market state after synchronizing the tranche accounting
event PreOpTrancheAccountingSynced(SyncedAccountingState resultingState);
/**
* @notice Emitted when a post-operation tranche accounting synchronization settles
* @param op The operation the synchronization settled
* @param resultingState The resulting market state after synchronizing the tranche accounting
*/
event PostOpTrancheAccountingSynced(Operation op, SyncedAccountingState resultingState);
/**
* @notice Emitted when the kernel deploys its held liquidity-premium senior shares into the liquidity provider tranche's venue
* @param stSharesReinvested The senior tranche shares drained from the kernel's held balance and deployed into the liquidity venue
* @param lptAssetsMinted The liquidity provider tranche assets minted to the liquidity provider tranche by the deployment
*/
event LiquidityPremiumReinvested(uint256 stSharesReinvested, TRANCHE_UNIT lptAssetsMinted);
/**
* @notice Emitted when a liquidity-premium reinvestment attempt does not execute, leaving the senior shares idle in the kernel
* @param stSharesToReinvest The senior tranche shares the kernel attempted to deploy into the liquidity venue
* @param minLPTAssetsOut The slippage-bounded minimum liquidity provider tranche assets the deployment demanded
* @param revertData The raw revert data returned by the venue, identifying a breached slippage gate versus any other add failure
*/
event LiquidityPremiumReinvestmentFailed(uint256 stSharesToReinvest, TRANCHE_UNIT minLPTAssetsOut, bytes revertData);
/// @notice Thrown when the tranche and the kernel's corresponding tranche assets don't match
error TRANCHE_AND_KERNEL_ASSETS_MISMATCH();
/// @notice Thrown when the caller of a permissioned function isn't the market's liquidity provider tranche
error ONLY_LIQUIDITY_PROVIDER_TRANCHE();
/// @notice Thrown when an LP is attempting to deposit into or redeem from the market while it is in a fixed term state
error DISABLED_IN_FIXED_TERM_STATE();
/// @notice Thrown when a deposit would mint zero tranche shares (a dust amount that prices to zero shares)
error MUST_MINT_NON_ZERO_SHARES();
/// @notice Thrown when a redemption is requested with zero shares
error MUST_REDEMPTION_NON_ZERO_SHARES();
/// @notice Thrown when the caller of a permissioned function isn't the market's senior, junior, or liquidity provider tranche
error ONLY_TRANCHE();
/// @notice Thrown when a venue driver restricted to kernel self-calls is invoked by any other caller
error ONLY_SELF();
/// @notice Thrown when the senior tranche self-liquidation bonus is set above 100% (WAD)
error INVALID_SELF_LIQUIDATION_BONUS();
/// @notice Thrown when the collateral asset oracle does not price this market's collateral asset
error COLLATERAL_ASSET_ORACLE_MISMATCH();
/// @notice Thrown when a sequencer uptime feed is configured with a non-positive grace period
error INVALID_GRACE_PERIOD_SECONDS();
/// @notice Thrown when the collateral asset oracle's price is invalid
error INVALID_PRICE();
/// @notice Thrown when the L2 sequencer is reported down by the configured sequencer uptime feed
error SEQUENCER_DOWN();
/// @notice Thrown when the L2 sequencer's grace period has not fully elapsed since it was last restored
error GRACE_PERIOD_NOT_OVER();
/// @notice Thrown when the market's coverage requirement is violated
error COVERAGE_REQUIREMENT_VIOLATED();
/// @notice Thrown when the market's liquidity requirement is violated
error LIQUIDITY_REQUIREMENT_VIOLATED();
/// @notice Thrown when a JT deposit settles with the market still at or above its liquidation coverage utilization
error JT_DEPOSIT_BLOCKED_DURING_LIQUIDATION();
/// @notice Thrown when the collateral asset's decimals are greater than 18
error INVALID_COLLATERAL_ASSET_DECIMALS();
/// @notice Thrown when the LPT asset's decimals are greater than 18
error INVALID_LPT_ASSET_DECIMALS();
/// @notice Thrown when the caller is not the accountant
error ONLY_ACCOUNTANT();
/// @notice Retrieves the senior tranche address
/// @return seniorTranche The address of the senior tranche for this Royco market
function seniorTranche() external view returns (address seniorTranche);
/// @notice Retrieves the junior tranche address
/// @return juniorTranche The address of the junior tranche for this Royco market
function juniorTranche() external view returns (address juniorTranche);
/// @notice Retrieves the coinvested collateral asset address
/// @return collateralAsset The address of the coinvested collateral asset both the senior and junior tranches deposit
function collateralAsset() external view returns (address collateralAsset);
/// @notice Retrieves the liquidity provider tranche address
/// @return liquidityProviderTranche The address of the liquidity provider tranche for this Royco market
function liquidityProviderTranche() external view returns (address liquidityProviderTranche);
/// @notice Retrieves the liquidity provider tranche's base asset (the liquidity venue's market-making position token) address
/// @return lptAsset The liquidity provider tranche's base asset address
function lptAsset() external view returns (address lptAsset);
/// @notice Retrieves the quote asset paired against the senior share in the liquidity venue
/// @return quoteAsset The quote asset's address
function quoteAsset() external view returns (address quoteAsset);
/// @notice Retrieves the accountant address
/// @return accountant The accountant responsible for maintaining this Royco market's accounting state and marking tranche NAVs to market
function accountant() external view returns (address accountant);
/**
* @notice Converts the specified collateral assets denominated in tranche units to their value in the kernel's NAV units
* @param _collateralAssets The collateral assets denominated in tranche units to convert to the kernel's NAV units
* @return value The specified collateral assets denominated in tranche units converted to the kernel's NAV units
*/
function convertCollateralAssetsToValue(TRANCHE_UNIT _collateralAssets) external view returns (NAV_UNIT value);
/**
* @notice Converts the specified value denominated in the kernel's NAV units to collateral assets denominated in tranche units
* @param _value The value denominated in the kernel's NAV units to convert to collateral assets denominated in tranche units
* @return collateralAssets The specified value denominated in the kernel's NAV units converted to collateral assets denominated in tranche units
*/
function convertValueToCollateralAssets(NAV_UNIT _value) external view returns (TRANCHE_UNIT collateralAssets);
/**
* @notice Converts the specified LPT assets denominated in its tranche units to their value in the kernel's NAV units
* @param _lptAssets The LPT assets denominated in tranche units to convert to the kernel's NAV units
* @return value The specified LPT assets denominated in its tranche units converted to the kernel's NAV units
*/
function convertLPTAssetsToValue(TRANCHE_UNIT _lptAssets) external view returns (NAV_UNIT value);
/**
* @notice Converts the specified value denominated in the kernel's NAV units to assets denominated in LPT's tranche units
* @param _value The value denominated in the kernel's NAV units to convert to assets denominated in LPT's tranche units
* @return lptAssets The specified value denominated in the kernel's NAV units converted to assets denominated in LPT's tranche units
*/
function convertValueToLPTAssets(NAV_UNIT _value) external view returns (TRANCHE_UNIT lptAssets);
/**
* @notice Queries the collateral asset oracle for the value of 1 whole collateral asset in NAV units
* @dev Always prices the oracle live, never through the operation's cache
* @dev The reported price is gated by the L2 sequencer, staleness, and non-zero price checks
* @return collateralAssetPrice The value of 1 whole collateral asset in NAV units
*/
function queryCollateralAssetOracle() external view returns (NAV_UNIT collateralAssetPrice);
/**
* @notice Queries the liquidity venue for the value of 1 whole LPT asset in NAV units
* @dev Always prices the venue live, never through the operation's cache
* @dev Implemented by the concrete liquidity venue against its manipulation-resistant venue oracle
* @return lptAssetPrice The value of 1 whole LPT asset in NAV units
*/
function queryLPTAssetOracle() external view returns (NAV_UNIT lptAssetPrice);
/**
* @notice Returns the maximum amount of assets that can be deposited in-kind into the specified tranche
* @dev Only callable by one of the market's tranches: the queried tranche is the calling tranche
* @param _receiver The address that will receive the tranche shares equating to the deposited assets
* @return assets The maximum amount of assets that can be deposited into the calling tranche, denominated in its tranche units
*/
function inkindMaxDeposit(address _receiver) external view returns (TRANCHE_UNIT assets);
/**
* @notice Returns the maximum number of shares that can be redeemed in-kind from the calling tranche, unbounded by any owner's balance
* @dev Only callable by one of the market's tranches: the queried tranche is the calling tranche
* @param _owner The address that is redeeming the shares
* @return maxRedeemableShares The maximum number of shares that can be redeemed from the calling tranche
*/
function inkindMaxRedeemable(address _owner) external view returns (uint256 maxRedeemableShares);
/**
* @notice Returns the maximum number of shares that can be redeemed from the liquidity provider tranche via a multi-asset redemption, unbounded by any owner's balance
* @dev A multi-asset redemption redeems its senior tranche share legs (the proportional removal's ST leg and the idle liquidity
* premium pile) in-flow, shrinking the liquidity requirement alongside the withdrawal, so its bound is at least the
* in-kind bound, and strictly exceeds it whenever the liquidity requirement binds and the removal's senior-share
* legs carry value
* @dev NON-VIEW: sizes the requirement reduction through the venue removal's execute-and-revert preview, which mutates no state net
* @param _owner The address that is redeeming the shares
* @return maxRedeemableShares The maximum number of shares that can be redeemed multi-asset from the liquidity provider tranche
*/
function lptMaxRedeemableMultiAsset(address _owner) external returns (uint256 maxRedeemableShares);
/**
* @notice Synchronizes and persists the raw and effective NAVs of all tranches
* @dev Only executes a pre-op sync because there is no operation being executed in the same call as this sync
* @dev Never deploys the idle liquidity-premium senior shares: the pool hook routes this sync from inside the venue's
* own frame, where a deployment's venue add would re-enter it
* @return state The synced NAV, impermanent loss, and fee accounting containing all mark-to-market accounting data
*/
function syncTrancheAccounting() external returns (SyncedAccountingState memory state);
/**
* @notice Synchronizes and persists the raw and effective NAVs of all tranches from the accountant
* @dev Only executes a pre-op sync because there is no operation being executed in the same call as this sync
* @dev Never deploys the idle liquidity-premium senior shares: the pool hook routes this sync from inside the venue's
* own frame, where a deployment's venue add would re-enter it
* @dev Only callable by the accountant
* @return state The synced NAV, impermanent loss, and fee accounting containing all mark-to-market accounting data
*/
function syncTrancheAccountingFromAccountant() external returns (SyncedAccountingState memory state);
/**
* @notice Synchronizes and persists the raw and effective NAVs of all tranches, returning the specified tranche's post-sync claims and supply
* @dev Only executes a pre-op sync because there is no operation being executed in the same call as this sync
* @dev Syncs every tranche exactly as `syncTrancheAccounting` does, the tranche type only scopes the claims and supply returned alongside the state
* @dev The executed counterpart of `previewSyncTrancheAccountingFor`: it returns the same figures against the same accounting state, but commits them
* @param _trancheType An enumerator indicating which tranche to return claims and total tranche shares for
* @return state The synced NAV, impermanent loss, and fee accounting containing all mark-to-market accounting data
* @return claims The asset claims that the specified tranche has denominated in tranche-native units
* @return totalTrancheShares The total number of shares that exist in the specified tranche after the post-sync mint of its accrued shares: the protocol fee shares for the senior and junior tranches, plus the liquidity premium shares for the senior tranche (the liquidity provider tranche mints none)
*/
function syncTrancheAccountingFor(TrancheType _trancheType)
external
returns (SyncedAccountingState memory state, AssetClaims memory claims, uint256 totalTrancheShares);
/**
* @notice Syncs the tranche accounting and attempts to reinvest the liquidity provider tranche's idle liquidity-premium senior shares into its market-making inventory
* @dev The on-demand deployment path: a sync never deploys the pile, so idle premium leaves the kernel only through an operation's reinvestment tail or this entrypoint
* @dev Values the reinvested shares against the freshly synced senior share rate, so a smaller amount can clear the venue's slippage gate when reinvesting the entire idle balance would not
* @param _stShares The amount of idle liquidity-premium senior shares to reinvest, or type(uint256).max to reinvest the entire idle balance
*/
function reinvestLiquidityPremium(uint256 _stShares) external;
/**
* @notice Previews a synchronization of the raw and effective NAVs of all tranches
* @dev Does not mutate any state
* @param _trancheType An enumerator indicating which tranche to execute this preview for
* @return state The synced NAV, impermanent loss, and fee accounting containing all mark-to-market accounting data
* @return claims The asset claims that the specified tranche has denominated in tranche-native units
* @return totalTrancheShares The total number of shares that exist in the specified tranche after the post-sync mint of its accrued shares: the protocol fee shares for the senior and junior tranches, plus the liquidity premium shares for the senior tranche (the liquidity provider tranche mints none)
*/
function previewSyncTrancheAccountingFor(TrancheType _trancheType)
external
view
returns (SyncedAccountingState memory state, AssetClaims memory claims, uint256 totalTrancheShares);
/**
* @notice Processes the in-kind deposit of a specified amount of the calling tranche's own assets into it
* @dev Only callable by one of the market's tranches: the deposited tranche is the calling tranche
* @dev Assumes that the funds are transferred to the kernel before the deposit call is made
* @dev Prices the shares at the tranche's pre-deposit effective NAV against the post-sync supply and mints them to the receiver
* @dev ST and JT deposits are enabled only in a PERPETUAL market state, the ST deposit granted that the market's coverage and liquidity requirements are satisfied post-deposit
* @dev An in-kind LPT deposit mints no new senior shares and only deepens liquidity, so it is enabled in every market state (including fixed-term) and enforces no requirements
* @dev A preview never returns: the flow unwinds every mutation by reverting with SIMULATION_RESULT carrying the ABI encoded return values
* @param _mode The dispatch mode: SIMULATE computes the operation and unwinds every mutation by reverting with its result, EXECUTE settles it
* @param _assets The amount of assets to deposit, denominated in the calling tranche's tranche units
* @param _caller The address that initiated the deposit on the tranche, screened with the receiver against the market's blacklist, the null address for a simulation's synthetic caller
* @param _receiver The address that receives the minted tranche shares
* @return trancheSharesMinted The number of tranche shares minted to the receiver for the deposit
*/
function inkindDeposit(DispatchMode _mode, TRANCHE_UNIT _assets, address _caller, address _receiver) external returns (uint256 trancheSharesMinted);
/**
* @notice Processes the in-kind redemption of a specified number of the calling tranche's shares
* @dev Only callable by one of the market's tranches: the redeemed tranche is the calling tranche
* @dev The function is expected to transfer the redeemed assets directly to the receiver, based on the redemption claims
* @dev Burns the owner's shares after scaling their claims against the pre-burn supply (a preview skips only the burn)
* @dev Redemptions are enabled only in a PERPETUAL market state, the JT redemption granted that the market's coverage requirement
* and the LPT redemption granted that the market's liquidity requirement are satisfied post-redemption
* @dev A preview never returns: the flow unwinds every mutation by reverting with SIMULATION_RESULT carrying the ABI encoded return values
* @param _mode The dispatch mode: SIMULATE computes the operation and unwinds every mutation by reverting with its result, EXECUTE settles it
* @param _shares The number of shares to redeem
* @param _caller The address that initiated the redemption on the tranche, screened with the owner and receiver against the market's blacklist, the null address for a simulation's synthetic caller that also skips the share burn
* @param _owner The address whose tranche shares are burned for the redemption, the null address for a simulation's synthetic owner
* @param _receiver The address that is receiving the assets
* @return userAssetClaims The distribution of assets that were transferred to the receiver on redemption
*/
function inkindRedeem(
DispatchMode _mode,
uint256 _shares,
address _caller,
address _owner,
address _receiver
)
external
returns (AssetClaims memory userAssetClaims);
/**
* @notice Atomically enters the liquidity provider tranche with the LPT assets' constituent assets: deposits collateral (minting senior
* shares), adds (senior shares + quote) into the liquidity venue to mint the LPT tranche assets, then deposits them into the LPT
* @dev Assumes the collateral and quote have been transferred to the kernel before this call (by the LPT tranche)
* @dev Enabled in a PERPETUAL market state, and in a fixed-term market only for a quote-only deposit (_collateralAssets == 0) that mints no senior shares, an ST-leg deposit reverts in a fixed-term market
* @dev The senior leg is gated by the market's coverage requirement, its liquidity requirement is satisfied by the add deploying the minted shares as depth
* @dev Prices the shares at the pre-deposit LPT effective NAV against the venue's settled post-add state and mints them to the receiver
* @dev A preview never returns: the flow unwinds every mutation by reverting with SIMULATION_RESULT carrying the ABI encoded return values
* @param _mode The dispatch mode: SIMULATE computes the operation and unwinds every mutation by reverting with its result, EXECUTE settles it
* @param _collateralAssets The amount of collateral to deposit for the senior leg, denominated in tranche units
* @param _quoteAssets The amount of quote asset to add as the second venue leg
* @param _minLPTAssetsOut The minimum LPT tranche assets the liquidity add must mint (slippage bound against an unfavorable venue state)
* @param _caller The address that initiated the deposit on the tranche, screened with the receiver against the market's blacklist, the null address for a simulation's synthetic caller
* @param _receiver The address that receives the minted tranche shares
* @return trancheSharesMinted The number of tranche shares minted to the receiver for the deposit
* @return lptAssetsOut The amount of LPT tranche assets minted and credited to the liquidity provider tranche
*/
function lptDepositMultiAsset(
DispatchMode _mode,
TRANCHE_UNIT _collateralAssets,
uint256 _quoteAssets,
TRANCHE_UNIT _minLPTAssetsOut,
address _caller,
address _receiver
)
external
returns (uint256 trancheSharesMinted, TRANCHE_UNIT lptAssetsOut);
/**
* @notice Atomically exits the liquidity provider tranche to the LPT assets' constituent assets: proportionally removes the LPT-asset slice,
* redeems the venue-held senior shares to collateral, and returns (collateral + quote) to the receiver
* @dev Burns the owner's LPT shares after scaling their claims against the pre-burn supply (a preview skips only the burn)
* @dev A preview never returns: the flow unwinds every mutation by reverting with SIMULATION_RESULT carrying the ABI encoded return values
* @param _mode The dispatch mode: SIMULATE computes the operation and unwinds every mutation by reverting with its result, EXECUTE settles it
* @param _lptShares The number of LPT shares being redeemed (used to size the proportional LPT-asset slice)
* @param _minSTSharesOut The minimum senior tranche shares the proportional removal must return (slippage bound)
* @param _minQuoteAssetsOut The minimum quote to return (slippage bound)
* @param _caller The address that initiated the redemption on the tranche, screened with the owner and receiver against the market's blacklist, the null address for a simulation's synthetic caller that also skips the share burn
* @param _owner The address whose LPT shares are burned for the redemption, the null address for a simulation's synthetic owner
* @param _receiver The address that receives the collateral and quote
* @return stClaims The ST redemption asset claims transferred to the receiver (its collateral asset leg)
* @return quoteAssets The quote assets returned to the receiver
*/
function lptRedeemMultiAsset(
DispatchMode _mode,
uint256 _lptShares,
uint256 _minSTSharesOut,
uint256 _minQuoteAssetsOut,
address _caller,
address _owner,
address _receiver
)
external
returns (AssetClaims memory stClaims, uint256 quoteAssets);
/**
* @notice Sets the new protocol fee recipient
* @dev Only callable by a designated admin
* @param _protocolFeeRecipient The address of the new protocol fee recipient
*/
function setProtocolFeeRecipient(address _protocolFeeRecipient) external;
/**
* @notice Sets the ST self-liquidation bonus remitted to redeeming ST LPs when liquidation coverageUtilization threshold has been breached
* @dev Only callable by a designated admin
* @param _stSelfLiquidationBonusWAD The ST self liquidation bonus, scaled to WAD precision
*/
function setSeniorTrancheSelfLiquidationBonus(uint64 _stSelfLiquidationBonusWAD) external;
/**
* @notice Sets the blacklist contract consulted on tranche balance updates for this market
* @dev Only callable by a designated admin
* @dev Setting the blacklist to the null address disables blacklist screening for this market
* @param _roycoBlacklist The address of the market's blacklist contract (or the null address to disable screening)
*/
function setRoycoBlacklist(address _roycoBlacklist) external;
/**
* @notice Sets the collateral asset oracle pricing 1 whole collateral asset in NAV units
* @param _collateralAssetOracle The new collateral asset oracle
* @param _syncBeforeUpdate Whether to sync the tranche accounting before updating the collateral asset oracle
*/
function setCollateralAssetOracle(address _collateralAssetOracle, bool _syncBeforeUpdate) external;
/**
* @notice Sets the L2 sequencer uptime feed and grace period used to gate price queries
* @param _sequencerUptimeFeed The new L2 sequencer uptime feed (set to the null address to disable the check)
* @param _gracePeriodSeconds The new grace period in seconds that must elapse after the L2 sequencer is restored before trusting the price
*/
function setSequencerUptimeFeed(address _sequencerUptimeFeed, uint48 _gracePeriodSeconds) external;
/// @notice Returns the collateral asset oracle pricing 1 whole collateral asset in NAV units
/// @return collateralAssetOracle The collateral asset oracle
function getCollateralAssetOracle() external view returns (address collateralAssetOracle);
/**
* @notice Pre-balance update hook for the tranche
* @dev This function should revert if the balance update is invalid
* @dev Should be called before every tranche share balance update
* @param _caller The address that is calling the balance update
* @param _from The address from which the balance is being updated
* @param _to The address to which the balance is being updated
* @param _value The amount of the balance being updated
*/
function preTrancheBalanceUpdateHook(address _caller, address _from, address _to, uint256 _value) external;
/**
* @notice Reverts if any of the specified accounts is blacklisted by the market's configured blacklist
* @dev No-op when no blacklist is configured (the null address disables screening)
* @dev Exposes the market's blacklist screening to periphery contracts whose value flows settle outside the tranche balance update hooks
* @param _accounts The addresses of the accounts to screen
*/
function enforceNotBlacklisted(address[] memory _accounts) external view;
/**
* @notice Reverts if the specified account is blacklisted on this market
* @dev No-op when no blacklist is configured (the null address disables screening)
* @param _account The address of the account to screen
*/
function enforceNotBlacklisted(address _account) external view;
/**
* @notice Retrieves the market's wiring in one carrier for external consumers (the entry point and other periphery)
* @dev The kernel's delegatecalled logic libraries read the wiring from the kernel's state directly, so this carrier never enters the operation hot paths
* @return immutables The market's tranche set, assets, and accountant
*/
function getImmutableState() external view returns (RoycoDayKernelImmutableState memory immutables);
/// @notice Retrieves the state of the Royco kernel
/// @return state The Royco kernel's state, including the protocol fee recipient and the kernel's controlled tranche and base assets
function getState() external view returns (RoycoDayKernelState memory state);
// =============================
// Liquidity Provider Tranche Venue Drivers
// =============================
/**
* @notice Adds a senior tranche share and quote asset position into the liquidity venue and returns the liquidity provider tranche assets minted
* @dev Only invoked via a self-call from the kernel's delegatecall logic libraries
* @param _mode The dispatch mode: SIMULATE computes the operation and unwinds every mutation by reverting with its result, EXECUTE settles it
* @param _seniorShares The exact amount of senior tranche shares to add into the liquidity venue
* @param _quoteAssets The exact amount of quote assets to add into the liquidity venue
* @param _minLPTAssetsOut The minimum liquidity provider tranche assets that must be minted, bounding the add's slippage
* @return lptAssets The liquidity provider tranche assets minted by the add
* @return lptAssetPrice The value of 1 whole LPT asset against the post-add venue state, produced only for a preview to cache for the operation (zero when settling)
*/
function addLiquidity(
DispatchMode _mode,
uint256 _seniorShares,
uint256 _quoteAssets,
TRANCHE_UNIT _minLPTAssetsOut
)
external
returns (TRANCHE_UNIT lptAssets, NAV_UNIT lptAssetPrice);
/**
* @notice Proportionally removes a slice of liquidity provider tranche assets from the liquidity venue into its senior tranche share and quote asset constituents
* @dev Only invoked via a self-call from the kernel's delegatecall logic libraries
* @param _mode The dispatch mode: SIMULATE computes the operation and unwinds every mutation by reverting with its result, EXECUTE settles it
* @param _lptAssets The exact liquidity provider tranche assets to burn
* @param _minSTSharesOut The minimum senior tranche shares that must be withdrawn, bounding the removal's slippage
* @param _minQuoteAssetsOut The minimum quote assets that must be withdrawn, bounding the removal's slippage
* @param _quoteAssetsReceiver The recipient of the withdrawn quote assets, the withdrawn senior shares are returned to the kernel for the combined senior unwind
* @return stShares The senior tranche shares withdrawn by the removal
* @return quoteAssets The quote assets withdrawn by the removal
* @return lptAssetPrice The value of 1 whole LPT asset against the post-remove venue state, produced only for a preview to cache for the operation (zero when settling)
*/
function removeLiquidity(
DispatchMode _mode,
TRANCHE_UNIT _lptAssets,
uint256 _minSTSharesOut,
uint256 _minQuoteAssetsOut,
address _quoteAssetsReceiver
)
external
returns (uint256 stShares, uint256 quoteAssets, NAV_UNIT lptAssetPrice);
/**
* @notice Attempts to reinvest the liquidity provider tranche's idle liquidity-premium senior shares into its market-making inventory
* @dev Tolerates reversions gracefully so it is non-blocking for the tranche operation that invokes it
* @param _stSharesToReinvest The amount of idle liquidity-premium senior shares to reinvest, or type(uint256).max to reinvest the entire idle balance
* @param _stShareRate The senior share rate the pile is valued at, the NAV backing one whole (WAD) senior share at the operation's settled state
*/
function attemptLiquidityPremiumReinvestment(uint256 _stSharesToReinvest, NAV_UNIT _stShareRate) external;
}
src/interfaces/IRoycoSeniorTranche.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { IRoycoVaultTranche } from "./IRoycoVaultTranche.sol";
/**
* @title IRoycoSeniorTranche
* @notice Interface for the senior tranche (ST): the standard share-token surface (inherited from IRoycoVaultTranche) plus
* the senior-specific liquidity premium share mint, by which the kernel routes senior yield to the liquidity provider tranche
* as newly minted senior shares
* @dev Only the senior tranche carries this mint: the liquidity premium is a reassignment of senior appreciation, so it is
* paid as senior shares
* The junior and liquidity provider tranches share the base IRoycoVaultTranche surface without it
*/
interface IRoycoSeniorTranche is IRoycoVaultTranche {
/**
* @notice Emitted when liquidity premium shares are minted to the kernel on behalf of the liquidity provider tranche
* @param holder The address that received the minted premium shares (the kernel, which custodies them for the liquidity provider tranche)
* @param mintedLiquidityPremiumShares The number of senior shares minted as the liquidity premium
* @param totalTrancheShares The total shares in the senior tranche after minting the liquidity premium shares
*/
event LiquidityPremiumSharesMinted(address indexed holder, uint256 mintedLiquidityPremiumShares, uint256 totalTrancheShares);
/**
* @notice Mints a kernel-computed number of liquidity premium shares to the kernel
* @dev Only callable by the kernel during accounting synchronization
* @dev The premium shares always land in the kernel, which custodies them for the liquidity provider tranche
* @dev The liquidity premium is senior yield routed to the liquidity provider tranche, minted as senior tranche shares held by
* the kernel on the LPT's behalf, this leaves the collateral NAV (and thus coverage) unchanged, so the mint is
* coverage-neutral and only reassigns senior appreciation to the LPT
* @dev Takes a precomputed share count, priced jointly with the ST protocol fee so neither carve-out dilutes the other
* @param _liquidityPremiumShares The precomputed number of liquidity premium shares to mint
* @return totalTrancheShares The total shares in the senior tranche after minting the liquidity premium shares
*/
function mintLiquidityPremiumShares(uint256 _liquidityPremiumShares) external returns (uint256 totalTrancheShares);
}
src/interfaces/IRoycoVaultTranche.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { IERC20Metadata } from "../../lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { AssetClaims, TrancheType } from "../libraries/Types.sol";
import { TRANCHE_UNIT } from "../libraries/Units.sol";
/**
* @title IRoycoVaultTranche
* @notice Interface for the Royco vault tranche contract that manages LP deposits and redemptions for a given tranche
* @dev Extends ERC20 with vault-like deposit/redeem functionality and protocol fee share minting
*/
interface IRoycoVaultTranche is IERC20Metadata {
/**
* @custom:field name - The name of the tranche share token (should be prefixed with "Royco-ST", "Royco-JT", or "Royco-LPT")
* @custom:field symbol - The symbol of the tranche share token (should be prefixed with "ST", "JT", or "LPT")
* @custom:field initialAuthority - The initial authority for the tranche
* @custom:field kernel - The kernel that handles the core market logic and accounting synchronization
* @custom:field asset - The underlying yield bearing asset of the tranche
*/
struct RoycoTrancheInitParams {
string name;
string symbol;
address initialAuthority;
address kernel;
address asset;
}
/**
* @notice Storage state for the Royco vault tranche
* @custom:storage-location erc7201:Royco.storage.RoycoVaultTrancheState
* @custom:field kernel - The kernel that handles the core market logic and accounting synchronization
* @custom:field asset - The address of the yield bearing asset of the tranche
*/
struct RoycoVaultTrancheState {
address kernel;
address asset;
}
/**
* @notice Emitted when a deposit is made into the tranche
* @param sender The address that initiated the deposit
* @param receiver The address that received the minted shares
* @param assets The amount of assets deposited, denominated in the tranche's base asset units
* @param shares The amount of shares minted to the receiver
*/
event Deposit(address indexed sender, address indexed receiver, TRANCHE_UNIT assets, uint256 shares);
/**
* @notice Emitted when a redemption is made from the tranche
* @param sender The address that initiated the redemption
* @param receiver The address that received the redeemed assets
* @param claims The asset claims received by the receiver, including claims on the collateral assets, LPT assets, ST shares, and their total NAV value
* @param shares The amount of shares redeemed
*/
event Redeem(address indexed sender, address indexed receiver, AssetClaims claims, uint256 shares);
/**
* @notice Emitted when protocol fee shares are minted to the fee recipient
* @param protocolFeeRecipient The address that received the minted protocol fee shares
* @param mintedProtocolFeeShares The number of protocol fee shares minted
* @param totalTrancheShares The total shares in the tranche after minting the protocol fee shares
*/
event ProtocolFeeSharesMinted(address indexed protocolFeeRecipient, uint256 mintedProtocolFeeShares, uint256 totalTrancheShares);
/// @notice Thrown when the caller of a permissioned function is not the tranche's configured kernel
error ONLY_KERNEL();
/// @notice Returns the address of the kernel that this tranche is associated with
/// @return kernel The address of the kernel responsible for executing deposits and redemptions for this tranche
function kernel() external view returns (address kernel);
/**
* @notice Deposits assets into the tranche and mints shares to the receiver
* @dev Transfers assets from the caller and mints shares to the receiver
* @param _assets The amount of assets to deposit, denominated in the tranche's base asset units
* @param _receiver The address that will receive the minted shares
* @return shares The number of shares minted to the receiver
*/
function deposit(TRANCHE_UNIT _assets, address _receiver) external returns (uint256 shares);
/**
* @notice Redeems shares from the tranche and transfers assets to the receiver
* @dev Burns shares from the owner and transfers the corresponding asset claims to the receiver
* @param _shares The number of shares to redeem
* @param _receiver The address that will receive the redeemed assets
* @param _owner The address that owns the shares being redeemed
* @return claims The asset claims transferred to the receiver, including claims on the collateral assets, LPT assets, ST shares, and their total NAV value
*/
function redeem(uint256 _shares, address _receiver, address _owner) external returns (AssetClaims memory claims);
/**
* @notice Mints a kernel-computed number of protocol fee shares to the specified fee recipient
* @dev Only callable by the kernel during accounting synchronization
* @dev Takes a precomputed share count rather than a NAV: the kernel prices every tranche's protocol fee shares (and the
* senior liquidity premium) against the post-carve-out NAV so neither dilutes the other and the tranche only mints the count
* @param _protocolFeeRecipient The address that will receive the minted protocol fee shares
* @param _protocolFeeShares The precomputed number of protocol fee shares to mint
* @return totalTrancheShares The total shares in the tranche after minting the protocol fee shares
*/
function mintProtocolFeeShares(address _protocolFeeRecipient, uint256 _protocolFeeShares) external returns (uint256 totalTrancheShares);
/**
* @notice Mints tranche shares to the specified account
* @dev Only callable by the kernel, which prices every mint inside a synchronized operation
* @dev Takes a raw share count: the caller (kernel) is responsible for computing a fair, non-diluting amount
* @param _to The account to mint the shares to
* @param _shares The number of shares to mint
*/
function kernelMint(address _to, uint256 _shares) external;
/**
* @notice Burns the specified number of tranche shares from the specified owner
* @dev Only callable by the kernel during a redemption flow, after the owner's claims have been scaled against the pre-burn supply
* @dev Takes a raw share count: redemption inputs are validated upstream by the tranche, so a derived zero share burn is a permitted no-op
* @param _from The address whose tranche shares are burned
* @param _shares The number of tranche shares to burn
*/
function kernelBurn(address _from, uint256 _shares) external;
/**
* @notice Previews the number of shares that would be minted for a given deposit amount
* @dev NON-VIEW: routes the deposit through its execute-and-revert simulation, which mutates no state net
* @dev The quote is produced by the actual kernel deposit path, so any revert the deposit would raise bubbles unchanged
* @param _assets The amount of assets to deposit, denominated in the tranche's base asset units
* @return shares The number of shares that would be minted for the specified deposit amount
*/
function previewDeposit(TRANCHE_UNIT _assets) external returns (uint256 shares);
/**
* @notice Previews the asset claims that would be received for a given redemption amount
* @dev NON-VIEW: routes the redemption through its execute-and-revert simulation, which mutates no state net
* @dev The quote is produced by the actual kernel redemption path, so any revert the redemption would raise bubbles unchanged
* @param _shares The number of shares to redeem
* @return claims The asset claims that would be received, including claims on the collateral assets, LPT assets, ST shares, and their total NAV value
*/
function previewRedeem(uint256 _shares) external returns (AssetClaims memory claims);
/**
* @notice Converts a specified number of shares to asset claims using the current exchange rate
* @dev Does not mutate any state
* @dev For the liquidity provider tranche this is the composability-facing exchange rate and is LPT-asset-only (the raw NAV,
* `stShares` always zero): the claimable idle liquidity-premium senior shares are excluded, so the quoted
* price is a conservative floor that cannot dip when a staged premium deploys into the pool
* Use `previewRedeem` for the accurate redemption quote, which includes the idle slice paid in-kind, the two
* coincide exactly when no premium is staged
* @param _shares The number of shares to convert
* @return claims The equivalent asset claims for the specified share amount, including claims on the collateral assets, LPT assets, ST shares, and their total NAV value
*/
function convertToAssets(uint256 _shares) external view returns (AssetClaims memory claims);
/**
* @notice Converts a specified amount of assets to shares using the current exchange rate
* @dev Does not mutate any state
* @dev For the liquidity provider tranche the exchange rate is LPT-asset-only (the raw NAV): the claimable idle
* liquidity-premium senior shares are excluded, so the quoted rate cannot dip when a staged premium deploys
* Use `previewDeposit` for the accurate deposit quote, which prices at the idle-inclusive effective NAV
* @param _assets The amount of assets to convert, denominated in the tranche's base asset units
* @return shares The equivalent number of shares for the specified asset amount
*/
function convertToShares(TRANCHE_UNIT _assets) external view returns (uint256 shares);
/**
* @notice Returns the maximum amount of assets that can be deposited by the specified receiver
* @dev May return zero if deposits are disabled due to market conditions (e.g., ST impermanent loss exists or coverage violated)
* @param _receiver The address that would receive the minted shares
* @return assets The maximum amount of assets that can be deposited, denominated in the tranche's base asset units
*/
function maxDeposit(address _receiver) external view returns (TRANCHE_UNIT assets);
/**
* @notice Returns the maximum number of shares that can be redeemed by the specified owner
* @dev May return zero if redemptions are disabled due to market conditions (e.g., fixed-term state for ST)
* @param _owner The address that owns the shares to be redeemed
* @return shares The maximum number of shares that can be redeemed
*/
function maxRedeem(address _owner) external view returns (uint256 shares);
/**
* @notice Returns the total effective assets held by this tranche
* @dev The effective assets include the claims on the collateral assets after accounting for coverage and yield sharing
* @return claims The total asset claims held by this tranche, including claims on the collateral assets, LPT assets, ST shares, and their total NAV value
*/
function totalAssets() external view returns (AssetClaims memory claims);
/// @notice Returns the address of the underlying base asset for this tranche
/// @return asset The address of the ERC20 token used as the base asset for deposits into this tranche
function asset() external view returns (address asset);
/// @notice Returns the tranche type indicating whether this is a senior, junior, or liquidity provider tranche
/// @return trancheType An enumerator indicating SENIOR, JUNIOR, or LIQUIDITY tranche type
function TRANCHE_TYPE() external view returns (TrancheType trancheType);
}
src/libraries/Constants.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { NAV_UNIT, TRANCHE_UNIT } from "./Units.sol";
/// @dev Constant for 0 NAV units
NAV_UNIT constant ZERO_NAV_UNITS = NAV_UNIT.wrap(0);
/// @dev Constant for the max value expressable as NAV units
NAV_UNIT constant MAX_NAV_UNITS = NAV_UNIT.wrap(type(uint256).max);
/// @dev Constant for 0 tranche units
TRANCHE_UNIT constant ZERO_TRANCHE_UNITS = TRANCHE_UNIT.wrap(0);
/// @dev Constant for the max value expressable as tranche units
TRANCHE_UNIT constant MAX_TRANCHE_UNITS = TRANCHE_UNIT.wrap(type(uint256).max);
/// @dev Constant for the WAD scaling factor
uint256 constant WAD = 1e18;
/// @dev Constant for the WAD scaling factor as an integer
int256 constant WAD_INT = int256(WAD);
/// @dev Constant for the number of decimals of precision a WAD denominated quantity has
uint256 constant WAD_DECIMALS = 18;
/// @dev The max protocol fee percentage on tranche yields, scaled to WAD precision
uint256 constant MAX_PROTOCOL_FEE_WAD = 1e18;
/**
* @dev The max fraction of the post-mint share supply a single mint may own, scaled to WAD precision
* @dev Fair pricing keeps every healthy mint far below this bound, it only binds on a deposit into a wiped tranche
* (supply alive, backing near zero) where pro-rata pricing would mint an effectively unbounded share count
* @dev Sits near 100% because a binding mint is essentially the whole tranche: the wiped incumbents keep only sub-dust
* paid out of the depositor's pocket, which is why the mint clamps instead of reverting, while the bound still
* caps the supply growth per wipe cycle far below the cap math's own overflow cliff
*/
uint256 constant MAX_MINT_DILUTION_WAD = (WAD - 1e6);
/// @dev Constant for the virtual shares injected into the tranche to prevent the first depositor from capturing the pre-existing backing
uint256 constant VIRTUAL_SHARES = 1;
/// @dev Constant for the virtual value backing the virtual shares, denominated in NAV units
NAV_UNIT constant VIRTUAL_VALUE = NAV_UNIT.wrap(1);
src/libraries/Types.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { NAV_UNIT, TRANCHE_UNIT } from "./Units.sol";
/**
* @title MarketState
* @notice Defines the operational state of a Royco market
* @custom:state PERPETUAL
* Normal operating state where market forces govern behavior, and the permanent state of a market configured with no fixed-term duration
* - The market is healthy (no losses over dust tolerance), severely undercollateralized (liquidation coverage utilization breached), or uncollateralized (no JT NAV remaining against a non-zero ST NAV)
* - All three tranches are liquid, subject to the coverage and liquidity requirements at all times, including while under or uncollateralized
* - Premiums and protocol fees accrue on ST yield, and adaptive curve YDMs adapt to this market's coverage and liquidity utilization
* @custom:state FIXED_TERM
* Temporary recovery state entered when JT covers an ST drawdown while coverage stays within the liquidation threshold
* - Entered when a non-dust JT impermanent loss is first incurred
* - ST deposits and redemptions blocked: stops ST withdrawing coverage from existing JT on arbitrary volatility
* - JT deposits and redemptions blocked: stops new JT diluting existing JT on arbitrary volatility
* - LPT redemptions blocked: keeps the LPT market making the ST when secondary liquidity is most valuable
* - No liquidity premium is paid and no protocol fees are taken, since there is no yield to distribute during recovery
* - Adaptive curve YDMs do not adapt, since utilization moves on underlying PNL rather than market forces during recovery
* - Transitions back to PERPETUAL when the JT impermanent loss clears or the term elapses, and is forced back on a liquidation breach or an uncollateralized market, clearing the JT impermanent loss
*/
enum MarketState {
PERPETUAL,
FIXED_TERM
}
/**
* @title DispatchMode
* @dev Defines how a dispatched operation runs
* @custom:type SIMULATE - Computes the operation's result under real execution semantics, then unwinds every mutation by reverting with the ABI encoded result
* @custom:type EXECUTE - Executes and settles the operation
*/
enum DispatchMode {
SIMULATE,
EXECUTE
}
/**
* @title AssetClaims
* @dev A struct representing claims on collateral assets, liquidity provider tranche assets, senior tranche shares, and NAV
* @custom:field collateralAssets - The claim on the coinvested collateral assets denominated in tranche units (only applicable for the ST and JT)
* @custom:field lptAssets - The claim on liquidity provider tranche assets denominated in LPT's tranche units (only applicable for the LPT)
* @custom:field stShares - The claim on senior tranche shares (only applicable for the LPT)
* @custom:field nav - The net asset value of these claims in NAV units
*/
struct AssetClaims {
// ST and JT claims
TRANCHE_UNIT collateralAssets;
// LPT claims
TRANCHE_UNIT lptAssets;
uint256 stShares;
// Total net asset value of the claims
NAV_UNIT nav;
}
/**
* @title SyncedAccountingState
* @dev Contains all current mark-to-market NAV accounting data for the market's tranches
* @custom:field marketState - The current state of the Royco market (perpetual or fixed term)
* @custom:field collateralNAV - The pure value of the coinvested collateral backing the senior and junior tranches, always equal to (stEffectiveNAV + jtEffectiveNAV)
* @custom:field lptRawNAV - The liquidity provider tranche's current raw NAV: the mark-to-market value of its market making inventory
* @custom:field stEffectiveNAV - Senior tranche effective NAV: its claim on the collateral, includes applied coverage, its share of ST yield, and uncovered losses
* @custom:field jtEffectiveNAV - Junior tranche effective NAV: its claim on the collateral, includes provided coverage, JT yield, its share of ST yield, and JT losses
* @custom:field jtImpermanentLoss - The junior tranche's impermanent loss: JT's recoverable drawdown, deepened by JT losses and provided coverage, repaid by JT's first claim on appreciation/recovery
* @custom:field lptLiquidityPremium - The liquidity premium accrued to the liquidity provider tranche on this sync: LPT's share of senior yield, minted as senior tranche shares to LPT (coverage-neutral)
* @custom:field stProtocolFee - Protocol fee taken on ST yield on this sync
* @custom:field jtProtocolFee - Protocol fee taken on JT yield on this sync
* @custom:field lptProtocolFee - Protocol fee taken on the liquidity premium (LPT yield share) on this sync
* @custom:field coverageUtilizationWAD - The current coverageUtilization of the market, scaled to WAD precision
* @custom:field liquidityUtilizationWAD - The current liquidityUtilization of the market, scaled to WAD precision
* @custom:field fixedTermEndTimestamp - The timestamp at which the fixed term ends, set to 0 if the market is not in a fixed term state
* @custom:field minCoverageWAD - The coverage percentage that the senior tranche is expected to be protected by, scaled to WAD precision
* @custom:field coverageLiquidationUtilizationWAD - The liquidation coverageUtilization threshold for this market, scaled to WAD precision
* @custom:field minLiquidityWAD - The percentage of the senior tranche NAV that must be in the liquidity provider tranche's market making inventory, scaled to WAD precision
*/
struct SyncedAccountingState {
// The market's current operating state (PERPETUAL or FIXED_TERM)
MarketState marketState;
// The market's marked-to-market NAVs, JT impermanent loss, LPT liquidity premium, and fees
NAV_UNIT collateralNAV;
NAV_UNIT lptRawNAV;
NAV_UNIT stEffectiveNAV;
NAV_UNIT jtEffectiveNAV;
NAV_UNIT jtImpermanentLoss;
NAV_UNIT lptLiquidityPremium;
NAV_UNIT stProtocolFee;
NAV_UNIT jtProtocolFee;
NAV_UNIT lptProtocolFee;
// The market's derived state metrics
uint256 coverageUtilizationWAD;
uint256 liquidityUtilizationWAD;
uint32 fixedTermEndTimestamp;
// The market's coverage configuration
uint256 minCoverageWAD;
uint256 coverageLiquidationUtilizationWAD;
// The market's liquidity configuration
uint256 minLiquidityWAD;
}
/**
* @title Operation
* @dev Defines the type of operation being executed by the user
* @custom:type ST_DEPOSIT - A senior tranche deposit that increases ST's effective NAV
* @custom:type ST_REDEMPTION - A senior tranche redemption that decreases ST's effective NAV
* @custom:type JT_DEPOSIT - A junior tranche deposit that increases JT's effective NAV
* @custom:type JT_REDEMPTION - A junior tranche redemption that decreases JT's effective NAV
* @custom:type LPT_DEPOSIT - An in-kind liquidity provider tranche deposit that only adds market-making inventory
* @custom:type LPT_REDEMPTION - An in-kind liquidity provider tranche redemption that only removes market-making inventory and idle premium shares
*/
enum Operation {
ST_DEPOSIT,
ST_REDEMPTION,
JT_DEPOSIT,
JT_REDEMPTION,
LPT_DEPOSIT,
LPT_REDEMPTION
}
/**
* @title TrancheType
* @dev Defines the types of Royco tranches deployed per market
* @custom:type SENIOR - The identifier for the senior tranche (protected capital)
* @custom:type JUNIOR - The identifier for the junior tranche (first-loss capital)
* @custom:type LIQUIDITY_PROVIDER - The identifier for the liquidity provider tranche (senior's market-making capital)
*/
enum TrancheType {
SENIOR,
JUNIOR,
LIQUIDITY_PROVIDER
}
/**
* @notice Maps the specified tranche to its deposit operation
* @param _trancheType The tranche to return the deposit operation for
* @return The deposit operation committed by the specified tranche's in-kind deposit
*/
function toDepositOperation(TrancheType _trancheType) pure returns (Operation) {
if (_trancheType == TrancheType.SENIOR) return Operation.ST_DEPOSIT;
else if (_trancheType == TrancheType.JUNIOR) return Operation.JT_DEPOSIT;
else return Operation.LPT_DEPOSIT;
}
/**
* @notice Maps the specified tranche to its redemption operation
* @param _trancheType The tranche to return the redemption operation for
* @return The redemption operation committed by the specified tranche's in-kind redemption
*/
function toRedemptionOperation(TrancheType _trancheType) pure returns (Operation) {
if (_trancheType == TrancheType.SENIOR) return Operation.ST_REDEMPTION;
else if (_trancheType == TrancheType.JUNIOR) return Operation.JT_REDEMPTION;
else return Operation.LPT_REDEMPTION;
}
src/libraries/Units.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { Math } from "../../lib/openzeppelin-contracts/contracts/utils/math/Math.sol";
/**
* @notice Common unit of account for Royco NAV values (e.g., USD, BTC) used consistently across a market's tranches
* @dev `NAV_UNIT` must be expressed in the same underlying unit and precision for both ST and JT within a market
* @dev `NAV_UNIT` always has WAD decimals (18) of precision
*/
type NAV_UNIT is uint256;
/// @notice Unit for tranche asset amounts (native token units for a specific tranche)
/// @dev `TRANCHE_UNIT` always has the same precision as the asset it represents (base asset of the tranche)
type TRANCHE_UNIT is uint256;
/**
* @title RoycoUnitsMath
* @notice Typed math helpers for Royco units (NAV_UNIT and TRANCHE_UNIT)
* @dev Wraps OpenZeppelin Math helpers and preserves unit typing on return values
*/
library RoycoUnitsMath {
/// @notice Returns the minimum of two NAV-denominated quantities
function min(NAV_UNIT _a, NAV_UNIT _b) internal pure returns (NAV_UNIT) {
return toNAVUnits(Math.min(toUint256(_a), toUint256(_b)));
}
/// @notice Returns the signed delta `_a - _b` for NAV-denominated quantities
function computeNAVDelta(NAV_UNIT _a, NAV_UNIT _b) internal pure returns (int256) {
return (toInt256(_a) - toInt256(_b));
}
/// @notice Returns `max(_a - _b, 0)` for NAV-denominated quantities
function saturatingSub(NAV_UNIT _a, NAV_UNIT _b) internal pure returns (NAV_UNIT) {
return toNAVUnits(Math.saturatingSub(toUint256(_a), toUint256(_b)));
}
/// @notice Returns `(_a * _b) / _c` for NAV-denominated quantities with explicit rounding
function mulDiv(NAV_UNIT _a, NAV_UNIT _b, NAV_UNIT _c, Math.Rounding _rounding) internal pure returns (NAV_UNIT) {
return toNAVUnits(Math.mulDiv(toUint256(_a), toUint256(_b), toUint256(_c), _rounding));
}
/// @notice Returns `(_a * _b) / _c` where `_a` is NAV-denominated and `_b`/`_c` are scalars, with explicit rounding
function mulDiv(NAV_UNIT _a, uint256 _b, uint256 _c, Math.Rounding _rounding) internal pure returns (NAV_UNIT) {
return toNAVUnits(Math.mulDiv(toUint256(_a), _b, _c, _rounding));
}
/// @notice Returns `(_a * _b) / _c` where `_a`/`_c` are NAV-denominated and `_b` is a scalar, with explicit rounding
function mulDiv(NAV_UNIT _a, uint256 _b, NAV_UNIT _c, Math.Rounding _rounding) internal pure returns (uint256) {
return Math.mulDiv(toUint256(_a), _b, toUint256(_c), _rounding);
}
/// @notice Returns `(_a * _b) / _c` where `_a` is NAV-denominated and `_b`/`_c` are tranche-denominated, with explicit rounding
function mulDiv(NAV_UNIT _a, TRANCHE_UNIT _b, TRANCHE_UNIT _c, Math.Rounding _rounding) internal pure returns (NAV_UNIT) {
return toNAVUnits(Math.mulDiv(toUint256(_a), toUint256(_b), toUint256(_c), _rounding));
}
/// @notice Returns `(_a * _b) / _c` where `_a` is tranche-denominated and `_b`/`_c` are NAV-denominated, with explicit rounding
function mulDiv(TRANCHE_UNIT _a, NAV_UNIT _b, NAV_UNIT _c, Math.Rounding _rounding) internal pure returns (TRANCHE_UNIT) {
return toTrancheUnits(Math.mulDiv(toUint256(_a), toUint256(_b), toUint256(_c), _rounding));
}
/// @notice Returns `(_a * _b) / _c` where `_a`/`_c` are tranche-denominated and `_b` is NAV-denominated, with explicit rounding
function mulDiv(TRANCHE_UNIT _a, NAV_UNIT _b, TRANCHE_UNIT _c, Math.Rounding _rounding) internal pure returns (NAV_UNIT) {
return toNAVUnits(Math.mulDiv(toUint256(_a), toUint256(_b), toUint256(_c), _rounding));
}
/// @notice Returns `(_a * _b) / _c` where `_a`/`_c` are NAV-denominated and `_b` is tranche-denominated, with explicit rounding
function mulDiv(NAV_UNIT _a, TRANCHE_UNIT _b, NAV_UNIT _c, Math.Rounding _rounding) internal pure returns (TRANCHE_UNIT) {
return toTrancheUnits(Math.mulDiv(toUint256(_a), toUint256(_b), toUint256(_c), _rounding));
}
/// @notice Returns `(_a * _b) / _c` where `_a` is tranche-denominated and `_b`/`_c` are scalars, with explicit rounding
function mulDiv(TRANCHE_UNIT _a, uint256 _b, uint256 _c, Math.Rounding _rounding) internal pure returns (TRANCHE_UNIT) {
return toTrancheUnits(Math.mulDiv(toUint256(_a), _b, _c, _rounding));
}
/// @notice Returns `(_a * _b) / _c` where `_a` is a scalar and `_b`/`_c` are NAV-denominated, with explicit rounding
function mulDiv(uint256 _a, NAV_UNIT _b, NAV_UNIT _c, Math.Rounding _rounding) internal pure returns (uint256) {
return Math.mulDiv(_a, toUint256(_b), toUint256(_c), _rounding);
}
/// @notice Returns `(_a * _b) / _c` where `_a` is a scalar and `_b`/`_c` are tranche-denominated, with explicit rounding
function mulDiv(uint256 _a, TRANCHE_UNIT _b, TRANCHE_UNIT _c, Math.Rounding _rounding) internal pure returns (uint256) {
return Math.mulDiv(_a, toUint256(_b), toUint256(_c), _rounding);
}
}
/**
* -----------------------------------------------------------------------
* Global NAV_UNIT Helpers
* -----------------------------------------------------------------------
*/
/// @notice Wraps a raw `uint256` amount as a `NAV_UNIT`
function toNAVUnits(uint256 _assets) pure returns (NAV_UNIT) {
return NAV_UNIT.wrap(_assets);
}
/// @notice Thrown when a signed NAV amount that must be non-negative is negative, or a `NAV_UNIT` exceeds the int256 range
error ASSETS_MUST_BE_NON_NEGATIVE();
/// @notice Wraps a signed `int256` amount as a `NAV_UNIT`, reverting if negative
function toNAVUnits(int256 _assets) pure returns (NAV_UNIT) {
require(_assets >= 0, ASSETS_MUST_BE_NON_NEGATIVE());
// forge-lint: disable-next-line(unsafe-typecast)
return NAV_UNIT.wrap(uint256(_assets));
}
/// @notice Unwraps a `NAV_UNIT` to its raw `uint256` value
function toUint256(NAV_UNIT _units) pure returns (uint256) {
return NAV_UNIT.unwrap(_units);
}
/// @notice Unwraps a `NAV_UNIT` to a signed `int256`, reverting if it exceeds the int256 range
function toInt256(NAV_UNIT _units) pure returns (int256 assets) {
// Ensure there was no overflow in the cast
require((assets = int256(NAV_UNIT.unwrap(_units))) >= 0, ASSETS_MUST_BE_NON_NEGATIVE());
}
/// @notice Adds two NAV-denominated quantities (bound to the `+` operator)
function addNAVUnits(NAV_UNIT _a, NAV_UNIT _b) pure returns (NAV_UNIT) {
return NAV_UNIT.wrap(NAV_UNIT.unwrap(_a) + NAV_UNIT.unwrap(_b));
}
/// @notice Subtracts one NAV-denominated quantity from another (bound to the `-` operator)
function subNAVUnits(NAV_UNIT _a, NAV_UNIT _b) pure returns (NAV_UNIT) {
return NAV_UNIT.wrap(NAV_UNIT.unwrap(_a) - NAV_UNIT.unwrap(_b));
}
/// @notice Multiplies two NAV-denominated quantities as raw values (bound to the `*` operator)
function mulNAVUnits(NAV_UNIT _a, NAV_UNIT _b) pure returns (NAV_UNIT) {
return NAV_UNIT.wrap(NAV_UNIT.unwrap(_a) * NAV_UNIT.unwrap(_b));
}
/// @notice Divides one NAV-denominated quantity by another as raw values (bound to the `/` operator)
function divNAVUnits(NAV_UNIT _a, NAV_UNIT _b) pure returns (NAV_UNIT) {
return NAV_UNIT.wrap(NAV_UNIT.unwrap(_a) / NAV_UNIT.unwrap(_b));
}
/// @notice Returns whether `_a` is strictly less than `_b` (bound to the `<` operator)
function lessThanNAVUnits(NAV_UNIT _a, NAV_UNIT _b) pure returns (bool) {
return NAV_UNIT.unwrap(_a) < NAV_UNIT.unwrap(_b);
}
/// @notice Returns whether `_a` is less than or equal to `_b` (bound to the `<=` operator)
function lessThanOrEqualToNAVUnits(NAV_UNIT _a, NAV_UNIT _b) pure returns (bool) {
return NAV_UNIT.unwrap(_a) <= NAV_UNIT.unwrap(_b);
}
/// @notice Returns whether `_a` is strictly greater than `_b` (bound to the `>` operator)
function greaterThanNAVUnits(NAV_UNIT _a, NAV_UNIT _b) pure returns (bool) {
return NAV_UNIT.unwrap(_a) > NAV_UNIT.unwrap(_b);
}
/// @notice Returns whether `_a` is greater than or equal to `_b` (bound to the `>=` operator)
function greaterThanOrEqualToNAVUnits(NAV_UNIT _a, NAV_UNIT _b) pure returns (bool) {
return NAV_UNIT.unwrap(_a) >= NAV_UNIT.unwrap(_b);
}
/// @notice Returns whether `_a` equals `_b` (bound to the `==` operator)
function equalsNAVUnits(NAV_UNIT _a, NAV_UNIT _b) pure returns (bool) {
return NAV_UNIT.unwrap(_a) == NAV_UNIT.unwrap(_b);
}
/// @notice Returns whether `_a` does not equal `_b` (bound to the `!=` operator)
function notEqualsNAVUnits(NAV_UNIT _a, NAV_UNIT _b) pure returns (bool) {
return NAV_UNIT.unwrap(_a) != NAV_UNIT.unwrap(_b);
}
/// @dev Binds the arithmetic and comparison operators above to `NAV_UNIT` globally
using {
addNAVUnits as +,
subNAVUnits as -,
mulNAVUnits as *,
divNAVUnits as /,
lessThanNAVUnits as <,
lessThanOrEqualToNAVUnits as <=,
greaterThanNAVUnits as >,
greaterThanOrEqualToNAVUnits as >=,
equalsNAVUnits as ==,
notEqualsNAVUnits as !=
} for NAV_UNIT global;
/**
* -----------------------------------------------------------------------
* Global TRANCHE_UNIT Helpers
* -----------------------------------------------------------------------
*/
/// @notice Wraps a raw `uint256` amount as a `TRANCHE_UNIT`
function toTrancheUnits(uint256 _assets) pure returns (TRANCHE_UNIT) {
return TRANCHE_UNIT.wrap(_assets);
}
/// @notice Unwraps a `TRANCHE_UNIT` to its raw `uint256` value
function toUint256(TRANCHE_UNIT _units) pure returns (uint256) {
return TRANCHE_UNIT.unwrap(_units);
}
/// @notice Adds two tranche-denominated quantities (bound to the `+` operator)
function addTrancheUnits(TRANCHE_UNIT _a, TRANCHE_UNIT _b) pure returns (TRANCHE_UNIT) {
return TRANCHE_UNIT.wrap(TRANCHE_UNIT.unwrap(_a) + TRANCHE_UNIT.unwrap(_b));
}
/// @notice Subtracts one tranche-denominated quantity from another (bound to the `-` operator)
function subTrancheUnits(TRANCHE_UNIT _a, TRANCHE_UNIT _b) pure returns (TRANCHE_UNIT) {
return TRANCHE_UNIT.wrap(TRANCHE_UNIT.unwrap(_a) - TRANCHE_UNIT.unwrap(_b));
}
/// @notice Multiplies two tranche-denominated quantities as raw values (bound to the `*` operator)
function mulTrancheUnits(TRANCHE_UNIT _a, TRANCHE_UNIT _b) pure returns (TRANCHE_UNIT) {
return TRANCHE_UNIT.wrap(TRANCHE_UNIT.unwrap(_a) * TRANCHE_UNIT.unwrap(_b));
}
/// @notice Divides one tranche-denominated quantity by another as raw values (bound to the `/` operator)
function divTrancheUnits(TRANCHE_UNIT _a, TRANCHE_UNIT _b) pure returns (TRANCHE_UNIT) {
return TRANCHE_UNIT.wrap(TRANCHE_UNIT.unwrap(_a) / TRANCHE_UNIT.unwrap(_b));
}
/// @notice Returns whether `_a` is strictly less than `_b` (bound to the `<` operator)
function lessThanTrancheUnits(TRANCHE_UNIT _a, TRANCHE_UNIT _b) pure returns (bool) {
return TRANCHE_UNIT.unwrap(_a) < TRANCHE_UNIT.unwrap(_b);
}
/// @notice Returns whether `_a` is less than or equal to `_b` (bound to the `<=` operator)
function lessThanOrEqualToTrancheUnits(TRANCHE_UNIT _a, TRANCHE_UNIT _b) pure returns (bool) {
return TRANCHE_UNIT.unwrap(_a) <= TRANCHE_UNIT.unwrap(_b);
}
/// @notice Returns whether `_a` is strictly greater than `_b` (bound to the `>` operator)
function greaterThanTrancheUnits(TRANCHE_UNIT _a, TRANCHE_UNIT _b) pure returns (bool) {
return TRANCHE_UNIT.unwrap(_a) > TRANCHE_UNIT.unwrap(_b);
}
/// @notice Returns whether `_a` is greater than or equal to `_b` (bound to the `>=` operator)
function greaterThanOrEqualToTrancheUnits(TRANCHE_UNIT _a, TRANCHE_UNIT _b) pure returns (bool) {
return TRANCHE_UNIT.unwrap(_a) >= TRANCHE_UNIT.unwrap(_b);
}
/// @notice Returns whether `_a` equals `_b` (bound to the `==` operator)
function equalsTrancheUnits(TRANCHE_UNIT _a, TRANCHE_UNIT _b) pure returns (bool) {
return TRANCHE_UNIT.unwrap(_a) == TRANCHE_UNIT.unwrap(_b);
}
/// @notice Returns whether `_a` does not equal `_b` (bound to the `!=` operator)
function notEqualsTrancheUnits(TRANCHE_UNIT _a, TRANCHE_UNIT _b) pure returns (bool) {
return TRANCHE_UNIT.unwrap(_a) != TRANCHE_UNIT.unwrap(_b);
}
/// @dev Binds the arithmetic and comparison operators above to `TRANCHE_UNIT` globally
using {
addTrancheUnits as +,
subTrancheUnits as -,
mulTrancheUnits as *,
divTrancheUnits as /,
lessThanTrancheUnits as <,
lessThanOrEqualToTrancheUnits as <=,
greaterThanTrancheUnits as >,
greaterThanOrEqualToTrancheUnits as >=,
equalsTrancheUnits as ==,
notEqualsTrancheUnits as !=
} for TRANCHE_UNIT global;
src/libraries/logic/AssetLedgerLogic.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { IERC20 } from "../../../lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "../../../lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import { IRoycoDayKernel } from "../../interfaces/IRoycoDayKernel.sol";
import { IRoycoVaultTranche } from "../../interfaces/IRoycoVaultTranche.sol";
import { VIRTUAL_SHARES, VIRTUAL_VALUE, ZERO_NAV_UNITS, ZERO_TRANCHE_UNITS } from "../Constants.sol";
import { AssetClaims, SyncedAccountingState, TrancheType } from "../Types.sol";
import { Math, NAV_UNIT, RoycoUnitsMath, TRANCHE_UNIT, toUint256 } from "../Units.sol";
import { ValuationLogic } from "./ValuationLogic.sol";
/**
* @title AssetLedgerLogic
* @author Shivaansh Kapoor, Ankur Dubey, Tomer Ganor
* @notice Tranche asset-ledger accounting for a Royco market: claim derivation, proportional scaling, ledger credits and debits, and remittance
*/
library AssetLedgerLogic {
using SafeERC20 for IERC20;
using RoycoUnitsMath for NAV_UNIT;
using RoycoUnitsMath for TRANCHE_UNIT;
using RoycoUnitsMath for uint256;
using Math for uint256;
/**
* @notice Resolves the specified tranche's contract address from the kernel's state
* @param $ The storage state of the Royco Kernel that is delegatecalling into this function
* @param _trancheType An enumerator indicating which tranche's address to resolve
* @return The specified tranche's contract address
*/
function _getTrancheAddress(IRoycoDayKernel.RoycoDayKernelState storage $, TrancheType _trancheType) internal view returns (address) {
if (_trancheType == TrancheType.SENIOR) return $.seniorTranche;
else if (_trancheType == TrancheType.JUNIOR) return $.juniorTranche;
else return $.liquidityProviderTranche;
}
/**
* @notice Derives the cumulative asset claims that the specified tranche is entitled to
* @param $ The storage state of the Royco Kernel that is delegatecalling into this function
* @param _trancheType An enumerator indicating which tranche to return cumulative claims for
* @param _state The synced NAV, impermanent loss, and fee accounting containing all mark to market accounting data
* @return claims The cumulative asset claims that the specified tranche is entitled to
*/
function _deriveTrancheAssetClaims(
IRoycoDayKernel.RoycoDayKernelState storage $,
TrancheType _trancheType,
SyncedAccountingState memory _state
)
internal
view
returns (AssetClaims memory claims)
{
if (_trancheType == TrancheType.LIQUIDITY_PROVIDER) {
if (_state.lptRawNAV != ZERO_NAV_UNITS) claims.lptAssets = IRoycoDayKernel(address(this)).convertValueToLPTAssets(_state.lptRawNAV);
claims.stShares = $.lptOwnedSeniorTrancheShares;
claims.nav = ValuationLogic._getLiquidityProviderTrancheEffectiveNAV(
$, _state.stEffectiveNAV, IRoycoVaultTranche($.seniorTranche).totalSupply(), claims.stShares
);
} else {
// A tranche's claim is its effective NAV, granted in the coinvested collateral asset
claims.nav = (_trancheType == TrancheType.SENIOR ? _state.stEffectiveNAV : _state.jtEffectiveNAV);
if (claims.nav != ZERO_NAV_UNITS) claims.collateralAssets = IRoycoDayKernel(address(this)).convertValueToCollateralAssets(claims.nav);
}
}
/**
* @notice Credits deposited assets to the specified tranche's ledger
* @param $ The storage state of the Royco Kernel that is delegatecalling into this function
* @param _trancheType An enumerator indicating which tranche's ledger to credit
* @param _assets The amount of assets to credit, denominated in the tranche's tranche units
*/
function _creditAssets(IRoycoDayKernel.RoycoDayKernelState storage $, TrancheType _trancheType, TRANCHE_UNIT _assets) internal {
// The senior and junior tranches share the coinvested collateral ledger, the liquidity provider tranche holds the LPT asset ledger
if (_trancheType == TrancheType.LIQUIDITY_PROVIDER) $.totalLPTAssets = $.totalLPTAssets + _assets;
else $.totalCollateralAssets = $.totalCollateralAssets + _assets;
}
/**
* @notice Debits the specified asset claims from the kernel's tranche ledgers
* @param $ The storage state of the Royco Kernel that is delegatecalling into this function
* @param _claims The collateral assets, LPT assets, and ST shares to debit from the ledgers
*/
function _debitAssets(IRoycoDayKernel.RoycoDayKernelState storage $, AssetClaims memory _claims) internal {
// Debit the collateral assets, LPT assets, and/or ST shares being withdrawn if non-zero
if (_claims.collateralAssets != ZERO_TRANCHE_UNITS) $.totalCollateralAssets = $.totalCollateralAssets - _claims.collateralAssets;
if (_claims.lptAssets != ZERO_TRANCHE_UNITS) $.totalLPTAssets = $.totalLPTAssets - _claims.lptAssets;
if (_claims.stShares != 0) $.lptOwnedSeniorTrancheShares -= _claims.stShares;
}
/**
* @notice Remits the specified asset claims to the receiver via direct transfers
* @dev Holds no accounting effects, callers debit the claims from their ledgers first so the transfers can run last (CEI)
* @param $ The storage state of the Royco Kernel that is delegatecalling into this function
* @param _claims The collateral assets, LPT assets, and ST shares to transfer to the specified receiver
* @param _receiver The receiver of the asset claims
*/
function _remitClaims(IRoycoDayKernel.RoycoDayKernelState storage $, AssetClaims memory _claims, address _receiver) internal {
// Preemptively return if this is a self-remittance
if (_receiver == address(this)) return;
// Transfer the collateral assets being remitted to the receiver
if (_claims.collateralAssets != ZERO_TRANCHE_UNITS) IERC20($.collateralAsset).safeTransfer(_receiver, toUint256(_claims.collateralAssets));
// Transfer the LPT assets being remitted to the receiver
if (_claims.lptAssets != ZERO_TRANCHE_UNITS) IERC20($.lptAsset).safeTransfer(_receiver, toUint256(_claims.lptAssets));
// Transfer the senior tranche shares being remitted to the receiver
if (_claims.stShares != 0) IERC20($.seniorTranche).safeTransfer(_receiver, _claims.stShares);
}
/**
* @notice Remits the specified asset claims to the receiver via direct transfers, resolving the claim assets from the kernel's immutable-state carrier
* @dev The periphery variant of `_remitClaims`: a contract outside the kernel holds no kernel storage pointer, so it remits from the carrier `getImmutableState` returns
* @param _immutables The kernel's immutable-state carrier resolving the claim assets
* @param _claims The collateral assets, LPT assets, and ST shares to transfer to the specified receiver
* @param _receiver The receiver of the asset claims
*/
function _remitClaims(IRoycoDayKernel.RoycoDayKernelImmutableState memory _immutables, AssetClaims memory _claims, address _receiver) internal {
// Preemptively return if this is a self-remittance
if (_receiver == address(this)) return;
// Transfer the collateral assets being remitted to the receiver
if (_claims.collateralAssets != ZERO_TRANCHE_UNITS) IERC20(_immutables.collateralAsset).safeTransfer(_receiver, toUint256(_claims.collateralAssets));
// Transfer the LPT assets being remitted to the receiver
if (_claims.lptAssets != ZERO_TRANCHE_UNITS) IERC20(_immutables.lptAsset).safeTransfer(_receiver, toUint256(_claims.lptAssets));
// Transfer the senior tranche shares being remitted to the receiver
if (_claims.stShares != 0) IERC20(_immutables.seniorTranche).safeTransfer(_receiver, _claims.stShares);
}
/**
* @notice Scales a tranche's asset claims (collateral assets, LPT assets, ST shares, and NAV) by a given shares assuming total shares in a vault
* @param _claims The asset claims of the tranche
* @param _shares The number of shares to scale the claims by
* @param _totalTrancheShares The total number of shares that exist in the tranche
* @param _includeVirtualShares Whether to use virtual shares for the scaling
* @return scaledClaims The scaled asset claims of the tranche
*/
function _scaleAssetClaims(
AssetClaims memory _claims,
uint256 _shares,
uint256 _totalTrancheShares,
bool _includeVirtualShares
)
internal
pure
returns (AssetClaims memory scaledClaims)
{
// If the total tranche shares is zero, it has no claims on the assets, so return zero claims
if (_totalTrancheShares == 0) return scaledClaims;
// Scale the claims by the redeemer's fraction of the EFFECTIVE supply
uint256 effectiveTrancheShares = _totalTrancheShares + (_includeVirtualShares ? VIRTUAL_SHARES : 0);
NAV_UNIT effectiveTrancheValue = _claims.nav + (_includeVirtualShares ? VIRTUAL_VALUE : ZERO_NAV_UNITS);
scaledClaims.collateralAssets = _claims.collateralAssets.mulDiv(_shares, effectiveTrancheShares, Math.Rounding.Floor);
scaledClaims.lptAssets = _claims.lptAssets.mulDiv(_shares, effectiveTrancheShares, Math.Rounding.Floor);
scaledClaims.stShares = _claims.stShares.mulDiv(_shares, effectiveTrancheShares, Math.Rounding.Floor);
scaledClaims.nav = effectiveTrancheValue.mulDiv(_shares, effectiveTrancheShares, Math.Rounding.Floor);
}
}
src/libraries/logic/DispatchLogic.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { DispatchMode } from "../Types.sol";
/**
* @title DispatchLogic
* @author Shivaansh Kapoor, Ankur Dubey, Tomer Ganor
* @notice Dispatches operations for execution or simulation: an execution persists and returns its result, a simulation
* runs the same operation and unwinds every state change by reverting with SIMULATION_RESULT
* @dev Either mode delivers the operation's result byte for byte, so callers decode without mode awareness:
* _dispatch serves operations that return bytes (the result keeps its offset and length words), _dispatchAndUnwrap serves
* operations that return value types (the result arrives bare)
*/
library DispatchLogic {
/// @notice Thrown when a simulated operation returns instead of unwinding via its result-carrying revert
error SIMULATION_CANNOT_MUTATE_STATE();
/// @notice The result-carrying revert that unwinds a simulated operation
/// @param result The simulated operation's ABI encoded result
error SIMULATION_RESULT(bytes result);
/**
* @notice Dispatches an operation that returns bytes for execution or simulation
* @dev Should be used by any call site whose target function is declared to return bytes: their result is prefixed with its own offset and length words
* @param _target The address the operation is dispatched into
* @param _mode The dispatch mode: SIMULATE computes the operation and unwinds every mutation by reverting with its result, EXECUTE settles it
* @param _callData The ABI encoded call to the operation
* @return result The operation's ABI encoded return bytes
*/
function _dispatch(address _target, DispatchMode _mode, bytes memory _callData) internal returns (bytes memory result) {
return ((_mode == DispatchMode.SIMULATE) ? _simulate(_target, _callData, false) : _execute(_target, _callData));
}
/**
* @notice Dispatches an operation that returns a value tuple for execution or simulation
* @dev Should be used by any call site whose target function is declared to return value types: their result is the bare encoded values with no prefix
* @param _target The address the operation is dispatched into
* @param _mode The dispatch mode: SIMULATE computes the operation and unwinds every mutation by reverting with its result, EXECUTE settles it
* @param _callData The ABI encoded call to the operation
* @return result The operation's ABI encoded return values
*/
function _dispatchAndUnwrap(address _target, DispatchMode _mode, bytes memory _callData) internal returns (bytes memory result) {
return ((_mode == DispatchMode.SIMULATE) ? _simulate(_target, _callData, true) : _execute(_target, _callData));
}
/**
* @notice Simulates an operation through the execute-and-revert pattern and returns its result
* @dev Validates that a reversion occurred downstream with the expected error selector
* @param _target The address the simulated operation is dispatched into
* @param _callData The ABI encoded call to the operation's execute-and-revert function
* @param _unwrap Whether to strip the error's offset and length words from the result: stripping matches an operation declared to return value types, keeping them matches one declared to return bytes
* @return result The simulated operation's ABI encoded result
*/
function _simulate(address _target, bytes memory _callData, bool _unwrap) private returns (bytes memory result) {
// Call the function and ensure it reverted
(bool success, bytes memory revertData) = _target.call(_callData);
// NOTE: Should be unreachable since the simulation is required to revert downstream
require(!success, SIMULATION_CANNOT_MUTATE_STATE());
// Ensure that the exception has the correct selector for the simulate operation (indicating a successful simulation) and propagate the result upstream
bytes4 expectedErrorSelector = SIMULATION_RESULT.selector;
assembly ("memory-safe") {
// Revert with any genuine operation failure, mimicking the operation exactly
let errorSelectorPtr := add(revertData, 0x20)
if iszero(eq(shr(224, mload(errorSelectorPtr)), shr(224, expectedErrorSelector))) {
revert(errorSelectorPtr, mload(revertData))
}
// Handle the unwrap as specified
switch _unwrap
case 1 {
// Seek past the container's length word, the validated selector, and the error's offset word
// The caller only consumes the carried result
result := add(revertData, 0x44)
}
default {
// Seek the result pointer by 4 bytes (selector length)
result := add(revertData, 0x04)
// Write the new length of the result excluding the selector to the first word of result, effectively wiping the selector and seeking the entire result
mstore(result, sub(mload(revertData), 4))
}
}
}
/**
* @notice Executes an operation and reports its outcome instead of bubbling a failure
* @dev For best-effort operations that must never block their caller: the caller decides what a failure means
* @param _target The address the operation is dispatched into
* @param _callData The ABI encoded call to the operation
* @return success Whether the operation succeeded
* @return result The operation's return data on success, or its revert data on failure
*/
function _tryExecute(address _target, bytes memory _callData) internal returns (bool success, bytes memory result) {
return _target.call(_callData);
}
/**
* @notice Executes an operation and returns its revertData, bubbling any failure verbatim
* @param _target The address the operation is dispatched into
* @param _callData The ABI encoded call to the operation
* @return result The operation's revertData
*/
function _execute(address _target, bytes memory _callData) private returns (bytes memory result) {
bool success;
(success, result) = _target.call(_callData);
// Revert with any genuine operation failure, mimicking the operation exactly
assembly ("memory-safe") {
if iszero(success) {
revert(add(result, 0x20), mload(result))
}
}
}
}
src/libraries/logic/ValuationLogic.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { IRoycoDayKernel } from "../../interfaces/IRoycoDayKernel.sol";
import { MAX_MINT_DILUTION_WAD, VIRTUAL_SHARES, VIRTUAL_VALUE, WAD, ZERO_NAV_UNITS, ZERO_TRANCHE_UNITS } from "../Constants.sol";
import { Math, NAV_UNIT, RoycoUnitsMath, TRANCHE_UNIT, toUint256 } from "../Units.sol";
/**
* @title ValuationLogic
* @author Shivaansh Kapoor, Ankur Dubey, Tomer Ganor
* @notice Tranche NAV valuation for a Royco market: the collateral and LPT raw NAV reads, the LPT effective NAV, and NAV-to-shares conversion
* @dev Invoked by the kernel via delegatecall
*/
library ValuationLogic {
using RoycoUnitsMath for NAV_UNIT;
using RoycoUnitsMath for uint256;
using Math for uint256;
/**
* @notice Returns the mark-to-market value of the coinvested collateral backing the senior and junior tranches, denominated in the NAV units (USD, BTC, etc.) for this kernel
* @param $ The storage state of the Royco Kernel that is delegatecalling into this function
* @return collateralNAV The pure value of the held collateral assets
*/
function _getCollateralNAV(IRoycoDayKernel.RoycoDayKernelState storage $) internal view returns (NAV_UNIT collateralNAV) {
// With no holdings there is nothing to price
TRANCHE_UNIT totalCollateralAssets = $.totalCollateralAssets;
if (totalCollateralAssets == ZERO_TRANCHE_UNITS) return ZERO_NAV_UNITS;
// Get the held collateral assets and convert them to NAV units via the kernel's pricing
return IRoycoDayKernel(address(this)).convertCollateralAssetsToValue(totalCollateralAssets);
}
/**
* @notice Returns the raw net asset value of the liquidity provider tranche denominated in the NAV units (USD, BTC, etc.) for this kernel
* @param $ The storage state of the Royco Kernel that is delegatecalling into this function
* @return lptRawNAV The pure net asset value of the liquidity provider tranche invested assets
*/
function _getLiquidityProviderTrancheRawNAV(IRoycoDayKernel.RoycoDayKernelState storage $) internal view returns (NAV_UNIT lptRawNAV) {
// With no holdings there is nothing to price, an uninitialized venue is never queried
TRANCHE_UNIT totalLPTAssets = $.totalLPTAssets;
if (totalLPTAssets == ZERO_TRANCHE_UNITS) return ZERO_NAV_UNITS;
// Get the yield bearing assets owned by LPT and convert them to NAV units via the kernel's pricing
return IRoycoDayKernel(address(this)).convertLPTAssetsToValue(totalLPTAssets);
}
/**
* @notice Returns the effective net asset value (NAV) of the liquidity provider tranche denominated in the NAV units (USD, BTC, etc.) for this kernel
* @dev The effective NAV is the liquidity provider tranche's deployed market-making inventory (its raw NAV) plus the value of the
* senior tranche shares it holds from accumulated, not yet reinvested, liquidity premium payments
* @dev Reads the held senior-share count from storage, the value execution sees after the premium mint
* The preview path uses the overload below to inject the post-mint count that storage does not yet reflect
* @dev The senior NAV and share supply must be mutually consistent: the post-sync effective NAV against the
* post-carve-out-mint total supply, so the held senior shares are valued at the correct NAV per share
* @param $ The storage state of the Royco Kernel that is delegatecalling into this function
* @param _stEffectiveNAV The senior tranche's post-sync effective NAV: the total NAV backing all senior shares after reconciling unrealized PnL
* @param _totalSeniorTrancheShares The total senior tranche shares outstanding after minting the premium and protocol fee shares
* @return lptEffectiveNAV The effective net asset value of the liquidity provider tranche
*/
function _getLiquidityProviderTrancheEffectiveNAV(
IRoycoDayKernel.RoycoDayKernelState storage $,
NAV_UNIT _stEffectiveNAV,
uint256 _totalSeniorTrancheShares
)
internal
view
returns (NAV_UNIT lptEffectiveNAV)
{
// Value the held senior shares using the count committed to storage (the value execution sees after the premium mint)
return _getLiquidityProviderTrancheEffectiveNAV($, _stEffectiveNAV, _totalSeniorTrancheShares, $.lptOwnedSeniorTrancheShares);
}
/**
* @notice Returns the effective net asset value of the liquidity provider tranche for an explicitly supplied held senior-share count
* @dev The preview path supplies the post-mint held-share count (current storage plus this sync's premium shares) before the
* premium mint commits it to storage, so the previewed LPT effective NAV matches the value execution computes from storage
* @param $ The storage state of the Royco Kernel that is delegatecalling into this function
* @param _stEffectiveNAV The senior tranche's post-sync effective NAV: the total NAV backing all senior shares after reconciling unrealized PnL
* @param _totalSeniorTrancheShares The total senior tranche shares outstanding after minting the premium and protocol fee shares
* @param _lptOwnedSeniorTrancheShares The senior tranche shares held by the liquidity provider tranche from accumulated liquidity premium payments
* @return lptEffectiveNAV The effective net asset value of the liquidity provider tranche
*/
function _getLiquidityProviderTrancheEffectiveNAV(
IRoycoDayKernel.RoycoDayKernelState storage $,
NAV_UNIT _stEffectiveNAV,
uint256 _totalSeniorTrancheShares,
uint256 _lptOwnedSeniorTrancheShares
)
internal
view
returns (NAV_UNIT lptEffectiveNAV)
{
// Get the value of LPT's market-making inventory
NAV_UNIT lptRawNAV = _getLiquidityProviderTrancheRawNAV($);
// If there are no held senior shares or no senior shares outstanding, the effective NAV is just the raw NAV
if (_lptOwnedSeniorTrancheShares == 0 || _totalSeniorTrancheShares == 0) return lptRawNAV;
// The LPT effective NAV is the sum of the NAVs of its market-making inventory and its held ST shares
return (lptRawNAV + _convertToValue(_lptOwnedSeniorTrancheShares, _totalSeniorTrancheShares, _stEffectiveNAV, Math.Rounding.Floor));
}
/**
* @notice Returns the number of shares that have a claim on the specified value, clamped by the protocol's max mint dilution
* @dev The mint-sizing share conversion, shared by the tranches and the kernel-side mint sizing so both resolve identical share counts
* @dev See _convertToSharesUnclamped for the clamp-free variant, used only as a valuation reference and never to size a real mint
* @dev The mint-dilution clamp caps the share of the post-mint supply a single mint can own, bounding the share count any one mint can create
* @dev The clamp arms only in the collapsed-price regime where fair pricing itself mints runaway share counts, the state a
* supply-inflation attack needs, so a mint into a healthily priced tranche always prices fairly
* @dev With no shares outstanding the conversion stays 1:1 (a bootstrap mint dilutes nobody, so the clamp is exempt)
* @param _value The value to convert in NAV units
* @param _totalValue The total tranche controlled value in NAV units
* @param _totalSupply The total supply of tranche shares (including any marginally minted fee shares)
* @param _rounding The rounding mode to use for whichever branch sizes the mint
* @return shares The number of shares that have a claim on the specified value
*/
function _convertToShares(NAV_UNIT _value, NAV_UNIT _totalValue, uint256 _totalSupply, Math.Rounding _rounding) internal pure returns (uint256 shares) {
// The effective supply is the total supply plus the virtual shares
uint256 effectiveSupply = (_totalSupply + VIRTUAL_SHARES);
NAV_UNIT denominator = (_totalValue + VIRTUAL_VALUE);
// Arm the clamp only in the collapsed-price regime where fair pricing itself mints massive share counts
uint256 clampedShares = type(uint256).max;
if (effectiveSupply.mulDiv((WAD - MAX_MINT_DILUTION_WAD), MAX_MINT_DILUTION_WAD, Math.Rounding.Ceil) > toUint256(denominator)) {
// Cap the mint at the max share of the post-mint effective supply a single mint may own
clampedShares = effectiveSupply.mulDiv(MAX_MINT_DILUTION_WAD, (WAD - MAX_MINT_DILUTION_WAD), _rounding);
}
// Below the cap the mint takes the fair, unclamped virtual-shares price
return Math.min(clampedShares, _convertToSharesUnclamped(_value, _totalValue, _totalSupply, _rounding));
}
/**
* @notice Returns the shares that have a claim on the specified value under fair (unclamped) virtual-shares pricing
* @dev Identical to _convertToShares but WITHOUT the mint-dilution clamp
* @param _value The value to convert in NAV units
* @param _totalValue The total tranche controlled value in NAV units
* @param _totalSupply The total supply of tranche shares
* @param _rounding The rounding mode to use
* @return shares The number of shares that have a claim on the specified value at the fair, unclamped price
*/
function _convertToSharesUnclamped(
NAV_UNIT _value,
NAV_UNIT _totalValue,
uint256 _totalSupply,
Math.Rounding _rounding
)
internal
pure
returns (uint256 shares)
{
// The fair virtual-shares price, matching _convertToShares' unclamped branch
return (_totalSupply + VIRTUAL_SHARES).mulDiv(_value, (_totalValue + VIRTUAL_VALUE), _rounding);
}
/**
* @notice Returns the value (in NAV units) that the specified amount of shares have a claim on
* @dev The single value-conversion primitive, the inverse of _convertToShares, so a share count and its value round-trip consistently
* @param _shares The number of shares to convert
* @param _totalSupply The total supply of tranche shares (including any marginally minted fee shares)
* @param _totalValue The total tranche controlled value in NAV units
* @param _rounding The rounding mode to use
* @return value The value in NAV units that the shares have a claim on
*/
function _convertToValue(uint256 _shares, uint256 _totalSupply, NAV_UNIT _totalValue, Math.Rounding _rounding) internal pure returns (NAV_UNIT value) {
return (_totalValue + VIRTUAL_VALUE).mulDiv(_shares, (_totalSupply + VIRTUAL_SHARES), _rounding);
}
/**
* @notice Returns a tranche share rate: the NAV-unit value of one whole tranche share at the given tranche's total share supply and effective NAV
* @param _trancheTotalSupply The total tranche share supply the rate is computed against (for the senior tranche, the post-mint supply)
* @param _trancheEffectiveNAV The tranche's effective NAV backing all of its shares
* @return rate The NAV-unit value of one whole tranche share, rounded down
*/
function _computeTrancheShareRate(uint256 _trancheTotalSupply, NAV_UNIT _trancheEffectiveNAV) internal pure returns (NAV_UNIT rate) {
return _convertToValue(WAD, _trancheTotalSupply, _trancheEffectiveNAV, Math.Rounding.Floor);
}
}
src/tranches/base/RoycoVaultTranche.sol
// SPDX-License-Identifier: LicenseRef-PolyForm-Perimeter-1.0.1
pragma solidity ^0.8.28;
import { ERC20Upgradeable, IERC20, IERC20Metadata } from "../../../lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol";
import { ERC20BurnableUpgradeable } from "../../../lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC20BurnableUpgradeable.sol";
import { ERC20PermitUpgradeable } from "../../../lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
import { SafeERC20 } from "../../../lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import { Math } from "../../../lib/openzeppelin-contracts/contracts/utils/math/Math.sol";
import { RoycoBase } from "../../base/RoycoBase.sol";
import { IRoycoDayKernel } from "../../interfaces/IRoycoDayKernel.sol";
import { IRoycoVaultTranche } from "../../interfaces/IRoycoVaultTranche.sol";
import { WAD_DECIMALS } from "../../libraries/Constants.sol";
import { AssetClaims, DispatchMode, SyncedAccountingState, TrancheType } from "../../libraries/Types.sol";
import { NAV_UNIT, RoycoUnitsMath, TRANCHE_UNIT, toUint256 } from "../../libraries/Units.sol";
import { AssetLedgerLogic } from "../../libraries/logic/AssetLedgerLogic.sol";
import { DispatchLogic } from "../../libraries/logic/DispatchLogic.sol";
import { ValuationLogic } from "../../libraries/logic/ValuationLogic.sol";
/**
* @title RoycoVaultTranche
* @author Ankur Dubey, Shivaansh Kapoor, Tomer Ganor
* @notice Abstract base contract implementing core vault functionality for Royco tranches (ST, JT, and LPT)
* @dev Tranches interact with the kernel to execute all operations based on the current holistic state of the Royco market
*/
abstract contract RoycoVaultTranche is IRoycoVaultTranche, RoycoBase, ERC20BurnableUpgradeable, ERC20PermitUpgradeable {
using Math for uint256;
using RoycoUnitsMath for uint256;
using SafeERC20 for IERC20;
using DispatchLogic for address;
/// @dev Storage slot for RoycoVaultTrancheState using ERC-7201 pattern
// keccak256(abi.encode(uint256(keccak256("Royco.storage.RoycoVaultTrancheState")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant _ROYCO_VAULT_TRANCHE_STORAGE_SLOT = 0xb29e56aa3db56637b513fb077b36928988b241f28eccd4f6a5bd34624bbe3900;
/// @dev Permissions the function to only be callable by the kernel, the single source of truth for sync-driven share mints
modifier onlyKernel() {
require(msg.sender == _getRoycoVaultTrancheStorage().kernel, ONLY_KERNEL());
_;
}
/**
* @notice Initializes the Royco tranche
* @dev This function initializes parent contracts and the tranche-specific state
* @param _params Deployment parameters including name, symbol, initial authority, kernel, and asset
*/
function __RoycoTranche_init(RoycoTrancheInitParams calldata _params) internal onlyInitializing {
// Ensure that the asset and kernel are not null
require(_params.asset != address(0) && _params.kernel != address(0), NULL_ADDRESS());
// Set the tranche's market wiring
RoycoVaultTrancheState storage $ = _getRoycoVaultTrancheStorage();
$.kernel = _params.kernel;
$.asset = _params.asset;
// Initialize all the parent contracts
__RoycoBase_init(_params.initialAuthority);
__ERC20_init_unchained(_params.name, _params.symbol);
__ERC20Burnable_init();
__ERC20Permit_init(_params.name);
}
// =============================
// Tranche Deposit and Redeem Functions
// =============================
/// @inheritdoc IRoycoVaultTranche
function deposit(TRANCHE_UNIT _assets, address _receiver) public virtual override(IRoycoVaultTranche) restricted returns (uint256 shares) {
require(_receiver != address(0), ERC20InvalidReceiver(address(0)));
// Transfer the assets to the kernel
RoycoVaultTrancheState storage $ = _getRoycoVaultTrancheStorage();
IERC20($.asset).safeTransferFrom(msg.sender, $.kernel, toUint256(_assets));
// Deposit the assets into the Royco market, the kernel prices the shares and mints them to the receiver
shares = _deposit(DispatchMode.EXECUTE, _assets, _receiver);
emit Deposit(msg.sender, _receiver, _assets, shares);
}
/// @inheritdoc IRoycoVaultTranche
function redeem(
uint256 _shares,
address _receiver,
address _owner
)
public
virtual
override(IRoycoVaultTranche)
restricted
returns (AssetClaims memory claims)
{
require(_receiver != address(0), ERC20InvalidReceiver(address(0)));
// Spend allowance if msg.sender is not the owner
if (msg.sender != _owner) _spendAllowance(_owner, msg.sender, _shares);
// Process the withdrawal from the Royco market, the kernel burns the owner's shares after scaling their claims
// It is expected that the kernel transfers the assets directly to the receiver
claims = _redeem(DispatchMode.EXECUTE, _shares, _receiver, _owner);
emit Redeem(msg.sender, _receiver, claims, _shares);
}
// =============================
// Tranche Max Deposit and Redeem Functions
// =============================
/// @inheritdoc IRoycoVaultTranche
function maxDeposit(address _receiver) external view virtual override(IRoycoVaultTranche) returns (TRANCHE_UNIT assets) {
return IRoycoDayKernel(kernel()).inkindMaxDeposit(_receiver);
}
/// @inheritdoc IRoycoVaultTranche
function maxRedeem(address _owner) public view virtual override(IRoycoVaultTranche) returns (uint256 shares) {
// The maximum redeemable shares are the minimum of the owner's share balance and the globally redeemable shares the kernel prices
return Math.min(balanceOf(_owner), IRoycoDayKernel(kernel()).inkindMaxRedeemable(_owner));
}
// =============================
// Tranche Preview and Conversion Functions
// =============================
/// @inheritdoc IRoycoVaultTranche
/// @dev Routes the deposit through the execute-and-revert pattern so the quote is produced by the actual kernel deposit path under its real semantics
function previewDeposit(TRANCHE_UNIT _assets) external virtual override(IRoycoVaultTranche) returns (uint256 shares) {
return _deposit(DispatchMode.SIMULATE, _assets, kernel());
}
/// @inheritdoc IRoycoVaultTranche
/// @dev Routes the redemption through the execute-and-revert pattern so the quote is produced by the actual kernel redemption path under its real semantics
function previewRedeem(uint256 _shares) external virtual override(IRoycoVaultTranche) returns (AssetClaims memory claims) {
return _redeem(DispatchMode.SIMULATE, _shares, kernel(), address(0));
}
/// @inheritdoc IRoycoVaultTranche
function convertToAssets(uint256 _shares) public view virtual override(IRoycoVaultTranche) returns (AssetClaims memory claims) {
// Get the post-sync tranche state: applying NAV reconciliation
(SyncedAccountingState memory state, AssetClaims memory trancheClaims, uint256 trancheTotalShares) =
IRoycoDayKernel(kernel()).previewSyncTrancheAccountingFor(TRANCHE_TYPE());
if (TRANCHE_TYPE() == TrancheType.LIQUIDITY_PROVIDER) {
// We exclude any idle (not reinvested) ST shares from the LPT claims in order to ensure that its share price does not drop due to slippage incurred on reinvestment
trancheClaims.stShares = 0;
trancheClaims.nav = state.lptRawNAV;
}
return AssetLedgerLogic._scaleAssetClaims(trancheClaims, _shares, trancheTotalShares, true);
}
/// @inheritdoc IRoycoVaultTranche
function convertToShares(TRANCHE_UNIT _assets) public view virtual override(IRoycoVaultTranche) returns (uint256 shares) {
address kernel_ = kernel();
// Value the assets specified in NAV units
NAV_UNIT value = (TRANCHE_TYPE() == TrancheType.LIQUIDITY_PROVIDER)
? IRoycoDayKernel(kernel_).convertLPTAssetsToValue(_assets)
: IRoycoDayKernel(kernel_).convertCollateralAssetsToValue(_assets);
// Get the post-sync tranche state
(SyncedAccountingState memory state, AssetClaims memory trancheClaims, uint256 trancheTotalShares) =
IRoycoDayKernel(kernel_).previewSyncTrancheAccountingFor(TRANCHE_TYPE());
// We exclude any idle (not reinvested) ST shares from the LPT NAV basis in order to ensure that its NAV per share does not drop due to slippage incurred on reinvestment
NAV_UNIT navBasis = ((TRANCHE_TYPE() == TrancheType.LIQUIDITY_PROVIDER) ? state.lptRawNAV : trancheClaims.nav);
shares = ValuationLogic._convertToShares(value, navBasis, trancheTotalShares, Math.Rounding.Floor);
}
// =============================
// General Tranche View Functions
// =============================
/// @inheritdoc IRoycoVaultTranche
function totalAssets() external view virtual override(IRoycoVaultTranche) returns (AssetClaims memory claims) {
(, claims,) = IRoycoDayKernel(kernel()).previewSyncTrancheAccountingFor(TRANCHE_TYPE());
}
/// @inheritdoc IRoycoVaultTranche
function asset() external view virtual override(IRoycoVaultTranche) returns (address) {
return _getRoycoVaultTrancheStorage().asset;
}
/// @inheritdoc IRoycoVaultTranche
function kernel() public view virtual override(IRoycoVaultTranche) returns (address) {
return _getRoycoVaultTrancheStorage().kernel;
}
/**
* @inheritdoc IERC20Metadata
* @dev The kernel always uses WAD precision for NAV units
* @dev Shares are minted using NAV_UNIT values instead of TRANCHE_UNIT values, so they have identical precision to NAV_UNIT values (WAD precision)
*/
function decimals() public view virtual override(ERC20Upgradeable, IERC20Metadata) returns (uint8) {
return uint8(WAD_DECIMALS);
}
/// @dev Returns the type of the tranche (Senior, Junior, or Liquidity)
function TRANCHE_TYPE() public pure virtual returns (TrancheType);
// =============================
// Kernel Mint and Burn Entrypoints
// =============================
/// @inheritdoc IRoycoVaultTranche
function mintProtocolFeeShares(
address _protocolFeeRecipient,
uint256 _protocolFeeShares
)
external
virtual
override(IRoycoVaultTranche)
onlyKernel
returns (uint256 totalTrancheShares)
{
// Mint the precomputed protocol fee shares to the recipient (the kernel prices them jointly with the liquidity premium)
if (_protocolFeeShares != 0) _mint(_protocolFeeRecipient, _protocolFeeShares);
totalTrancheShares = totalSupply();
emit ProtocolFeeSharesMinted(_protocolFeeRecipient, _protocolFeeShares, totalTrancheShares);
}
/// @inheritdoc IRoycoVaultTranche
function kernelMint(address _to, uint256 _shares) external virtual override(IRoycoVaultTranche) onlyKernel {
require(_to != address(0), ERC20InvalidReceiver(address(0)));
_mint(_to, _shares);
}
/// @inheritdoc IRoycoVaultTranche
function kernelBurn(address _from, uint256 _shares) external virtual override(IRoycoVaultTranche) onlyKernel {
_burn(_from, _shares);
}
// =============================
// Public Burn Functions
// =============================
/// @inheritdoc ERC20BurnableUpgradeable
function burn(uint256 _shares) public virtual override(ERC20BurnableUpgradeable) restricted {
super.burn(_shares);
}
/// @inheritdoc ERC20BurnableUpgradeable
function burnFrom(address _account, uint256 _shares) public virtual override(ERC20BurnableUpgradeable) restricted {
super.burnFrom(_account, _shares);
}
// =============================
// Internal Utility Functions
// =============================
/**
* @dev Deposits the assets into the Royco market through the kernel's in-kind deposit entrypoint
* @dev The kernel resolves the deposited tranche from this calling tranche, prices the shares at its pre-deposit effective NAV against the post-sync supply, and mints them to the receiver
* @dev Forwards msg.sender as the caller for an execution, a simulation carries the null synthetic caller so previews never vary by caller
* @param _mode The dispatch mode: SIMULATE computes the operation and unwinds every mutation by reverting with its result, EXECUTE settles it
* @param _assets The amount of assets to deposit, denominated in the tranche's base asset units
* @param _receiver The address that receives the minted shares
* @return shares The number of shares minted for the deposit
*/
function _deposit(DispatchMode _mode, TRANCHE_UNIT _assets, address _receiver) internal virtual returns (uint256 shares) {
// Deposit the assets into the Royco market through the kernel's in-kind deposit entrypoint, which prices and mints the shares
// The kernel rejects a deposit that prices to zero shares
return abi.decode(
kernel()._dispatchAndUnwrap(_mode, abi.encodeCall(IRoycoDayKernel.inkindDeposit, (_mode, _assets, _resolveCaller(_mode), _receiver))), (uint256)
);
}
/**
* @dev Redeems the shares from the Royco market through the kernel's in-kind redemption entrypoint
* @dev The kernel resolves the redeemed tranche from this calling tranche, transfers the redeemed assets directly to the receiver, and burns the owner's shares after scaling their claims
* @dev Forwards msg.sender as the caller for an execution, a simulation carries the null synthetic caller so previews never vary by caller
* @param _mode The dispatch mode: SIMULATE computes the operation and unwinds every mutation by reverting with its result, EXECUTE settles it
* @param _shares The number of shares to redeem
* @param _receiver The address that receives the redeemed assets
* @param _owner The address whose shares are burned for the redemption
* @return claims The distribution of assets transferred to the receiver on redemption
*/
function _redeem(DispatchMode _mode, uint256 _shares, address _receiver, address _owner) internal virtual returns (AssetClaims memory claims) {
// Redeem the shares through the kernel's in-kind redemption entrypoint, the kernel transfers the redeemed assets directly to the receiver
// The kernel rejects a zero-share redemption
return abi.decode(
kernel()._dispatchAndUnwrap(_mode, abi.encodeCall(IRoycoDayKernel.inkindRedeem, (_mode, _shares, _resolveCaller(_mode), _owner, _receiver))),
(AssetClaims)
);
}
/// @dev Resolves the caller forwarded to the kernel: an execution forwards msg.sender and a simulation carries the null address so previews never vary by caller
/// @param _mode The dispatch mode used to resolve the caller
function _resolveCaller(DispatchMode _mode) internal view returns (address) {
return (_mode == DispatchMode.SIMULATE) ? address(0) : msg.sender;
}
/**
* @inheritdoc ERC20Upgradeable
* @dev Routes every balance update through the kernel's screening hook, which enforces the market's blacklist and
* reverts when the kernel is paused: transfers, mints, and burns are all gated by the kernel
*/
function _update(address _from, address _to, uint256 _value) internal override(ERC20Upgradeable) {
// Call the kernel's pre-balance update hook to assert that the balance update is valid
IRoycoDayKernel(kernel()).preTrancheBalanceUpdateHook(msg.sender, _from, _to, _value);
// Call the parent contract's update function to update the balance
ERC20Upgradeable._update(_from, _to, _value);
}
/**
* @notice Returns a storage pointer to the RoycoVaultTrancheState storage
* @dev Uses ERC-7201 storage slot pattern for collision-resistant storage
* @return $ Storage pointer to the tranche's state
*/
function _getRoycoVaultTrancheStorage() internal pure returns (RoycoVaultTrancheState storage $) {
assembly ("memory-safe") {
$.slot := _ROYCO_VAULT_TRANCHE_STORAGE_SLOT
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 2000,
"details": {
"yul": true,
"yulDetails": {
"stackAllocation": true
},
"constantOptimizer": true
},
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"lib/Pendle-SY-Public/:@openzeppelin/contracts/=lib/openzeppelin-contracts-v4/contracts/",
"@balancer-labs/v3-interfaces/=lib/balancer-v3-monorepo/pkg/interfaces/",
"@balancer-labs/v3-solidity-utils/=lib/balancer-v3-monorepo/pkg/solidity-utils/",
"@balancer-labs/v3-vault/=lib/balancer-v3-monorepo/pkg/vault/",
"@balancer-labs/v3-pool-utils/=lib/balancer-v3-monorepo/pkg/pool-utils/",
"@balancer-labs/v3-pool-gyro/=lib/balancer-v3-monorepo/pkg/pool-gyro/",
"@balancer-labs/v3-standalone-utils/=lib/balancer-v3-monorepo/pkg/standalone-utils/",
"@chainlink/contracts/=lib/chainlink-brownie-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"Pendle-SY-Public/=lib/Pendle-SY-Public/contracts/",
"balancer-v3-monorepo/=lib/balancer-v3-monorepo/",
"chainlink-brownie-contracts/=lib/chainlink-brownie-contracts/",
"ds-test/=lib/openzeppelin-contracts-v4/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts-v4/=lib/openzeppelin-contracts-v4/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin/=lib/openzeppelin-contracts-v4/contracts/",
"royco-periphery/=lib/royco-periphery/",
"solady/=lib/solady/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.