// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
/**
* @title Assertions
* @notice This library contains assertions for common requirement checks
*/
library Assertions {
// --- Errors ---
/// @dev Throws if `_x` is not greater than `_y`
error NotGreaterThan(uint256 _x, uint256 _y);
/// @dev Throws if `_x` is not lesser than `_y`
error NotLesserThan(uint256 _x, uint256 _y);
/// @dev Throws if `_x` is not greater than or equal to `_y`
error NotGreaterOrEqualThan(uint256 _x, uint256 _y);
/// @dev Throws if `_x` is not lesser than or equal to `_y`
error NotLesserOrEqualThan(uint256 _x, uint256 _y);
/// @dev Throws if `_x` is not greater than `_y`
error IntNotGreaterThan(int256 _x, int256 _y);
/// @dev Throws if `_x` is not lesser than `_y`
error IntNotLesserThan(int256 _x, int256 _y);
/// @dev Throws if `_x` is not greater than or equal to `_y`
error IntNotGreaterOrEqualThan(int256 _x, int256 _y);
/// @dev Throws if `_x` is not lesser than or equal to `_y`
error IntNotLesserOrEqualThan(int256 _x, int256 _y);
/// @dev Throws if checked amount is null
error NullAmount();
/// @dev Throws if checked address is null
error NullAddress();
/// @dev Throws if checked address contains no code
error NoCode(address _contract);
// --- Assertions ---
/// @dev Asserts that `_x` is greater than `_y` and returns `_x`
function assertGt(uint256 _x, uint256 _y) internal pure returns (uint256 __x) {
if (_x <= _y) revert NotGreaterThan(_x, _y);
return _x;
}
/// @dev Asserts that `_x` is greater than `_y` and returns `_x`
function assertGt(int256 _x, int256 _y) internal pure returns (int256 __x) {
if (_x <= _y) revert IntNotGreaterThan(_x, _y);
return _x;
}
/// @dev Asserts that `_x` is greater than or equal to `_y` and returns `_x`
function assertGtEq(uint256 _x, uint256 _y) internal pure returns (uint256 __x) {
if (_x < _y) revert NotGreaterOrEqualThan(_x, _y);
return _x;
}
/// @dev Asserts that `_x` is greater than or equal to `_y` and returns `_x`
function assertGtEq(int256 _x, int256 _y) internal pure returns (int256 __x) {
if (_x < _y) revert IntNotGreaterOrEqualThan(_x, _y);
return _x;
}
/// @dev Asserts that `_x` is lesser than `_y` and returns `_x`
function assertLt(uint256 _x, uint256 _y) internal pure returns (uint256 __x) {
if (_x >= _y) revert NotLesserThan(_x, _y);
return _x;
}
/// @dev Asserts that `_x` is lesser than `_y` and returns `_x`
function assertLt(int256 _x, int256 _y) internal pure returns (int256 __x) {
if (_x >= _y) revert IntNotLesserThan(_x, _y);
return _x;
}
/// @dev Asserts that `_x` is lesser than or equal to `_y` and returns `_x`
function assertLtEq(uint256 _x, uint256 _y) internal pure returns (uint256 __x) {
if (_x > _y) revert NotLesserOrEqualThan(_x, _y);
return _x;
}
/// @dev Asserts that `_x` is lesser than or equal to `_y` and returns `_x`
function assertLtEq(int256 _x, int256 _y) internal pure returns (int256 __x) {
if (_x > _y) revert IntNotLesserOrEqualThan(_x, _y);
return _x;
}
/// @dev Asserts that `_x` is not null and returns `_x`
function assertNonNull(uint256 _x) internal pure returns (uint256 __x) {
if (_x == 0) revert NullAmount();
return _x;
}
/// @dev Asserts that `_address` is not null and returns `_address`
function assertNonNull(address _address) internal pure returns (address __address) {
if (_address == address(0)) revert NullAddress();
return _address;
}
/// @dev Asserts that `_address` contains code and returns `_address`
function assertHasCode(address _address) internal view returns (address __address) {
if (_address.code.length == 0) revert NoCode(_address);
return _address;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {IAuthorizable} from '@interfaces/utils/IAuthorizable.sol';
import {EnumerableSet} from '@openzeppelin/utils/structs/EnumerableSet.sol';
/**
* @title Authorizable
* @notice Implements authorization control for contracts
* @dev Authorization control is boolean and handled by `isAuthorized` modifier
*/
abstract contract Authorizable is IAuthorizable {
using EnumerableSet for EnumerableSet.AddressSet;
// --- Data ---
/// @notice EnumerableSet of authorized accounts
EnumerableSet.AddressSet internal _authorizedAccounts;
// --- Init ---
/**
* @param _account Initial account to add authorization to
*/
constructor(address _account) {
_addAuthorization(_account);
}
// --- Views ---
/**
* @notice Checks whether an account is authorized
* @return _authorized Whether the account is authorized or not
*/
function authorizedAccounts(address _account) external view returns (bool _authorized) {
return _isAuthorized(_account);
}
/**
* @notice Getter for the authorized accounts
* @return _accounts Array of authorized accounts
*/
function authorizedAccounts() external view returns (address[] memory _accounts) {
return _authorizedAccounts.values();
}
// --- Methods ---
/**
* @notice Add auth to an account
* @param _account Account to add auth to
*/
function addAuthorization(address _account) external virtual isAuthorized {
_addAuthorization(_account);
}
/**
* @notice Remove auth from an account
* @param _account Account to remove auth from
*/
function removeAuthorization(address _account) external virtual isAuthorized {
_removeAuthorization(_account);
}
// --- Internal methods ---
function _addAuthorization(address _account) internal {
if (_account == address(0)) revert NullAddress();
if (_authorizedAccounts.add(_account)) {
emit AddAuthorization(_account);
} else {
revert AlreadyAuthorized();
}
}
function _removeAuthorization(address _account) internal {
if (_authorizedAccounts.remove(_account)) {
emit RemoveAuthorization(_account);
} else {
revert NotAuthorized();
}
}
function _isAuthorized(address _account) internal view virtual returns (bool _authorized) {
return _authorizedAccounts.contains(_account);
}
// --- Modifiers ---
/**
* @notice Checks whether msg.sender can call an authed function
* @dev Will revert with `Unauthorized` if the sender is not authorized
*/
modifier isAuthorized() {
if (!_isAuthorized(msg.sender)) revert Unauthorized();
_;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.6) (utils/Base64.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*
* _Available since v4.5._
*/
library Base64 {
/**
* @dev Base64 Encoding/Decoding Table
*/
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/
function encode(bytes memory data) internal pure returns (string memory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/
if (data.length == 0) return "";
// Loads the table into memory
string memory table = _TABLE;
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
// and split into 4 numbers of 6 bits.
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
// - `data.length + 2` -> Round up
// - `/ 3` -> Number of 3-bytes chunks
// - `4 *` -> 4 characters for each chunk
string memory result = new string(4 * ((data.length + 2) / 3));
/// @solidity memory-safe-assembly
assembly {
// Prepare the lookup table (skip the first "length" byte)
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 0x20)
let dataPtr := data
let endPtr := add(data, mload(data))
// In some cases, the last iteration will read bytes after the end of the data. We cache the value, and
// set it to zero to make sure no dirty bytes are read in that section.
let afterPtr := add(endPtr, 0x20)
let afterCache := mload(afterPtr)
mstore(afterPtr, 0x00)
// Run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// To write each character, shift the 3 byte (24 bits) chunk
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
// and apply logical AND with 0x3F to bitmask the least significant 6 bits.
// Use this as an index into the lookup table, mload an entire word
// so the desired character is in the least significant byte, and
// mstore8 this least significant byte into the result and continue.
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
}
// Reset the value that was cached
mstore(afterPtr, afterCache)
// When data `bytes` is not exactly 3 bytes long
// it is padded with `=` characters at the end
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// ----------------------------------------------------------------------------
// DateTime Library v2.0
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library DateTime {
uint256 constant SECONDS_PER_DAY = 24 * 60 * 60;
uint256 constant SECONDS_PER_HOUR = 60 * 60;
uint256 constant SECONDS_PER_MINUTE = 60;
int256 constant OFFSET19700101 = 2_440_588;
uint256 constant DOW_MON = 1;
uint256 constant DOW_TUE = 2;
uint256 constant DOW_WED = 3;
uint256 constant DOW_THU = 4;
uint256 constant DOW_FRI = 5;
uint256 constant DOW_SAT = 6;
uint256 constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 _days) {
require(year >= 1970);
int256 _year = int256(year);
int256 _month = int256(month);
int256 _day = int256(day);
int256 __days = _day - 32_075 + (1461 * (_year + 4800 + (_month - 14) / 12)) / 4
+ (367 * (_month - 2 - ((_month - 14) / 12) * 12)) / 12 - (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) / 4
- OFFSET19700101;
_days = uint256(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint256 _days) internal pure returns (uint256 year, uint256 month, uint256 day) {
unchecked {
int256 __days = int256(_days);
int256 L = __days + 68_569 + OFFSET19700101;
int256 N = (4 * L) / 146_097;
L = L - (146_097 * N + 3) / 4;
int256 _year = (4000 * (L + 1)) / 1_461_001;
L = L - (1461 * _year) / 4 + 31;
int256 _month = (80 * L) / 2447;
int256 _day = L - (2447 * _month) / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint256(_year);
month = uint256(_month);
day = uint256(_day);
}
}
function timestampFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(
uint256 year,
uint256 month,
uint256 day,
uint256 hour,
uint256 minute,
uint256 second
) internal pure returns (uint256 timestamp) {
timestamp =
_daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day) {
unchecked {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
}
function timestampToDateTime(uint256 timestamp)
internal
pure
returns (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second)
{
unchecked {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint256 secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
}
function isValidDate(uint256 year, uint256 month, uint256 day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(
uint256 year,
uint256 month,
uint256 day,
uint256 hour,
uint256 minute,
uint256 second
) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) {
(uint256 year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint256 year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) {
(uint256 year, uint256 month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {
uint256 _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = ((_days + 3) % 7) + 1;
}
function getYear(uint256 timestamp) internal pure returns (uint256 year) {
(year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint256 timestamp) internal pure returns (uint256 month) {
(, month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint256 timestamp) internal pure returns (uint256 day) {
(,, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint256 timestamp) internal pure returns (uint256 hour) {
uint256 secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {
uint256 secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint256 timestamp) internal pure returns (uint256 second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp >= timestamp);
}
function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = ((month - 1) % 12) + 1;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp >= timestamp);
}
function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp <= timestamp);
}
function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) {
(uint256 year, uint256 month, uint256 day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint256 yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = (yearMonth % 12) + 1;
uint256 daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + (timestamp % SECONDS_PER_DAY);
require(newTimestamp <= timestamp);
}
function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) {
require(fromTimestamp <= toTimestamp);
(uint256 fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint256 toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) {
require(fromTimestamp <= toTimestamp);
(uint256 fromYear, uint256 fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint256 toYear, uint256 toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
function __ERC721Enumerable_init() internal onlyInitializing {
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual override {
super._beforeTokenTransfer(from, to, firstTokenId, batchSize);
if (batchSize > 1) {
// Will only trigger during construction. Batch transferring (minting) is not available afterwards.
revert("ERC721Enumerable: consecutive transfers not supported");
}
uint256 tokenId = firstTokenId;
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: address zero is not a valid owner");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _ownerOf(tokenId);
require(owner != address(0), "ERC721: invalid token ID");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not token owner or approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
_requireMinted(tokenId);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_safeTransfer(from, to, tokenId, data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _ownerOf(tokenId) != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId, 1);
// Check that tokenId was not minted by `_beforeTokenTransfer` hook
require(!_exists(tokenId), "ERC721: token already minted");
unchecked {
// Will not overflow unless all 2**256 token ids are minted to the same owner.
// Given that tokens are minted one by one, it is impossible in practice that
// this ever happens. Might change if we allow batch minting.
// The ERC fails to describe this case.
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId, 1);
// Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
owner = ERC721Upgradeable.ownerOf(tokenId);
// Clear approvals
delete _tokenApprovals[tokenId];
unchecked {
// Cannot overflow, as that would require more tokens to be burned/transferred
// out than the owner initially received through minting and transferring in.
_balances[owner] -= 1;
}
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId, 1);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId, 1);
// Check that tokenId was not transferred by `_beforeTokenTransfer` hook
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
// Clear approvals from the previous owner
delete _tokenApprovals[tokenId];
unchecked {
// `_balances[from]` cannot overflow for the same reason as described in `_burn`:
// `from`'s balance is the number of token held, which is at least one before the current
// transfer.
// `_balances[to]` could overflow in the conditions described in `_mint`. That would require
// all 2**256 token ids to be minted, which in practice is impossible.
_balances[from] -= 1;
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` has not been minted yet.
*/
function _requireMinted(uint256 tokenId) internal view virtual {
require(_exists(tokenId), "ERC721: invalid token ID");
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
* - When `from` is zero, the tokens will be minted for `to`.
* - When `to` is zero, ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
* - When `from` is zero, the tokens were minted for `to`.
* - When `to` is zero, ``from``'s tokens were burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
* being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
* that `ownerOf(tokenId)` is `a`.
*/
// solhint-disable-next-line func-name-mixedcase
function __unsafe_increaseBalance(address account, uint256 amount) internal {
_balances[account] += amount;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[44] private __gap;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
/**
* @title Encoding
* @notice This library contains functions for decoding data into common types
*/
library Encoding {
// --- Methods ---
/// @dev Decodes a bytes array into a uint256
function toUint256(bytes memory _data) internal pure returns (uint256 _uint256) {
assembly {
_uint256 := mload(add(_data, 0x20))
}
}
/// @dev Decodes a bytes array into an int256
function toInt256(bytes memory _data) internal pure returns (int256 _int256) {
assembly {
_int256 := mload(add(_data, 0x20))
}
}
/// @dev Decodes a bytes array into an address
function toAddress(bytes memory _data) internal pure returns (address _address) {
assembly {
_address := mload(add(_data, 0x20))
}
}
/// @dev Decodes a bytes array into a bool
function toBool(bytes memory _data) internal pure returns (bool _bool) {
assembly {
_bool := mload(add(_data, 0x20))
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
interface IAuthorizable {
// --- Events ---
/**
* @notice Emitted when an account is authorized
* @param _account Account that is authorized
*/
event AddAuthorization(address _account);
/**
* @notice Emitted when an account is unauthorized
* @param _account Account that is unauthorized
*/
event RemoveAuthorization(address _account);
// --- Errors ---
/// @notice Throws if the account is already authorized on `addAuthorization`
error AlreadyAuthorized(); // 0x6027d27e
/// @notice Throws if the account is not authorized on `removeAuthorization`
error NotAuthorized(); // 0xea8e4eb5
/// @notice Throws if the account is not authorized and tries to call an `onlyAuthorized` method
error Unauthorized(); // 0x82b42900
/// @notice Throws if zero address is passed
error NullAddress();
// --- Data ---
/**
* @notice Checks whether an account is authorized on the contract
* @param _account Account to check
* @return _authorized Whether the account is authorized or not
*/
function authorizedAccounts(address _account) external view returns (bool _authorized);
/**
* @notice Getter for the authorized accounts
* @return _accounts Array of authorized accounts
*/
function authorizedAccounts() external view returns (address[] memory _accounts);
// --- Administration ---
/**
* @notice Add authorization to an account
* @param _account Account to add authorization to
* @dev Method will revert if the account is already authorized
*/
function addAuthorization(address _account) external;
/**
* @notice Remove authorization from an account
* @param _account Account to remove authorization from
* @dev Method will revert if the account is not authorized
*/
function removeAuthorization(address _account) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
/**
* @title IBaseOracle
* @notice Basic interface for a system price feed
* All price feeds should be translated into an 18 decimals format
*/
interface IBaseOracle {
// --- Errors ---
error InvalidPriceFeed();
/**
* @notice Symbol of the quote: token / baseToken (e.g. 'ETH / USD')
*/
function symbol() external view returns (string memory _symbol);
/**
* @notice Fetch the latest oracle result and whether it is valid or not
* @dev This method should never revert
*/
function getResultWithValidity() external view returns (uint256 _result, bool _validity);
/**
* @notice Fetch the latest oracle result
* @dev Will revert if is the price feed is invalid
*/
function read() external view returns (uint256 _value);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {ISAFEEngine} from '@interfaces/ISAFEEngine.sol';
import {IERC20Metadata} from '@openzeppelin/token/ERC20/extensions/IERC20Metadata.sol';
import {IAuthorizable} from '@interfaces/utils/IAuthorizable.sol';
import {IDisableable} from '@interfaces/utils/IDisableable.sol';
interface ICollateralJoin is IAuthorizable, IDisableable {
// --- Events ---
/**
* @notice Emitted when an account joins collateral tokens into the system
* @param _sender Address of the account that called the function (sent the ERC20 collateral tokens)
* @param _account Address of the account that received the collateral tokens
* @param _wad Amount of collateral tokens joined [wad]
*/
event Join(address _sender, address _account, uint256 _wad);
/**
* @notice Emitted when an account exits collateral tokens from the system
* @param _sender Address of the account that called the function (sent the internal collateral tokens)
* @param _account Address of the account that received the ERC20 collateral tokens
* @param _wad Amount of collateral tokens exited [wad]
*/
event Exit(address _sender, address _account, uint256 _wad);
// --- Registry ---
/// @notice Address of the SAFEEngine contract
function safeEngine() external view returns (ISAFEEngine _safeEngine);
/// @notice Address of the ERC20 collateral token contract
function collateral() external view returns (IERC20Metadata _collateral);
// --- Data ---
/**
* @notice The collateral type that this contract handles
* @return _cType Bytes32 representation of the collateralType
*/
function collateralType() external view returns (bytes32 _cType);
/// @notice Number of decimals of the collateral token
function decimals() external view returns (uint256 _decimals);
/// @notice Multiplier used to transform collateral into 18 decimals within the system
function multiplier() external view returns (uint256 _multiplier);
// --- Methods ---
/**
* @notice Join collateral in the system
* @param _account Account to which we add collateral into the system
* @param _wei Amount of collateral to transfer in the system (represented as a number with token decimals)
*/
function join(address _account, uint256 _wei) external;
/**
* @notice Exit collateral from the system
* @param _account Account to which we transfer the collateral out of the system
* @param _wei Amount of collateral to transfer to account (represented as a number with token decimals)
*/
function exit(address _account, uint256 _wei) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {ICollateralJoin} from '@interfaces/utils/ICollateralJoin.sol';
import {IAuthorizable} from '@interfaces/utils/IAuthorizable.sol';
import {IDisableable} from '@interfaces/utils/IDisableable.sol';
interface ICollateralJoinFactory is IAuthorizable, IDisableable {
// --- Events ---
/**
* @notice Emitted when a new CollateralJoin contract is deployed
* @param _cType Bytes32 representation of the collateral type
* @param _collateral Address of the ERC20 collateral token
* @param _collateralJoin Address of the deployed CollateralJoin contract
*/
event DeployCollateralJoin(bytes32 indexed _cType, address indexed _collateral, address indexed _collateralJoin);
/**
* @notice Emitted when a CollateralJoin contract is disabled
* @param _collateralJoin Address of the disabled CollateralJoin contract
*/
event DisableCollateralJoin(address indexed _collateralJoin);
// --- Errors ---
/// @notice Throws when trying to deploy a CollateralJoin contract for an existent collateral type
error CollateralJoinFactory_CollateralJoinExistent();
/// @notice Throws when trying to disable a non-existent CollateralJoin contract
error CollateralJoinFactory_CollateralJoinNonExistent();
// --- Registry ---
/// @notice Address of the SAFEEngine contract
function safeEngine() external view returns (address _safeEngine);
// --- Data ---
/**
* @notice Getter for the address of the CollateralJoin contract associated with a collateral type
* @param _cType Bytes32 representation of the collateral type
* @return _collateralJoin Address of the CollateralJoin contract
*/
function collateralJoins(bytes32 _cType) external view returns (address _collateralJoin);
/**
* @notice Getter for the list of collateral types
* @return _collateralTypesList List of collateral types
*/
function collateralTypesList() external view returns (bytes32[] memory _collateralTypesList);
/**
* @notice Getter for the list of CollateralJoin contracts
* @return _collateralJoinsList List of CollateralJoin contracts
*/
function collateralJoinsList() external view returns (address[] memory _collateralJoinsList);
// --- Methods ---
/**
* @notice Deploys a CollateralJoinChild contract
* @param _cType Bytes32 representation of the collateral type
* @param _collateral Address of the ERC20 collateral token
* @return _collateralJoin Address of the deployed CollateralJoinChild contract
*/
function deployCollateralJoin(bytes32 _cType, address _collateral) external returns (ICollateralJoin _collateralJoin);
/**
* @notice Deploys a CollateralJoinDelegatableChild contract
* @param _cType Bytes32 representation of the collateral type
* @param _collateral Address of the ERC20Votes collateral token
* @param _delegatee Address to whom the deployed child will delegate the voting power to
* @return _collateralJoin Address of the deployed CollateralJoinDelegatableChild contract
*/
function deployDelegatableCollateralJoin(
bytes32 _cType,
address _collateral,
address _delegatee
) external returns (ICollateralJoin _collateralJoin);
/**
* @notice Disables a CollateralJoin contract and removes it from the collateral types list
* @param _cType Bytes32 representation of the collateral type
* @dev Allows the deployment of other CollateralJoin contract for the same collateral type
*/
function disableCollateralJoin(bytes32 _cType) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {IBaseOracle} from '@interfaces/oracles/IBaseOracle.sol';
interface IDelayedOracle is IBaseOracle {
// --- Events ---
/**
* @notice Emitted when the oracle is updated
* @param _newMedian The new median value
* @param _lastUpdateTime The timestamp of the update
*/
event UpdateResult(uint256 _newMedian, uint256 _lastUpdateTime);
// --- Errors ---
/// @notice Throws if the provided price source address is null
error DelayedOracle_NullPriceSource();
/// @notice Throws if the provided delay is null
error DelayedOracle_NullDelay();
/// @notice Throws when trying to update the oracle before the delay has elapsed
error DelayedOracle_DelayHasNotElapsed();
/// @notice Throws when trying to read the current value and it is invalid
error DelayedOracle_NoCurrentValue();
// --- Structs ---
struct Feed {
// The value of the price feed
uint256 /* WAD */ value;
// Whether the value is valid or not
bool /* bool */ isValid;
}
/**
* @notice Address of the non-delayed price source
* @dev Assumes that the price source is a valid IBaseOracle
*/
function priceSource() external view returns (IBaseOracle _priceSource);
/**
* @notice The next valid price feed, taking effect at the next updateResult call
* @return _result The value in 18 decimals format of the next price feed
* @return _validity Whether the next price feed is valid or not
*/
function getNextResultWithValidity() external view returns (uint256 _result, bool _validity);
/// @notice The delay in seconds that should elapse between updates
function updateDelay() external view returns (uint256 _updateDelay);
/// @notice The timestamp of the last update
function lastUpdateTime() external view returns (uint256 _lastUpdateTime);
/**
* @notice Indicates if a delay has passed since the last update
* @return _ok Whether the oracle should be updated or not
*/
function shouldUpdate() external view returns (bool _ok);
/**
* @notice Updates the current price with the last next price, and reads the next price feed
* @dev Will revert if the delay since last update has not elapsed
* @return _success Whether the update was successful or not
*/
function updateResult() external returns (bool _success);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {IAuthorizable} from '@interfaces/utils/IAuthorizable.sol';
interface IDisableable is IAuthorizable {
// --- Events ---
/// @notice Emitted when the inheriting contract is disabled
event DisableContract();
// --- Errors ---
/// @notice Throws when trying to call a `whenDisabled` method when the contract is enabled
error ContractIsEnabled();
/// @notice Throws when trying to call a `whenEnabled` method when the contract is disabled
error ContractIsDisabled();
/// @notice Throws when trying to disable a contract that cannot be disabled
error NonDisableable();
// --- Data ---
/**
* @notice Check if the contract is enabled
* @return _contractEnabled True if the contract is enabled
*/
function contractEnabled() external view returns (bool _contractEnabled);
// --- Methods ---
/**
* @notice External method to trigger the contract disablement
* @dev Triggers an internal call to `_onContractDisable` virtual method
*/
function disableContract() external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @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[EIP 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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {IAuthorizable} from '@interfaces/utils/IAuthorizable.sol';
interface IModifiable is IAuthorizable {
// --- Events ---
/// @dev Event topic 1 is always a parameter, topic 2 can be empty (global params)
event ModifyParameters(bytes32 indexed _param, bytes32 indexed _cType, bytes _data);
// --- Errors ---
error UnrecognizedParam();
error UnrecognizedCType();
// --- Administration ---
/**
* @notice Set a new value for a global specific parameter
* @param _param String identifier of the parameter to modify
* @param _data Encoded data to modify the parameter
*/
function modifyParameters(bytes32 _param, bytes memory _data) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {IAuthorizable} from '@interfaces/utils/IAuthorizable.sol';
import {IModifiable} from '@interfaces/utils/IModifiable.sol';
interface IModifiablePerCollateral is IAuthorizable, IModifiable {
// --- Events ---
/**
* @notice Emitted when a new collateral type is registered
* @param _cType Bytes32 representation of the collateral type
*/
event InitializeCollateralType(bytes32 _cType);
// --- Errors ---
error CollateralTypeAlreadyInitialized();
// --- Views ---
/**
* @notice List of all the collateral types registered in the OracleRelayer
* @return __collateralList Array of all the collateral types registered
*/
function collateralList() external view returns (bytes32[] memory __collateralList);
// --- Methods ---
/**
* @notice Register a new collateral type in the SAFEEngine
* @param _cType Collateral type to register
* @param _collateralParams Collateral parameters
*/
function initializeCollateralType(bytes32 _cType, bytes memory _collateralParams) external;
/**
* @notice Set a new value for a collateral specific parameter
* @param _cType String identifier of the collateral to modify
* @param _param String identifier of the parameter to modify
* @param _data Encoded data to modify the parameter
*/
function modifyParameters(bytes32 _cType, bytes32 _param, bytes memory _data) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
interface IODSafeManager {
// --- Events ---
/// @notice Emitted when calling allowSAFE with the sender address and the method arguments
event AllowSAFE(address indexed _sender, uint256 indexed _safe, address _usr, bool _ok);
/// @notice Emitted when calling transferSAFEOwnership with the sender address and the method arguments
event TransferSAFEOwnership(address indexed _sender, uint256 indexed _safe, address _dst);
/// @notice Emitted when calling openSAFE with the sender address and the method arguments
event OpenSAFE(address indexed _sender, address indexed _own, uint256 indexed _safe);
/// @notice Emitted when calling modifySAFECollateralization with the sender address and the method arguments
event ModifySAFECollateralization(
address indexed _sender, uint256 indexed _safe, int256 _deltaCollateral, int256 _deltaDebt
);
/// @notice Emitted when calling transferCollateral with the sender address and the method arguments
event TransferCollateral(address indexed _sender, uint256 indexed _safe, address _dst, uint256 _wad);
/// @notice Emitted when calling transferCollateral (specifying cType) with the sender address and the method arguments
event TransferCollateral(address indexed _sender, bytes32 _cType, uint256 indexed _safe, address _dst, uint256 _wad);
/// @notice Emitted when calling transferInternalCoins with the sender address and the method arguments
event TransferInternalCoins(address indexed _sender, uint256 indexed _safe, address _dst, uint256 _rad);
/// @notice Emitted when calling quitSystem with the sender address and the method arguments
event QuitSystem(address indexed _sender, uint256 indexed _safe, address _dst);
/// @notice Emitted when calling moveSAFE with the sender address and the method arguments
event MoveSAFE(address indexed _sender, uint256 indexed _safeSrc, uint256 indexed _safeDst);
/// @notice Emitted when calling protectSAFE with the sender address and the method arguments
event ProtectSAFE(address indexed _sender, uint256 indexed _safe, address _liquidationEngine, address _saviour);
// --- Errors ---
/// @notice Throws if the provided address is null
error ZeroAddress();
/// @notice Throws when trying to call a function not allowed for a given safe
error SafeNotAllowed();
/// @notice Throws when trying to call a function not allowed for a given handler
error HandlerNotAllowed();
/// @notice Throws when trying to transfer safe ownership to the current owner
error AlreadySafeOwner();
/// @notice Throws when trying to move a safe to another one with different collateral type
error CollateralTypesMismatch();
/// @notice Throws when trying to transfer collateral to an address that isn't a SAFEHandler
error HandlerDoesNotExist();
/// @notice Throws if anyone except the safe owner tries to call a function
error OnlySafeOwner();
// --- Structs ---
struct SAFEData {
// The current nonce of the safe - incremented each time it is transferred
uint96 nonce;
// Address of the safe owner
address owner;
// Address of the safe handler
address safeHandler;
// Collateral type of the safe
bytes32 collateralType;
}
// --- Data ---
/// @notice Address of the SAFEEngine
function safeEngine() external view returns (address _safeEngine);
/// @notice Mapping of owner and safe permissions to a caller permissions
function safeCan(
address _owner,
uint256 _safeId,
uint96 _safeNonce,
address _caller
) external view returns (bool _ok);
/// @notice Mapping of handler to the safeId
function safeHandlerToSafeId(address _safeHandler) external view returns (uint256 _safeId);
// --- Getters ---
/**
* @notice Getter for the list of safes owned by a user
* @param _usr Address of the user
* @return _safes List of safe ids owned by the user
*/
function getSafes(address _usr) external view returns (uint256[] memory _safes);
/**
* @notice Getter for the list of safes owned by a user for a given collateral type
* @param _usr Address of the user
* @param _cType Bytes32 representation of the collateral type
* @return _safes List of safe ids owned by the user for the given collateral type
*/
function getSafes(address _usr, bytes32 _cType) external view returns (uint256[] memory _safes);
/**
* @notice Getter for the details of the safes owned by a user
* @param _usr Address of the user
* @return _safes List of safe ids owned by the user
* @return _safeHandlers List of safe handlers addresses owned by the user
* @return _cTypes List of collateral types of the safes owned by the user
*/
function getSafesData(address _usr)
external
view
returns (uint256[] memory _safes, address[] memory _safeHandlers, bytes32[] memory _cTypes);
/**
* @notice Getter for the details of the safe given a handler address
* @param _handler Address of the handler
* @return _sData Struct with the safe data
*/
function getSafeDataFromHandler(address _handler) external view returns (SAFEData memory _sData);
/**
* @notice Getter for the details of a SAFE
* @param _safe Id of the SAFE
* @return _sData Struct with the safe data
*/
function safeData(uint256 _safe) external view returns (SAFEData memory _sData);
// --- Methods ---
/**
* @notice Allow/disallow a user address to manage the safe
* @param _safe Id of the SAFE
* @param _usr Address of the user to allow/disallow
* @param _ok Boolean state to allow/disallow
*/
function allowSAFE(uint256 _safe, address _usr, bool _ok) external;
/**
* @notice Open a new safe for a user address
* @param _cType Bytes32 representation of the collateral type
* @param _usr Address of the user to open the safe for
* @return _id Id of the new SAFE
*/
function openSAFE(bytes32 _cType, address _usr) external returns (uint256 _id);
/**
* @notice Transfer the ownership of a safe to a dst address
* @param _safe Id of the SAFE
* @param _dst Address of the dst address
*/
function transferSAFEOwnership(uint256 _safe, address _dst) external;
/**
* @notice Modify a SAFE's collateralization ratio while keeping the generated COIN or collateral freed in the safe handler address
* @param _safe Id of the SAFE
* @param _deltaCollateral Delta of collateral to add/remove [wad]
* @param _deltaDebt Delta of debt to add/remove [wad]
* @param _nonSafeHandlerAddress Boolean flag to specify whether to not to use the safe handler address, if true, then we use proxy address
*/
function modifySAFECollateralization(
uint256 _safe,
int256 _deltaCollateral,
int256 _deltaDebt,
bool _nonSafeHandlerAddress
) external;
/**
* @notice Transfer wad amount of safe collateral from the safe address to a dst address
* @param _safe Id of the SAFE
* @param _dst Address of the dst address
* @param _wad Amount of collateral to transfer [wad]
*/
function transferCollateral(uint256 _safe, address _dst, uint256 _wad) external;
/**
* @notice Transfer wad amount of any type of collateral from the safe address to a dst address
* @param _cType Bytes32 representation of the collateral type
* @param _safe Id of the SAFE
* @param _dst Address of the dst address
* @param _wad Amount of collateral to transfer [wad]
* @dev This function has the purpose to take away collateral from the system that doesn't correspond to the safe but was sent there wrongly.
*/
function transferCollateral(bytes32 _cType, uint256 _safe, address _dst, uint256 _wad) external;
/**
* @notice Transfer an amount of COIN from the safe address to a dst address [rad]
* @param _safe Id of the SAFE
* @param _dst Address of the dst address
* @param _rad Amount of COIN to transfer [rad]
*/
function transferInternalCoins(uint256 _safe, address _dst, uint256 _rad) external;
/**
* @notice Quit the system, migrating the safe (lockedCollateral, generatedDebt) to the ODProxy address
* @param _safe Id of the SAFE
*/
function quitSystem(uint256 _safe) external;
/**
* @notice Move a position from safeSrc handler to the safeDst handler
* @param _safeSrc Id of the source SAFE
* @param _safeDst Id of the destination SAFE
*/
function moveSAFE(uint256 _safeSrc, uint256 _safeDst) external;
/**
* @notice Add a safe to the user's list of safes (doesn't set safe ownership)
* @param _safe Id of the SAFE
* @dev This function is meant to allow the user to add a safe to their list (if it was previously removed)
*/
function addSAFE(uint256 _safe) external;
/**
* @notice Remove a safe from the user's list of safes (doesn't erase safe ownership)
* @param _safe Id of the SAFE
* @dev This function is meant to allow the user to remove a safe from their list (if it was added against their will)
*/
function removeSAFE(uint256 _safe) external;
/**
* @notice Choose a safe saviour inside LiquidationEngine for the SAFE
* @param _safe Id of the SAFE
* @param _saviour Address of the saviour
*/
function protectSAFE(uint256 _safe, address _saviour) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {IBaseOracle} from '@interfaces/oracles/IBaseOracle.sol';
import {IDelayedOracle} from '@interfaces/oracles/IDelayedOracle.sol';
import {ISAFEEngine} from '@interfaces/ISAFEEngine.sol';
import {IAuthorizable} from '@interfaces/utils/IAuthorizable.sol';
import {IModifiable} from '@interfaces/utils/IModifiable.sol';
import {IModifiablePerCollateral} from '@interfaces/utils/IModifiablePerCollateral.sol';
import {IDisableable} from '@interfaces/utils/IDisableable.sol';
interface IOracleRelayer is IAuthorizable, IDisableable, IModifiable, IModifiablePerCollateral {
// --- Events ---
/**
* @notice Emitted when the redemption price is updated
* @param _redemptionPrice The new redemption price [ray]
*/
event UpdateRedemptionPrice(uint256 _redemptionPrice);
/**
* @notice Emitted when the redemption rate is updated
* @param _redemptionRate The new redemption rate [ray]
*/
event UpdateRedemptionRate(uint256 _redemptionRate);
/**
* @notice Emitted when a collateral type price is updated
* @param _cType Bytes32 representation of the collateral type
* @param _priceFeedValue The new collateral price [wad]
* @param _safetyPrice The new safety price [ray]
* @param _liquidationPrice The new liquidation price [ray]
*/
event UpdateCollateralPrice(
bytes32 indexed _cType, uint256 _priceFeedValue, uint256 _safetyPrice, uint256 _liquidationPrice
);
// --- Errors ---
/// @notice Throws if the redemption price is not updated when updating the rate
error OracleRelayer_RedemptionPriceNotUpdated();
/// @notice Throws when trying to initialize a collateral type that is already initialized
error OracleRelayer_CollateralTypeAlreadyInitialized();
// --- Structs ---
struct OracleRelayerParams {
// Upper bound for the per-second redemption rate
uint256 /* RAY */ redemptionRateUpperBound;
// Lower bound for the per-second redemption rate
uint256 /* RAY */ redemptionRateLowerBound;
}
struct OracleRelayerCollateralParams {
// Usually a DelayedOracle that enforces delays to fresh price feeds
IDelayedOracle /* */ oracle;
// CRatio used to compute the 'safePrice' - the price used when generating debt in SAFEEngine
uint256 /* RAY */ safetyCRatio;
// CRatio used to compute the 'liquidationPrice' - the price used when liquidating SAFEs
uint256 /* RAY */ liquidationCRatio;
}
// --- Registry ---
/**
* @notice The SAFEEngine is called to update the price of the collateral in the system
* @return _safeEngine Address of the contract that handles the state of the SAFEs
*/
function safeEngine() external view returns (ISAFEEngine _safeEngine);
/**
* @notice The oracle used to fetch the system coin market price
* @return _systemCoinOracle Address of the contract that provides the system coin price
*/
function systemCoinOracle() external view returns (IBaseOracle _systemCoinOracle);
// --- Params ---
/**
* @notice Getter for the contract parameters struct
* @dev Returns a OracleRelayerParams struct
*/
function params() external view returns (OracleRelayerParams memory _oracleRelayerParams);
/**
* @notice Getter for the unpacked contract parameters struct
* @param _redemptionRateUpperBound Upper bound for the per-second redemption rate [ray]
* @param _redemptionRateLowerBound Lower bound for the per-second redemption rate [ray]
*/
// solhint-disable-next-line private-vars-leading-underscore
function _params() external view returns (uint256 _redemptionRateUpperBound, uint256 _redemptionRateLowerBound);
/**
* @notice Getter for the collateral parameters struct
* @param _cType Bytes32 representation of the collateral type
* @dev Returns a OracleRelayerCollateralParams struct
*/
function cParams(bytes32 _cType) external view returns (OracleRelayerCollateralParams memory _oracleRelayerCParams);
/**
* @notice Getter for the unpacked collateral parameters struct
* @param _cType Bytes32 representation of the collateral type
* @param _oracle Usually a DelayedOracle that enforces delays to fresh price feeds
* @param _safetyCRatio CRatio used to compute the 'safePrice' - the price used when generating debt in SAFEEngine [ray]
* @param _liquidationCRatio CRatio used to compute the 'liquidationPrice' - the price used when liquidating SAFEs [ray]
*/
// solhint-disable-next-line private-vars-leading-underscore
function _cParams(bytes32 _cType)
external
view
returns (IDelayedOracle _oracle, uint256 _safetyCRatio, uint256 _liquidationCRatio);
// --- Data ---
/**
* @notice View method to fetch the current redemption price
* @return _redemptionPrice The current calculated redemption price [ray]
*/
function calcRedemptionPrice() external view returns (uint256 _redemptionPrice);
/**
* @notice The current system coin market price
* @return _marketPrice The current system coin market price [ray]
*/
function marketPrice() external view returns (uint256 _marketPrice);
/**
* @notice The redemption rate is the rate at which the redemption price changes over time
* @return _redemptionRate The current updated redemption rate [ray]
* @dev By changing the redemption rate, it changes the incentives of the system users
* @dev The redemption rate is a per-second rate [ray]
*/
function redemptionRate() external view returns (uint256 _redemptionRate);
/**
* @notice Last time when the redemption price was changed
* @return _redemptionPriceUpdateTime The last time when the redemption price was changed [unix timestamp]
* @dev Used to calculate the current redemption price
*/
function redemptionPriceUpdateTime() external view returns (uint256 _redemptionPriceUpdateTime);
// --- Methods ---
/**
* @notice Fetch the latest redemption price by first updating it
* @return _updatedPrice The newly updated redemption price [ray]
*/
function redemptionPrice() external returns (uint256 _updatedPrice);
/**
* @notice Update the collateral price inside the system (inside SAFEEngine)
* @dev Usually called by a keeper, incentivized by the system to keep the prices up to date
* @param _cType Bytes32 representation of the collateral type
*/
function updateCollateralPrice(bytes32 _cType) external;
/**
* @notice Update the system redemption rate, the rate at which the redemption price changes over time
* @dev Usually called by the PIDRateSetter
* @param _redemptionRate The newly calculated redemption rate [ray]
*/
function updateRedemptionRate(uint256 _redemptionRate) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {IAuthorizable} from '@interfaces/utils/IAuthorizable.sol';
import {IModifiable} from '@interfaces/utils/IModifiable.sol';
import {IModifiablePerCollateral} from '@interfaces/utils/IModifiablePerCollateral.sol';
import {IDisableable} from '@interfaces/utils/IDisableable.sol';
interface ISAFEEngine is IAuthorizable, IDisableable, IModifiable, IModifiablePerCollateral {
// --- Events ---
/**
* @notice Emitted when an address authorizes another address to modify its SAFE
* @param _sender Address that sent the authorization
* @param _account Address that is authorized to modify the SAFE
*/
event ApproveSAFEModification(address _sender, address _account);
/**
* @notice Emitted when an address denies another address to modify its SAFE
* @param _sender Address that sent the denial
* @param _account Address that is denied to modify the SAFE
*/
event DenySAFEModification(address _sender, address _account);
/**
* @notice Emitted when collateral is transferred between accounts
* @param _cType Bytes32 representation of the collateral type
* @param _src Address that sent the collateral
* @param _dst Address that received the collateral
* @param _wad Amount of collateral transferred
*/
event TransferCollateral(bytes32 indexed _cType, address indexed _src, address indexed _dst, uint256 _wad);
/**
* @notice Emitted when internal coins are transferred between accounts
* @param _src Address that sent the coins
* @param _dst Address that received the coins
* @param _rad Amount of coins transferred
*/
event TransferInternalCoins(address indexed _src, address indexed _dst, uint256 _rad);
/**
* @notice Emitted when the SAFE state is modified by the owner or authorized accounts
* @param _cType Bytes32 representation of the collateral type
* @param _safe Address of the SAFE
* @param _collateralSource Address that sent/receives the collateral
* @param _debtDestination Address that sent/receives the debt
* @param _deltaCollateral Amount of collateral added/extracted from the SAFE [wad]
* @param _deltaDebt Amount of debt to generate/repay [wad]
*/
event ModifySAFECollateralization(
bytes32 indexed _cType,
address indexed _safe,
address _collateralSource,
address _debtDestination,
int256 _deltaCollateral,
int256 _deltaDebt
);
/**
* @notice Emitted when collateral and/or debt is transferred between SAFEs
* @param _cType Bytes32 representation of the collateral type
* @param _src Address that sent the collateral
* @param _dst Address that received the collateral
* @param _deltaCollateral Amount of collateral to take/add into src and give/take from dst [wad]
* @param _deltaDebt Amount of debt to take/add into src and give/take from dst [wad]
*/
event TransferSAFECollateralAndDebt(
bytes32 indexed _cType, address indexed _src, address indexed _dst, int256 _deltaCollateral, int256 _deltaDebt
);
/**
* @notice Emitted when collateral and debt is confiscated from a SAFE
* @param _cType Bytes32 representation of the collateral type
* @param _safe Address of the SAFE
* @param _collateralSource Address that sent/receives the collateral
* @param _debtDestination Address that sent/receives the debt
* @param _deltaCollateral Amount of collateral added/extracted from the SAFE [wad]
* @param _deltaDebt Amount of debt to generate/repay [wad]
*/
event ConfiscateSAFECollateralAndDebt(
bytes32 indexed _cType,
address indexed _safe,
address _collateralSource,
address _debtDestination,
int256 _deltaCollateral,
int256 _deltaDebt
);
/**
* @notice Emitted when an account's debt is settled with coins
* @dev Accounts (not SAFEs) can only settle unbacked debt
* @param _account Address of the account
* @param _rad Amount of debt & coins to destroy
*/
event SettleDebt(address indexed _account, uint256 _rad);
/**
* @notice Emitted when an unbacked debt is created to an account
* @param _debtDestination Address that received the newly created debt
* @param _coinDestination Address that received the newly created coins
* @param _rad Amount of debt to create
*/
event CreateUnbackedDebt(address indexed _debtDestination, address indexed _coinDestination, uint256 _rad);
/**
* @notice Emit when the accumulated rate of a collateral type is updated
* @param _cType Bytes32 representation of the collateral type
* @param _surplusDst Address that received the newly created surplus
* @param _rateMultiplier Delta of the accumulated rate [ray]
*/
event UpdateAccumulatedRate(bytes32 indexed _cType, address _surplusDst, int256 _rateMultiplier);
/**
* @notice Emitted when the safety price and liquidation price of a collateral type is updated
* @param _cType Bytes32 representation of the collateral type
* @param _safetyPrice New price at which a SAFE is allowed to generate debt [ray]
* @param _liquidationPrice New price at which a SAFE gets liquidated [ray]
*/
event UpdateCollateralPrice(bytes32 indexed _cType, uint256 _safetyPrice, uint256 _liquidationPrice);
// --- Errors ---
/// @notice Throws when trying to modify parameters of an uninitialized collateral type
error SAFEEng_CollateralTypeNotInitialized(); // 0xcc8fbb29
/// @notice Throws when trying to modify a SAFE into an unsafe state
error SAFEEng_SAFENotSafe(); // 0x1f441794
/// @notice Throws when trying to modify a SAFE into a dusty safe (debt non-zero and below `debtFloor`)
error SAFEEng_DustySAFE(); // 0xbc8beb5f
/// @notice Throws when trying to generate debt that would put the system over the global debt ceiling
error SAFEEng_GlobalDebtCeilingHit(); // 0x4d0b26ae
/// @notice Throws when trying to generate debt that would put the system over the collateral debt ceiling
error SAFEEng_CollateralDebtCeilingHit(); // 0x787cf02c
/// @notice Throws when trying to generate debt that would put the SAFE over the SAFE debt ceiling
error SAFEEng_SAFEDebtCeilingHit(); // 0x8c77698d
/// @notice Throws when an account tries to modify a SAFE without the proper permissions
error SAFEEng_NotSAFEAllowed(); // 0x4df694a1
/// @notice Throws when an account tries to pull collateral from a SAFE without the proper permissions
error SAFEEng_NotCollateralSrcAllowed(); // 0x3820cfbf
/// @notice Throws when an account tries to push debt to a SAFE without the proper permissions
error SAFEEng_NotDebtDstAllowed(); // 0x62c26e9a
// --- Structs ---
struct SAFE {
// Total amount of collateral locked in a SAFE
uint256 /* WAD */ lockedCollateral;
// Total amount of debt generated by a SAFE
uint256 /* WAD */ generatedDebt;
}
struct SAFEEngineParams {
// Total amount of debt that a single safe can generate
uint256 /* WAD */ safeDebtCeiling;
// Maximum amount of debt that can be issued across all safes
uint256 /* RAD */ globalDebtCeiling;
}
struct SAFEEngineCollateralData {
// Total amount of debt issued by the collateral type
uint256 /* WAD */ debtAmount;
// Total amount of collateral locked in SAFEs using the collateral type
uint256 /* WAD */ lockedAmount;
// Accumulated rate of the collateral type
uint256 /* RAY */ accumulatedRate;
// Floor price at which a SAFE is allowed to generate debt
uint256 /* RAY */ safetyPrice;
// Price at which a SAFE gets liquidated
uint256 /* RAY */ liquidationPrice;
}
struct SAFEEngineCollateralParams {
// Maximum amount of debt that can be generated with the collateral type
uint256 /* RAD */ debtCeiling;
// Minimum amount of debt that must be generated by a SAFE using the collateral
uint256 /* RAD */ debtFloor;
}
// --- Data ---
/**
* @notice Getter for the contract parameters struct
* @dev Returns a SAFEEngineParams struct
*/
function params() external view returns (SAFEEngineParams memory _safeEngineParams);
/**
* @notice Getter for the unpacked contract parameters struct
* @return _safeDebtCeiling Total amount of debt that a single safe can generate [wad]
* @return _globalDebtCeiling Maximum amount of debt that can be issued [rad]
*/
// solhint-disable-next-line private-vars-leading-underscore
function _params() external view returns (uint256 _safeDebtCeiling, uint256 _globalDebtCeiling);
/**
* @notice Getter for the collateral parameters struct
* @param _cType Bytes32 representation of the collateral type
* @dev Returns a SAFEEngineCollateralParams struct
*/
function cParams(bytes32 _cType) external view returns (SAFEEngineCollateralParams memory _safeEngineCParams);
/**
* @notice Getter for the unpacked collateral parameters struct
* @param _cType Bytes32 representation of the collateral type
* @return _debtCeiling Maximum amount of debt that can be generated with this collateral type
* @return _debtFloor Minimum amount of debt that must be generated by a SAFE using this collateral
*/
// solhint-disable-next-line private-vars-leading-underscore
function _cParams(bytes32 _cType) external view returns (uint256 _debtCeiling, uint256 _debtFloor);
/**
* @notice Getter for the collateral data struct
* @param _cType Bytes32 representation of the collateral type
* @dev Returns a SAFEEngineCollateralData struct
*/
function cData(bytes32 _cType) external view returns (SAFEEngineCollateralData memory _safeEngineCData);
/**
* @notice Getter for the address of the safe manager
* @return _safeManager Address of safe manager
*/
function odSafeManager() external view returns (address _safeManager);
/**
* @notice Getter for the unpacked collateral data struct
* @param _cType Bytes32 representation of the collateral type
* @return _debtAmount Total amount of debt issued by a collateral type [wad]
* @return _lockedAmount Total amount of collateral locked in all SAFEs of the collateral type [wad]
* @return _accumulatedRate Accumulated rate of a collateral type [ray]
* @return _safetyPrice Floor price at which a SAFE is allowed to generate debt [ray]
* @return _liquidationPrice Price at which a SAFE gets liquidated [ray]
*/
// solhint-disable-next-line private-vars-leading-underscore
function _cData(bytes32 _cType)
external
view
returns (
uint256 _debtAmount,
uint256 _lockedAmount,
uint256 _accumulatedRate,
uint256 _safetyPrice,
uint256 _liquidationPrice
);
/**
* @notice Data about each SAFE
* @param _cType Bytes32 representation of the collateral type
* @param _safeAddress Address of the SAFE
* @dev Returns a SAFE struct
*/
function safes(bytes32 _cType, address _safeAddress) external view returns (SAFE memory _safeData);
/**
* @notice Unpacked data about each SAFE
* @param _cType Bytes32 representation of the collateral type
* @param _safeAddress Address of the SAFE
* @return _lockedCollateral Total amount of collateral locked in a SAFE [wad]
* @return _generatedDebt Total amount of debt generated by a SAFE [wad]
*/
// solhint-disable-next-line private-vars-leading-underscore
function _safes(
bytes32 _cType,
address _safeAddress
) external view returns (uint256 _lockedCollateral, uint256 _generatedDebt);
/**
* @notice Who can transfer collateral & debt in/out of a SAFE
* @param _caller Address to check for SAFE permissions for
* @param _account Account to check if caller has permissions for
* @return _safeRights Numerical representation of the SAFE rights (0/1)
*/
function safeRights(address _caller, address _account) external view returns (uint256 _safeRights);
// --- Balances ---
/**
* @notice Balance of each collateral type
* @param _cType Bytes32 representation of the collateral type to check balance for
* @param _account Account to check balance for
* @return _collateralBalance Collateral balance of the account [wad]
*/
function tokenCollateral(bytes32 _cType, address _account) external view returns (uint256 _collateralBalance);
/**
* @notice Internal balance of system coins held by an account
* @param _account Account to check balance for
* @return _balance Internal coin balance of the account [rad]
*/
function coinBalance(address _account) external view returns (uint256 _balance);
/**
* @notice Amount of debt held by an account
* @param _account Account to check balance for
* @return _debtBalance Debt balance of the account [rad]
*/
function debtBalance(address _account) external view returns (uint256 _debtBalance);
/**
* @notice Total amount of debt (coins) currently issued
* @dev Returns the global debt [rad]
*/
function globalDebt() external returns (uint256 _globalDebt);
/**
* @notice 'Bad' debt that's not covered by collateral
* @dev Returns the global unbacked debt [rad]
*/
function globalUnbackedDebt() external view returns (uint256 _globalUnbackedDebt);
// --- Init ---
// --- Fungibility ---
/**
* @notice Transfer collateral between accounts
* @param _cType Collateral type transferred
* @param _source Collateral source
* @param _destination Collateral destination
* @param _wad Amount of collateral transferred
*/
function transferCollateral(bytes32 _cType, address _source, address _destination, uint256 _wad) external;
/**
* @notice Transfer internal coins (does not affect external balances from Coin.sol)
* @param _source Coins source
* @param _destination Coins destination
* @param _rad Amount of coins transferred
*/
function transferInternalCoins(address _source, address _destination, uint256 _rad) external;
/**
* @notice Join/exit collateral into and and out of the system
* @param _cType Collateral type to join/exit
* @param _account Account that gets credited/debited
* @param _wad Amount of collateral
*/
function modifyCollateralBalance(bytes32 _cType, address _account, int256 _wad) external;
// --- SAFE Manipulation ---
/**
* @notice Add/remove collateral or put back/generate more debt in a SAFE
* @param _cType Type of collateral to withdraw/deposit in and from the SAFE
* @param _safe Target SAFE
* @param _collateralSource Account we take collateral from/put collateral into
* @param _debtDestination Account from which we credit/debit coins and debt
* @param _deltaCollateral Amount of collateral added/extracted from the SAFE [wad]
* @param _deltaDebt Amount of debt to generate/repay [wad]
*/
function modifySAFECollateralization(
bytes32 _cType,
address _safe,
address _collateralSource,
address _debtDestination,
int256 /* WAD */ _deltaCollateral,
int256 /* WAD */ _deltaDebt
) external;
// --- SAFE Fungibility ---
/**
* @notice Transfer collateral and/or debt between SAFEs
* @param _cType Collateral type transferred between SAFEs
* @param _src Source SAFE
* @param _dst Destination SAFE
* @param _deltaCollateral Amount of collateral to take/add into src and give/take from dst [wad]
* @param _deltaDebt Amount of debt to take/add into src and give/take from dst [wad]
*/
function transferSAFECollateralAndDebt(
bytes32 _cType,
address _src,
address _dst,
int256 /* WAD */ _deltaCollateral,
int256 /* WAD */ _deltaDebt
) external;
// --- SAFE Confiscation ---
/**
* @notice Normally used by the LiquidationEngine in order to confiscate collateral and
* debt from a SAFE and give them to someone else
* @param _cType Collateral type the SAFE has locked inside
* @param _safe Target SAFE
* @param _collateralSource Who we take/give collateral to
* @param _debtDestination Who we take/give debt to
* @param _deltaCollateral Amount of collateral taken/added into the SAFE [wad]
* @param _deltaDebt Amount of debt taken/added into the SAFE [wad]
*/
function confiscateSAFECollateralAndDebt(
bytes32 _cType,
address _safe,
address _collateralSource,
address _debtDestination,
int256 _deltaCollateral,
int256 _deltaDebt
) external;
// --- Settlement ---
/**
* @notice Nullify an amount of coins with an equal amount of debt
* @dev Coins & debt are like matter and antimatter, they nullify each other
* @param _rad Amount of debt & coins to destroy
*/
function settleDebt(uint256 _rad) external;
/**
* @notice Allows an authorized contract to create debt without collateral
* @param _debtDestination The account that will receive the newly created debt
* @param _coinDestination The account that will receive the newly created coins
* @param _rad Amount of debt to create
* @dev Usually called by DebtAuctionHouse in order to terminate auctions prematurely post settlement
*/
function createUnbackedDebt(address _debtDestination, address _coinDestination, uint256 _rad) external;
// --- Update ---
/**
* @notice Allows an authorized contract to accrue interest on a specific collateral type
* @param _cType Collateral type we accrue interest for
* @param _surplusDst Destination for the newly created surplus
* @param _rateMultiplier Multiplier applied to the debtAmount in order to calculate the surplus [ray]
* @dev The rateMultiplier is usually calculated by the TaxCollector contract
*/
function updateAccumulatedRate(bytes32 _cType, address _surplusDst, int256 _rateMultiplier) external;
/**
* @notice Allows an authorized contract to update the safety price and liquidation price of a collateral type
* @param _cType Collateral type we update the prices for
* @param _safetyPrice New safety price [ray]
* @param _liquidationPrice New liquidation price [ray]
*/
function updateCollateralPrice(bytes32 _cType, uint256 _safetyPrice, uint256 _liquidationPrice) external;
// --- Authorization ---
/**
* @notice Allow an address to modify your SAFE
* @param _account Account to give SAFE permissions to
*/
function approveSAFEModification(address _account) external;
/**
* @notice Deny an address the rights to modify your SAFE
* @param _account Account that is denied SAFE permissions
*/
function denySAFEModification(address _account) external;
/**
* @notice Checks whether msg.sender has the right to modify a SAFE
*/
function canModifySAFE(address _safe, address _account) external view returns (bool _allowed);
/**
* @notice called by ODSafeManager during deployment
*/
function initializeSafeManager() external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {ISAFEEngine} from '@interfaces/ISAFEEngine.sol';
import {IAuthorizable} from '@interfaces/utils/IAuthorizable.sol';
import {IModifiablePerCollateral} from '@interfaces/utils/IModifiablePerCollateral.sol';
import {IModifiable} from '@interfaces/utils/IModifiable.sol';
interface ITaxCollector is IAuthorizable, IModifiable, IModifiablePerCollateral {
// --- Events ---
/**
* @notice Emitted when a new primary tax receiver is set
* @param _cType Bytes32 representation of the collateral type
* @param _receiver Address of the new primary tax receiver
*/
event SetPrimaryReceiver(bytes32 indexed _cType, address indexed _receiver);
/**
* @notice Emitted when a new secondary tax receiver is set
* @param _cType Bytes32 representation of the collateral type
* @param _receiver Address of the new secondary tax receiver
* @param _taxPercentage Percentage of SF allocated to this receiver
* @param _canTakeBackTax Whether this receiver can accept a negative rate (taking SF from it)
* @dev (taxPercentage, canTakeBackTax) = (0, false) means that the receiver is removed
*/
event SetSecondaryReceiver(
bytes32 indexed _cType, address indexed _receiver, uint256 _taxPercentage, bool _canTakeBackTax
);
/**
* @notice Emitted once when a collateral type taxation is processed
* @param _cType Bytes32 representation of the collateral type
* @param _latestAccumulatedRate The newly accumulated rate
* @param _deltaRate The delta between the new and the last accumulated rates
*/
event CollectTax(bytes32 indexed _cType, uint256 _latestAccumulatedRate, int256 _deltaRate);
/**
* @notice Emitted when a collateral type taxation is distributed (one event per receiver)
* @param _cType Bytes32 representation of the collateral type
* @param _target Address of the tax receiver
* @param _taxCut Amount of SF collected for this receiver
* @dev SF can be negative if the receiver can take back tax
*/
event DistributeTax(bytes32 indexed _cType, address indexed _target, int256 _taxCut);
// --- Errors ---
/// @notice Throws when inputting an invalid index for the collateral type list
error TaxCollector_InvalidIndexes();
/// @notice Throws when trying to add a null address as a tax receiver
error TaxCollector_NullAccount();
/// @notice Throws when trying to add a tax receiver that is already the primary receiver
error TaxCollector_PrimaryReceiverCannotBeSecondary();
/// @notice Throws when trying to modify parameters for a collateral type that is not initialized
error TaxCollector_CollateralTypeNotInitialized();
/// @notice Throws when trying to add a tax receiver that would surpass the max number of receivers
error TaxCollector_ExceedsMaxReceiverLimit();
/// @notice Throws when trying to collect tax for a receiver with null tax percentage
error TaxCollector_NullSF();
/// @notice Throws when trying to add a receiver such that the total tax percentage would surpass 100%
error TaxCollector_TaxCutExceedsHundred();
/// @notice Throws when trying to modify a receiver such that the total tax percentage would surpass 100%
error TaxCollector_TaxCutTooBig();
// --- Structs ---
struct TaxCollectorParams {
// Address of the primary tax receiver
address /* */ primaryTaxReceiver;
// Global stability fee
uint256 /* RAY */ globalStabilityFee;
// Max stability fee range of variation
uint256 /* RAY */ maxStabilityFeeRange;
// Max number of secondary tax receivers
uint256 /* */ maxSecondaryReceivers;
}
struct TaxCollectorCollateralParams {
// Per collateral stability fee
uint256 /* RAY */ stabilityFee;
}
struct TaxCollectorCollateralData {
// Per second borrow rate for this specific collateral type to be applied at the next taxation
uint256 /* RAY */ nextStabilityFee;
// When Stability Fee was last collected for this collateral type
uint256 /* unix */ updateTime;
// Percentage of each collateral's SF that goes to other addresses apart from the primary receiver
uint256 /* WAD % */ secondaryReceiverAllotedTax;
}
struct TaxReceiver {
address receiver;
// Whether this receiver can accept a negative rate (taking SF from it)
bool /* bool */ canTakeBackTax;
// Percentage of SF allocated to this receiver
uint256 /* WAD % */ taxPercentage;
}
// --- Data ---
/**
* @notice Getter for the contract parameters struct
* @return _taxCollectorParams Tax collector parameters struct
*/
function params() external view returns (TaxCollectorParams memory _taxCollectorParams);
/**
* @notice Getter for the unpacked contract parameters struct
* @return _primaryTaxReceiver Primary tax receiver address
* @return _globalStabilityFee Global stability fee [ray]
* @return _maxStabilityFeeRange Max stability fee range [ray]
* @return _maxSecondaryReceivers Max number of secondary tax receivers
*/
// solhint-disable-next-line private-vars-leading-underscore
function _params()
external
view
returns (
address _primaryTaxReceiver,
uint256 _globalStabilityFee,
uint256 _maxStabilityFeeRange,
uint256 _maxSecondaryReceivers
);
/**
* @notice Getter for the collateral parameters struct
* @param _cType Bytes32 representation of the collateral type
* @return _taxCollectorCParams Tax collector collateral parameters struct
*/
function cParams(bytes32 _cType) external view returns (TaxCollectorCollateralParams memory _taxCollectorCParams);
/**
* @notice Getter for the unpacked collateral parameters struct
* @param _cType Bytes32 representation of the collateral type
* @return _stabilityFee Stability fee [ray]
*/
// solhint-disable-next-line private-vars-leading-underscore
function _cParams(bytes32 _cType) external view returns (uint256 _stabilityFee);
/**
* @notice Getter for the collateral data struct
* @param _cType Bytes32 representation of the collateral type
* @return _taxCollectorCData Tax collector collateral data struct
*/
function cData(bytes32 _cType) external view returns (TaxCollectorCollateralData memory _taxCollectorCData);
/**
* @notice Getter for the unpacked collateral data struct
* @param _cType Bytes32 representation of the collateral type
* @return _nextStabilityFee Per second borrow rate to be applied at the next taxation [ray]
* @return _updateTime When Stability Fee was last collected
* @return _secondaryReceiverAllotedTax Percentage of SF that goes to other addresses apart from the primary receiver
*/
// solhint-disable-next-line private-vars-leading-underscore
function _cData(bytes32 _cType)
external
view
returns (uint256 _nextStabilityFee, uint256 _updateTime, uint256 _secondaryReceiverAllotedTax);
/**
* @notice Getter for the data about a specific secondary tax receiver
* @param _cType Bytes32 representation of the collateral type
* @param _receiver Tax receiver address to check
* @return _secondaryTaxReceiver Tax receiver struct
*/
function secondaryTaxReceivers(
bytes32 _cType,
address _receiver
) external view returns (TaxReceiver memory _secondaryTaxReceiver);
/**
* @notice Getter for the unpacked data about a specific secondary tax receiver
* @param _cType Bytes32 representation of the collateral type
* @param _receiver Tax receiver address to check
* @return _secondaryReceiver Secondary tax receiver address
* @return _canTakeBackTax Whether this receiver can accept a negative rate (taking SF from it)
* @return _taxPercentage Percentage of SF allocated to this receiver
*/
// solhint-disable-next-line private-vars-leading-underscore
function _secondaryTaxReceivers(
bytes32 _cType,
address _receiver
) external view returns (address _secondaryReceiver, bool _canTakeBackTax, uint256 _taxPercentage);
/// @notice Address of the SAFEEngine contract
function safeEngine() external view returns (ISAFEEngine _safeEngine);
// --- Administration ---
// --- Tax Collection Utils ---
/**
* @notice Check if multiple collateral types are up to date with taxation
* @param _start Index of the first collateral type to check
* @param _end Index of the last collateral type to check
* @return _ok Whether all collateral types are up to date
*/
function collectedManyTax(uint256 _start, uint256 _end) external view returns (bool _ok);
/**
* @notice Check how much SF will be charged (to collateral types between indexes 'start' and 'end'
* in the collateralList) during the next taxation
* @param _start Index in collateralList from which to start looping and calculating the tax outcome
* @param _end Index in collateralList at which we stop looping and calculating the tax outcome
* @return _ok Whether the tax outcome can be computed
* @return _rad The total amount of SF that will be charged during the next taxation
*/
function taxManyOutcome(uint256 _start, uint256 _end) external view returns (bool _ok, int256 _rad);
/**
* @notice Get how much SF will be distributed after taxing a specific collateral type
* @param _cType Collateral type to compute the taxation outcome for
* @return _newlyAccumulatedRate The newly accumulated rate
* @return _deltaRate The delta between the new and the last accumulated rates
*/
function taxSingleOutcome(bytes32 _cType) external view returns (uint256 _newlyAccumulatedRate, int256 _deltaRate);
// --- Tax Receiver Utils ---
/**
* @notice Get the secondary tax receiver list length
*/
function secondaryReceiversListLength() external view returns (uint256 _secondaryReceiversListLength);
/**
* @notice Get the collateralList length
*/
function collateralListLength() external view returns (uint256 _collateralListLength);
/**
* @notice Check if a tax receiver is at a certain position in the list
* @param _receiver Tax receiver address to check
* @return _isSecondaryReceiver Whether the tax receiver for at least one collateral type
*/
function isSecondaryReceiver(address _receiver) external view returns (bool _isSecondaryReceiver);
// --- Views ---
/// @notice Get the list of all secondary tax receivers
function secondaryReceiversList() external view returns (address[] memory _secondaryReceiversList);
/**
* @notice Get the list of all collateral types for which a specific address is a secondary tax receiver
* @param _secondaryReceiver Secondary tax receiver address to check
* @return _secondaryReceiverRevenueSourcesList List of collateral types for which the address is a secondary tax receiver
*/
function secondaryReceiverRevenueSourcesList(address _secondaryReceiver)
external
view
returns (bytes32[] memory _secondaryReceiverRevenueSourcesList);
// --- Tax (Stability Fee) Collection ---
/**
* @notice Collect tax from multiple collateral types at once
* @param _start Index in collateralList from which to start looping and calculating the tax outcome
* @param _end Index in collateralList at which we stop looping and calculating the tax outcome
*/
function taxMany(uint256 _start, uint256 _end) external;
/**
* @notice Collect tax from a single collateral type
* @param _cType Collateral type to tax
* @return _latestAccumulatedRate The newly accumulated rate after taxation
*/
function taxSingle(bytes32 _cType) external returns (uint256 _latestAccumulatedRate);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {IERC721EnumerableUpgradeable} from
'@openzeppelin-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol';
import {IODSafeManager} from '@interfaces/proxies/IODSafeManager.sol';
import {NFTRenderer} from '@contracts/proxies/NFTRenderer.sol';
import {IAuthorizable} from '@interfaces/utils/IAuthorizable.sol';
import {IModifiable} from '@interfaces/utils/IModifiable.sol';
interface IVault721 is IERC721EnumerableUpgradeable, IAuthorizable, IModifiable {
// --- Events ---
/**
* @notice Emitted when a new user proxy is built
* @param _user address of the owner of the proxy
* @param _proxy the address of the proxy
*/
event CreateProxy(address indexed _user, address indexed _proxy);
/**
* @notice Emitted when an nfv vault state is update.
* @param _vaultId the uint256 ID of the vault whos state was modified
*/
event NFVStateUpdated(uint256 _vaultId);
// --- Errors ---
/// @notice Throws if an address other than the safe manager tries to call a onlySafeManager function
error NotSafeManager();
/// @notice throws if a proxy tries to create another proxy
error NotWallet();
/// @notice throws if an address attempts to build a second proxy
error ProxyAlreadyExist();
/// @notice throws if a vault is attempted to be transferred before the block delay is over
error BlockDelayNotOver();
/// @notice throws if a vault is attempted to be transferred before the time delay is over
error TimeDelayNotOver();
/// @notice throws if zero address is passed as a param
error ZeroAddress();
/// @notice throws if the nfv state is altered before a transfer
error StateViolation();
// --- Struct ---
struct NFVState {
/// the vault's collateral type
bytes32 cType;
/// the collateral balance of the vault
uint256 collateral;
/// the debt generated by the vault
uint256 debt;
/// the block number of the last change in the vault
uint256 lastBlockNumber;
/// the time stamp of the last recorded change
uint256 lastBlockTimestamp;
/// the vault's safe handler address
address safeHandler;
}
/**
* @dev initializes DAO timelockController contract
*/
function initialize(address _timelockController, uint256 _blockDelay, uint256 _timeDelay) external;
/**
* @dev initializes SafeManager contract
*/
function initializeManager() external;
/**
* @dev initializes NFTRenderer contract
*/
function initializeRenderer() external;
// --- Registry ---
/**
* @notice The timelockController is the governance contract with permissions to update params
* @return _timelockController address of the timelock controller
*/
function timelockController() external returns (address _timelockController);
/**
* @notice The safe manager calls mint and other functions on this contract and is used to get safe data for the vault hash
* @return _safeManager safeManager address handles permissions and safe state
*/
function safeManager() external returns (IODSafeManager _safeManager);
/**
* @notice The nftRenderer creates the tokenURI and is used in the vaultHashState
* @return _nftRenderer address of NFTrenderer
*/
function nftRenderer() external returns (NFTRenderer _nftRenderer);
// --- Params ---
/**
* @notice The block delay is the enforced number of blocks between the last change of a vault and when vault ownership can be transfered
* @return blockDelay
*/
function blockDelay() external returns (uint256);
/**
* @notice The time delay is the enforced amount of time between the last change of a vault and when vault ownership can be transfered
* @return blockDelay
*/
function timeDelay() external returns (uint256);
// --- Data ---
/**
* @notice The contract metadata is the prefix used when calculating the contractUri
* @return contractMetadata
*/
function contractMetaData() external returns (string memory);
/**
* @dev get proxy by user address
*/
function getProxy(address _user) external view returns (address);
/**
* @dev get nfv state by vault id
*/
function getNfvState(uint256 _vaultId) external view returns (NFVState memory);
/**
* @dev has this user been allow listed? this function will tell you.
* @return bool false if not allow listed, true if they are indeed allow listed.
*/
function getIsAllowlisted(address _user) external view returns (bool);
// --- Methods ---
/**
* @dev allows msg.sender without an ODProxy to deploy a new ODProxy
*/
function build() external returns (address payable);
/**
* @dev allows user without an ODProxy to deploy a new ODProxy
*/
function build(address _user) external returns (address payable);
/**
* @dev allows user to deploy proxies for multiple users
* @param _users array of user addresses
* @return _proxies array of proxy addresses
*/
function build(address[] memory _users) external returns (address payable[] memory _proxies);
/**
* @dev mint can only be called by the SafeManager
* enforces that only ODProxies call `openSafe` function by checking _proxyRegistry
*/
function mint(address proxy, uint256 safeId) external;
/**
* @dev allows ODSafeManager to update the nfv state in nfvState mapping
*/
function updateNfvState(uint256 _vaultId) external;
/**
* @dev contract level meta data
*/
function contractURI() external returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @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 Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 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 functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_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 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_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() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @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 {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
/// @dev Max uint256 value that a RAD can represent without overflowing
uint256 constant MAX_RAD = type(uint256).max / RAY;
/// @dev Uint256 representation of 1 RAD
uint256 constant RAD = 10 ** 45;
/// @dev Uint256 representation of 1 RAY
uint256 constant RAY = 10 ** 27;
/// @dev Uint256 representation of 1 WAD
uint256 constant WAD = 10 ** 18;
/// @dev Uint256 representation of 1 year in seconds
uint256 constant YEAR = 365 days;
/// @dev Uint256 representation of 1 hour in seconds
uint256 constant HOUR = 3600;
/**
* @title Math
* @notice This library contains common math functions
*/
library Math {
// --- Errors ---
/// @dev Throws when trying to cast a uint256 to an int256 that overflows
error IntOverflow();
// --- Math ---
/**
* @notice Calculates the sum of an unsigned integer and a signed integer
* @param _x Unsigned integer
* @param _y Signed integer
* @return _add Unsigned sum of `_x` and `_y`
*/
function add(uint256 _x, int256 _y) internal pure returns (uint256 _add) {
if (_y >= 0) {
return _x + uint256(_y);
} else {
return _x - uint256(-_y);
}
}
/**
* @notice Calculates the substraction of an unsigned integer and a signed integer
* @param _x Unsigned integer
* @param _y Signed integer
* @return _sub Unsigned substraction of `_x` and `_y`
*/
function sub(uint256 _x, int256 _y) internal pure returns (uint256 _sub) {
if (_y >= 0) {
return _x - uint256(_y);
} else {
return _x + uint256(-_y);
}
}
/**
* @notice Calculates the substraction of two unsigned integers
* @param _x Unsigned integer
* @param _y Unsigned integer
* @return _sub Signed substraction of `_x` and `_y`
*/
function sub(uint256 _x, uint256 _y) internal pure returns (int256 _sub) {
return toInt(_x) - toInt(_y);
}
/**
* @notice Calculates the multiplication of an unsigned integer and a signed integer
* @param _x Unsigned integer
* @param _y Signed integer
* @return _mul Signed multiplication of `_x` and `_y`
*/
function mul(uint256 _x, int256 _y) internal pure returns (int256 _mul) {
return toInt(_x) * _y;
}
/**
* @notice Calculates the multiplication of two unsigned RAY integers
* @param _x Unsigned RAY integer
* @param _y Unsigned RAY integer
* @return _rmul Unsigned multiplication of `_x` and `_y` in RAY precision
*/
function rmul(uint256 _x, uint256 _y) internal pure returns (uint256 _rmul) {
return (_x * _y) / RAY;
}
/**
* @notice Calculates the multiplication of an unsigned and a signed RAY integers
* @param _x Unsigned RAY integer
* @param _y Signed RAY integer
* @return _rmul Signed multiplication of `_x` and `_y` in RAY precision
*/
function rmul(uint256 _x, int256 _y) internal pure returns (int256 _rmul) {
return (toInt(_x) * _y) / int256(RAY);
}
/**
* @notice Calculates the multiplication of two unsigned WAD integers
* @param _x Unsigned WAD integer
* @param _y Unsigned WAD integer
* @return _wmul Unsigned multiplication of `_x` and `_y` in WAD precision
*/
function wmul(uint256 _x, uint256 _y) internal pure returns (uint256 _wmul) {
return (_x * _y) / WAD;
}
/**
* @notice Calculates the multiplication of an unsigned and a signed WAD integers
* @param _x Unsigned WAD integer
* @param _y Signed WAD integer
* @return _wmul Signed multiplication of `_x` and `_y` in WAD precision
*/
function wmul(uint256 _x, int256 _y) internal pure returns (int256 _wmul) {
return (toInt(_x) * _y) / int256(WAD);
}
/**
* @notice Calculates the multiplication of two signed WAD integers
* @param _x Signed WAD integer
* @param _y Signed WAD integer
* @return _wmul Signed multiplication of `_x` and `_y` in WAD precision
*/
function wmul(int256 _x, int256 _y) internal pure returns (int256 _wmul) {
return (_x * _y) / int256(WAD);
}
/**
* @notice Calculates the division of two unsigned RAY integers
* @param _x Unsigned RAY integer
* @param _y Unsigned RAY integer
* @return _rdiv Unsigned division of `_x` by `_y` in RAY precision
*/
function rdiv(uint256 _x, uint256 _y) internal pure returns (uint256 _rdiv) {
return (_x * RAY) / _y;
}
/**
* @notice Calculates the division of two signed RAY integers
* @param _x Signed RAY integer
* @param _y Signed RAY integer
* @return _rdiv Signed division of `_x` by `_y` in RAY precision
*/
function rdiv(int256 _x, int256 _y) internal pure returns (int256 _rdiv) {
return (_x * int256(RAY)) / _y;
}
/**
* @notice Calculates the division of two unsigned WAD integers
* @param _x Unsigned WAD integer
* @param _y Unsigned WAD integer
* @return _wdiv Unsigned division of `_x` by `_y` in WAD precision
*/
function wdiv(uint256 _x, uint256 _y) internal pure returns (uint256 _wdiv) {
return (_x * WAD) / _y;
}
/**
* @notice Calculates the power of an unsigned RAY integer to an unsigned integer
* @param _x Unsigned RAY integer
* @param _n Unsigned integer exponent
* @return _rpow Unsigned `_x` to the power of `_n` in RAY precision
*/
function rpow(uint256 _x, uint256 _n) internal pure returns (uint256 _rpow) {
assembly {
switch _x
case 0 {
switch _n
case 0 { _rpow := RAY }
default { _rpow := 0 }
}
default {
switch mod(_n, 2)
case 0 { _rpow := RAY }
default { _rpow := _x }
let half := div(RAY, 2) // for rounding.
for { _n := div(_n, 2) } _n { _n := div(_n, 2) } {
let _xx := mul(_x, _x)
if iszero(eq(div(_xx, _x), _x)) { revert(0, 0) }
let _xxRound := add(_xx, half)
if lt(_xxRound, _xx) { revert(0, 0) }
_x := div(_xxRound, RAY)
if mod(_n, 2) {
let _zx := mul(_rpow, _x)
if and(iszero(iszero(_x)), iszero(eq(div(_zx, _x), _rpow))) { revert(0, 0) }
let _zxRound := add(_zx, half)
if lt(_zxRound, _zx) { revert(0, 0) }
_rpow := div(_zxRound, RAY)
}
}
}
}
}
/**
* @notice Calculates the maximum of two unsigned integers
* @param _x Unsigned integer
* @param _y Unsigned integer
* @return _max Unsigned maximum of `_x` and `_y`
*/
function max(uint256 _x, uint256 _y) internal pure returns (uint256 _max) {
_max = (_x >= _y) ? _x : _y;
}
/**
* @notice Calculates the minimum of two unsigned integers
* @param _x Unsigned integer
* @param _y Unsigned integer
* @return _min Unsigned minimum of `_x` and `_y`
*/
function min(uint256 _x, uint256 _y) internal pure returns (uint256 _min) {
_min = (_x <= _y) ? _x : _y;
}
/**
* @notice Casts an unsigned integer to a signed integer
* @param _x Unsigned integer
* @return _int Signed integer
* @dev Throws if `_x` is too large to fit in an int256
*/
function toInt(uint256 _x) internal pure returns (int256 _int) {
_int = int256(_x);
if (_int < 0) revert IntOverflow();
}
// --- PI Specific Math ---
/**
* @notice Calculates the Riemann sum of two signed integers
* @param _x Signed integer
* @param _y Signed integer
* @return _riemannSum Riemann sum of `_x` and `_y`
*/
function riemannSum(int256 _x, int256 _y) internal pure returns (int256 _riemannSum) {
return (_x + _y) / 2;
}
/**
* @notice Calculates the absolute value of a signed integer
* @param _x Signed integer
* @return _z Unsigned absolute value of `_x`
*/
function absolute(int256 _x) internal pure returns (uint256 _z) {
_z = (_x < 0) ? uint256(-_x) : uint256(_x);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return 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) {
// (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 up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev 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 {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 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 prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, 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.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
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^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// 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^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice 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) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* 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 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {IModifiable} from '@interfaces/utils/IModifiable.sol';
import {Authorizable} from '@contracts/utils/Authorizable.sol';
/**
* @title Modifiable
* @notice Allows inheriting contracts to modify parameters values
* @dev Requires inheriting contracts to override `_modifyParameters` virtual methods
*/
abstract contract Modifiable is Authorizable, IModifiable {
// --- Constants ---
/// @dev Used to emit a global parameter modification event
bytes32 internal constant _GLOBAL_PARAM = bytes32(0);
// --- External methods ---
/// @inheritdoc IModifiable
function modifyParameters(bytes32 _param, bytes memory _data) external isAuthorized validParams {
emit ModifyParameters(_param, _GLOBAL_PARAM, _data);
_modifyParameters(_param, _data);
}
// --- Internal virtual methods ---
/**
* @notice Internal function to be overriden with custom logic to modify parameters
* @dev This function is set to revert if not overriden
*/
// solhint-disable-next-line no-unused-vars
function _modifyParameters(bytes32 _param, bytes memory _data) internal virtual;
/// @notice Internal function to be overriden with custom logic to validate parameters
function _validateParameters() internal view virtual {}
// --- Modifiers ---
/// @notice Triggers a routine to validate parameters after a modification
modifier validParams() {
_;
_validateParameters();
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {DateTime} from '@libraries/DateTime.sol';
import {Strings} from '@openzeppelin/utils/Strings.sol';
import {Base64} from '@openzeppelin/utils/Base64.sol';
import {Math} from '@libraries/Math.sol';
import {IVault721} from '@interfaces/proxies/IVault721.sol';
import {IODSafeManager} from '@interfaces/proxies/IODSafeManager.sol';
import {ISAFEEngine} from '@interfaces/ISAFEEngine.sol';
import {IOracleRelayer} from '@interfaces/IOracleRelayer.sol';
import {IDelayedOracle} from '@interfaces/oracles/IDelayedOracle.sol';
import {ITaxCollector} from '@interfaces/ITaxCollector.sol';
import {ICollateralJoinFactory} from '@interfaces/factories/ICollateralJoinFactory.sol';
import {ICollateralJoin} from '@interfaces/utils/ICollateralJoin.sol';
import {IERC20Metadata} from '@openzeppelin/token/ERC20/extensions/IERC20Metadata.sol';
contract NFTRenderer {
using Strings for uint256;
using Math for uint256;
using DateTime for uint256;
uint256 internal constant _RAY = 10 ** 27;
IVault721 public immutable vault721;
// protocol contracts
IODSafeManager internal _safeManager;
ISAFEEngine internal _safeEngine;
IOracleRelayer internal _oracleRelayer;
ITaxCollector internal _taxCollector;
ICollateralJoinFactory internal _collateralJoinFactory;
event ImplementationSet(
address safeManager, address safeEngine, address oracleRelayer, address taxCollector, address collateralJoinFactory
);
constructor(address _vault721, address oracleRelayer, address taxCollector, address collateralJoinFactory) {
vault721 = IVault721(_vault721);
vault721.initializeRenderer();
_safeManager = IODSafeManager(vault721.safeManager());
_safeEngine = ISAFEEngine(_safeManager.safeEngine());
_oracleRelayer = IOracleRelayer(oracleRelayer);
_taxCollector = ITaxCollector(taxCollector);
_collateralJoinFactory = ICollateralJoinFactory(collateralJoinFactory);
}
// state = {0: (no collateral, no debt) 1: (collateral, no debt) 2: (collateral, debt)}
struct VaultParams {
uint256 state;
uint256 ratio;
string collateralJson;
string debtJson;
string collateralSvg;
string debtSvg;
string vaultId;
string stabilityFee;
string symbol;
string risk;
string color;
string stroke;
string lastUpdate;
string lastBlockNumber;
string lastBlockTimestamp;
string tokenCollateral;
}
/**
* @dev upgradeability permissioned to governor via Vault721
*/
function setImplementation(
address safeManager,
address oracleRelayer,
address taxCollector,
address collateralJoinFactory
) external {
require(msg.sender == address(vault721), 'NFT: only vault721');
_safeManager = IODSafeManager(safeManager);
_safeEngine = ISAFEEngine(_safeManager.safeEngine());
_oracleRelayer = IOracleRelayer(oracleRelayer);
_taxCollector = ITaxCollector(taxCollector);
_collateralJoinFactory = ICollateralJoinFactory(collateralJoinFactory);
emit ImplementationSet(
address(_safeManager),
address(_safeEngine),
address(_oracleRelayer),
address(_taxCollector),
address(_collateralJoinFactory)
);
}
/**
* @dev render json object with NFT description and image
* @notice svg needs to be broken into separate functions to reduce call stack for compilation
*/
function render(uint256 _safeId) external view returns (string memory _uri) {
VaultParams memory params = renderParams(_safeId);
string memory text = _renderText(params);
uint256 ratio = params.ratio;
string memory json = string.concat(
'{"name":"OD NFV #',
text,
'"}],"image":"data:image/svg+xml;base64,',
Base64.encode(
bytes(
string.concat(
_renderVaultInfo(params.vaultId, params.color),
_renderCollatAndDebt(
ratio, params.stabilityFee, params.debtSvg, params.collateralSvg, params.symbol, params.lastUpdate
),
_renderRisk(params.state, ratio, params.stroke, params.risk),
_renderBackground(params.color)
)
)
),
'"}'
);
_uri = string.concat('data:application/json;base64,', Base64.encode(bytes(json)));
}
/**
* @dev reads from various protocol contracts to collect data about user vaults by vault id
*/
function renderParams(uint256 _safeId) public view returns (VaultParams memory) {
VaultParams memory params;
params.vaultId = _safeId.toString();
bytes32 cType;
// scoped to reduce call stack
{
IVault721.NFVState memory nfvState = vault721.getNfvState(_safeId);
cType = nfvState.cType;
params.lastBlockNumber = nfvState.lastBlockNumber.toString();
params.lastBlockTimestamp = nfvState.lastBlockTimestamp.toString();
uint256 collateral = nfvState.collateral;
params.collateralJson = collateral.toString();
params.collateralSvg = _formatNumberForSvg(collateral);
uint256 debt = nfvState.debt;
params.debtJson = debt.toString();
params.debtSvg = _formatNumberForSvg(debt);
params.tokenCollateral = _formatNumberForJson(_safeEngine.tokenCollateral(cType, nfvState.safeHandler));
IOracleRelayer.OracleRelayerCollateralParams memory oracleParams = _oracleRelayer.cParams(cType);
IDelayedOracle oracle = oracleParams.oracle;
uint256 safetyCRatio = oracleParams.safetyCRatio / 10e24;
uint256 liquidationCRatio = oracleParams.liquidationCRatio / 10e24;
uint256 ratio;
uint256 state;
if (collateral > 0) {
if (debt > 0) {
state = 2;
ISAFEEngine.SAFEEngineCollateralData memory cTypeData = _safeEngine.cData(cType);
ratio = ((collateral.wmul(oracle.read())).wdiv(debt.wmul(cTypeData.accumulatedRate))) / 1e7; // _RAY to _WAD conversion
} else {
state = 1;
ratio = 200;
}
}
IERC20Metadata token = ICollateralJoin(_collateralJoinFactory.collateralJoins(cType)).collateral();
params.symbol = token.symbol();
params.lastUpdate = _formatDateTime(oracle.lastUpdateTime());
(params.risk, params.color) = _calcRisk(ratio, state, liquidationCRatio, safetyCRatio);
params.stroke = _calcStroke(ratio);
params.ratio = ratio;
params.state = state;
}
ITaxCollector.TaxCollectorCollateralData memory taxData = _taxCollector.cData(cType);
params.stabilityFee = (taxData.nextStabilityFee / _RAY).toString();
return params;
}
/**
* @dev json text
*/
function _renderText(VaultParams memory params) internal pure returns (string memory text) {
string memory desc = _renderDesc(params.vaultId);
string memory traits = _renderTraits(params);
text = string.concat(
params.vaultId,
'","description":',
desc,
'"attributes":[{"trait_type":"ID","value":"',
params.vaultId,
traits,
params.lastUpdate,
'"},{"trait_type":"Modified on Block","value":"',
params.lastBlockNumber,
'"},{"trait_type":"Modified at Timestamp ","value":"',
params.lastBlockTimestamp,
'"},{"trait_type":"Internal Collateral","value":"',
params.tokenCollateral
);
}
/**
* @dev json description
*/
function _renderDesc(string memory _safeId) internal pure returns (string memory desc) {
desc = string.concat(
'"Non-Fungible Vault #',
_safeId,
' Caution! Trading this NFV gives the recipient full ownership of your Vault, including all collateral & debt obligations. This act is irreversible.",'
);
}
/**
* @dev json attributes
*/
function _renderTraits(VaultParams memory params) internal pure returns (string memory traits) {
// stack at 16 slot max w/ 32-byte+ strings
traits = string.concat(
'"},{"trait_type":"Debt","value":"',
params.debtJson,
'"},{"trait_type":"Collateral","value":"',
params.collateralJson,
'"},{"trait_type":"Collateral Type","value":"',
params.symbol,
'"},{"trait_type":"Stability Fee","value":"',
params.stabilityFee,
'"},{"trait_type":"Risk","value":"',
params.risk,
'"},{"trait_type":"Collateral Ratio","value":"',
params.ratio.toString(),
'"},{"trait_type":"Last Updated","value":"'
);
}
/**
* @dev svg vault/token id
*/
function _renderVaultInfo(string memory vaultId, string memory color) internal pure returns (string memory svg) {
svg = string.concat(
'<svg width="420" height="420" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a target="_blank" href="https://app.dev.opendollar.com/#/vaults/',
vaultId,
'"><style>.graph-bg { fill: none; stroke: #000; stroke-width: 20; opacity: 80%;} .graph {fill: none; stroke-width: 20; stroke-linecap: flat; animation: progress 1s ease-out forwards;} .chart {stroke: ',
color,
';opacity: 40%;} .risk-ratio {fill: ',
color,
';}@keyframes progress {0% {stroke-dasharray: 0 1005;}} @keyframes liquidation {0% { opacity: 80%;} 50% { opacity: 20%;} 100 { opacity: 80%;}}</style><g font-family="Inter, Verdana, sans-serif" style="white-space:pre" font-size="12"><path fill="#001828" d="M0 0H420V420H0z" /><path fill="url(#gradient)" d="M0 0H420V420H0z" /><path id="od-pattern-tile" opacity=".05" d="M49.7-40a145 145 0 1 0 0 290m0-290V8.2m0-48.4a145 145 0 1 1 0 290m0-241.6a96.7 96.7 0 1 0 0 193.3m0-193.3a96.7 96.7 0 1 1 0 193.3m0 0v48.3m0-96.6a48.3 48.3 0 0 0 0-96.7v96.7Zm0 0a48.3 48.3 0 0 1 0-96.7v96.7Z" stroke="#fff" /><use xlink:href="#od-pattern-tile" x="290" /><use xlink:href="#od-pattern-tile" y="290" /><use xlink:href="#od-pattern-tile" x="290" y="290" /><use xlink:href="#od-pattern-tile" x="193" y="145" /><text fill="#00587E" xml:space="preserve"><tspan x="24" y="40.7">VAULT ID</tspan></text><text fill="#1499DA" xml:space="preserve" font-size="22"><tspan x="24" y="65">',
vaultId,
'</tspan></text><text fill="#00587E" xml:space="preserve"><tspan x="335.9" y="40.7">STABILITY</tspan><tspan x="335.9" y="54.7">FEE</tspan></text><text fill="#1499DA" xml:space="preserve" font-size="22"><tspan x="364" y="63.3">'
);
}
/**
* @dev svg collateral and debt data
*/
function _renderCollatAndDebt(
uint256 ratio,
string memory stabilityFee,
string memory debt,
string memory collateral,
string memory symbol,
string memory lastUpdate
) internal pure returns (string memory svg) {
string memory debtDetail;
if (ratio != 0) {
debtDetail = string.concat(
'<text fill="#00587E" xml:space="preserve" font-weight="600"><tspan x="102" y="168.9">DEBT MINTED</tspan></text><text fill="#D0F1FF" xml:space="preserve" font-size="24"><tspan x="102" y="194">',
debt,
' OD',
'</tspan></text><text fill="#00587E" xml:space="preserve" font-weight="600"><tspan x="102" y="229.9">COLLATERAL DEPOSITED</tspan></text><text fill="#D0F1FF" xml:space="preserve" font-size="24"><tspan x="102" y="255">',
collateral,
' ',
symbol,
'</tspan></text><text opacity=".3" transform="rotate(-90 326.5 -58.5)" fill="#fff" xml:space="preserve" font-size="10"><tspan x="-10.3" y="7.3">Updated '
);
} else {
debtDetail =
'<text fill="#63676F" xml:space="preserve" font-size="24"><tspan x="136" y="210">Zero Balance</tspan></text><text opacity=".3" transform="rotate(-90 326.5 -58.5)" fill="#fff" xml:space="preserve" font-size="10"><tspan x="-10.3" y="7.3">Updated ';
}
svg = string.concat(
stabilityFee,
'%</tspan></text><text opacity=".3" transform="rotate(90 -66.5 101.5)" fill="#fff" xml:space="preserve" font-size="10"><tspan x=".5" y="7.3">opendollar.com</tspan></text>',
debtDetail,
lastUpdate
);
}
/**
* @dev svg risk data
*/
function _renderRisk(
uint256 state,
uint256 ratio,
string memory stroke,
string memory risk
) internal pure returns (string memory svg) {
string memory rectangle;
string memory riskDetail;
if (state == 2) {
rectangle =
'), 1005" d="M210 40a160 160 0 0 1 0 320 160 160 0 0 1 0-320" /></g><g class="risk-ratio"><rect x="242" y="306" width="154" height="82" rx="8" fill="#001828" fill-opacity=".7" /><circle cx="243" cy="326.5" r="4" /><text xml:space="preserve" font-weight="600"><tspan x="255" y="330.7">';
riskDetail = string.concat(
' RISK</tspan></text><text xml:space="preserve"><tspan x="255" y="355.7">COLLATERAL</tspan><tspan x="255" y="371.7">RATIO ',
ratio.toString(),
'%</tspan></text>'
);
} else if (state == 1) {
rectangle =
'), 1005" d="M210 40a160 160 0 0 1 0 320 160 160 0 0 1 0-320" /></g><g class="risk-ratio"><rect x="242" y="306" width="154" height="82" rx="8" fill="#001828" fill-opacity=".7" /><circle cx="243" cy="326.5" r="4" /><text xml:space="preserve" font-weight="600"><tspan x="255" y="330.7">';
riskDetail =
' RISK</tspan></text><text xml:space="preserve"><tspan x="255" y="355.7">COLLATERAL</tspan><tspan x="255" y="371.7">RATIO ∞</tspan></text>';
} else {
rectangle =
'), 1005" d="M210 40a160 160 0 0 1 0 320 160 160 0 0 1 0-320" /></g><g class="risk-ratio"><rect x="298" y="350" width="96" height="40" rx="8" fill="#001828" fill-opacity=".7" /><circle cx="299" cy="370.5" r="4" /><text xml:space="preserve" font-weight="600"><tspan x="311" y="374.7">';
riskDetail = ' RISK</tspan></text>';
}
svg = string.concat(
'</tspan></text><g opacity=".6"><text fill="#fff" xml:space="preserve"><tspan x="24" y="387.4">Powered by</tspan></text><path d="M112.5 388c-2 0-3-1.2-3-3.2v-3.3c0-2 1-3.3 3-3.3 2.1 0 3.2 1.3 3.2 3.3v3.3c0 2-1 3.3-3.2 3.3Zm-1.5-3.2c0 1.1.5 1.8 1.6 1.8 1 0 1.5-.7 1.5-1.8v-3.3c0-1.1-.4-1.8-1.5-1.8s-1.6.7-1.6 1.8v3.3ZM117.3 390.6l-.1-.2V381l.1-.2h1.2l.1.2v.7c.3-.7 1-1 1.8-1 1.3 0 2 1 2 2.6v2.3c0 1.6-.8 2.6-2 2.6-.8 0-1.4-.4-1.7-1v3.3c0 .1 0 .2-.2.2h-1.2Zm1.4-5.2c0 .9.5 1.3 1.1 1.3.7 0 1-.5 1-1.3v-2.2c0-.7-.3-1.3-1-1.3-.6 0-1.1.5-1.1 1.4v2ZM126.2 388c-1.6 0-2.6-1-2.6-2.6v-2.2c0-1.6 1-2.6 2.5-2.6 1.6 0 2.6 1 2.6 2.6v1.4c0 .1 0 .2-.2.2h-3.4v.6c0 1 .4 1.4 1.1 1.4.6 0 1-.3 1.1-.8l.2-.2 1 .3c.1 0 .2 0 .1.2-.2 1-1 1.8-2.4 1.8Zm-1.1-4.2h2.2v-.7c0-.8-.4-1.3-1.1-1.3-.8 0-1.1.5-1.1 1.3v.7ZM130.2 388l-.2-.2v-7l.2-.1h1.1c.1 0 .2 0 .2.2v.7c.4-.7 1-1 1.7-1 1.1 0 1.8.8 1.8 2.5v4.7l-.1.1h-1.2l-.2-.1V383c0-.8-.3-1.2-.8-1.2s-1 .4-1.2 1v4.9l-.1.1h-1.2ZM136.8 388l-.2-.2v-9.3c0-.1 0-.2.2-.2h2.6c2 0 3.1 1.3 3.1 3.3v3c0 2-1 3.3-3.1 3.3h-2.6Zm1.4-1.5h1.2c1 0 1.6-.7 1.6-1.8v-3c0-1.2-.5-1.9-1.6-1.9h-1.2v6.7ZM146.4 388c-1.6 0-2.6-1-2.6-2.6v-2.2c0-1.6 1-2.6 2.6-2.6 1.7 0 2.6 1 2.6 2.6v2.2c0 1.7-1 2.7-2.6 2.7Zm-1-2.6c0 .9.3 1.3 1 1.3.8 0 1.1-.4 1.1-1.3v-2.2c0-.8-.4-1.3-1-1.3-.8 0-1.1.5-1.1 1.3v2.2ZM150.6 388l-.2-.2V378l.2-.2h1.2l.2.2v9.7l-.2.1h-1.2ZM153.7 388l-.2-.2V378c0-.1 0-.2.2-.2h1.2l.1.2v9.7l-.1.1h-1.2ZM160 388l-.1-.2v-.8c-.4.7-1 1-1.7 1-1.1 0-1.9-.7-1.9-2 0-1.4.7-2.3 2.6-2.3h1v-.8c0-.7-.4-1-1-1s-.8.2-1 .8h-.2l-1-.2c-.1 0-.2-.1-.1-.2.2-1 1-1.7 2.4-1.7 1.5 0 2.3.7 2.3 2.2v5l-.2.1h-1Zm-2.3-2.2c0 .7.3 1 1 1 .5 0 1-.3 1.1-1v-1.1h-.8c-.8 0-1.3.4-1.3 1.1ZM163 388l-.2-.2v-7h1.5v1c.3-.7.9-1.2 1.8-1.2.1 0 .2 0 .2.2v1.1c0 .1 0 .2-.2.2-1 0-1.5.3-1.8 1v4.7l-.1.1H163Z" fill="#fff" /><path d="M97 383.2c0-2.7 2-4.8 4.7-4.8v1.6a3.2 3.2 0 0 0-3.1 3.2c0 1.8 1.4 3.2 3 3.2v1.6a4.7 4.7 0 0 1-4.6-4.8ZM101.7 384.8c.8 0 1.5-.7 1.5-1.6 0-.9-.7-1.6-1.5-1.6v3.2Z" fill="#fff" opacity=".5" /><path d="M106.3 383.2c0 2.7-2 4.8-4.6 4.8v-1.6c1.7 0 3-1.4 3-3.2 0-1.8-1.3-3.2-3-3.2v-1.6c2.6 0 4.6 2.1 4.6 4.8ZM101.7 381.6c-.9 0-1.6.7-1.6 1.6 0 .9.7 1.6 1.6 1.6v-3.2Z" fill="#fff" /></g><g class="chart"><path class="graph-bg" d="M210 40a160 160 0 0 1 0 320 160 160 0 0 1 0-320" /><path class="graph" stroke-dasharray="calc(10.05 * ',
stroke,
rectangle,
risk,
riskDetail
);
}
/**
* @dev svg background
*/
function _renderBackground(string memory color) internal pure returns (string memory svg) {
svg = string.concat(
'</g></g><defs><radialGradient id="gradient" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-133.2 301 119) scale(368.295)"><stop stop-color="',
color,
'" /><stop offset="1" stop-color="',
color,
'" stop-opacity="0" /></radialGradient></defs></a></svg>'
);
}
/**
* @dev calculates liquidation risk
*/
function _calcRisk(
uint256 ratio,
uint256 state,
uint256 liquidationRatio,
uint256 safetyRatio
) internal pure returns (string memory, string memory) {
if (state == 2) {
if (ratio <= liquidationRatio) return ('LIQUIDATION', '#E45200');
else if (ratio > liquidationRatio && ratio <= safetyRatio) return ('HIGH', '#E45200');
else if (ratio > safetyRatio && ratio <= (safetyRatio * 120 / 100)) return ('ELEVATED', '#FCBF3B');
else return ('LOW', '#5DBA14');
} else if (state == 1) {
return ('LOW', '#5DBA14');
} else {
return ('NO', '#63676F');
}
}
/**
* @dev fills circular stroke by percentage of collateral over 100% up to 200%
*/
function _calcStroke(uint256 ratio) internal pure returns (string memory) {
if (ratio == 0) return '0';
if (ratio <= 100 || ratio >= 200) return '100';
else return (ratio - 100).toString();
}
function _formatNumberForJson(uint256 num) internal pure returns (string memory) {
(uint256 left, uint256 right) = _floatingPoint(num);
return _parseNumber(left, right);
}
function _formatNumberForSvg(uint256 num) internal pure returns (string memory) {
(uint256 left, uint256 right) = _floatingPoint(num);
return _parseNumberWithComma(left, right);
}
/**
* @dev converts uint from wei fixed-point to ether floating-point format
*/
function _floatingPoint(uint256 num) internal pure returns (uint256 left, uint256 right) {
left = num / 1e18;
uint256 expLeft = left * 1e18;
uint256 expRight = num - expLeft;
right = expRight / 1e14; // format to 4 decimal places
}
/**
* @dev parses number
*/
function _parseNumber(uint256 left, uint256 right) internal pure returns (string memory) {
if (left > 0) {
return string.concat(left.toString(), '.', right.toString());
} else {
return string.concat('0.', right.toString());
}
}
/**
* @dev parses comma-separated number
*/
function _parseNumberWithComma(uint256 left, uint256 right) internal pure returns (string memory) {
if (left > 0) {
return string.concat(_commaFormat(left), '.', right.toString());
} else {
return string.concat('0.', right.toString());
}
}
/**
* @dev adds commas every 3 digits
*/
function _commaFormat(uint256 source) internal pure returns (string memory) {
string memory result = '';
uint128 index;
while (source > 0) {
uint256 part = source % 10; // get each digit
bool isSet = index != 0 && index % 3 == 0; // request set glue for every additional 3 digits
result = _concatWithComma(result, part, isSet);
source = source / 10;
index += 1;
}
return result;
}
/**
* @dev concats with comma
*/
function _concatWithComma(string memory base, uint256 part, bool isSet) internal pure returns (string memory) {
string memory stringified = part.toString();
string memory glue = ',';
if (!isSet) glue = '';
return string(abi.encodePacked(stringified, glue, base));
}
/**
* @dev converts timestamp to human readable date and time format
*/
function _formatDateTime(uint256 timestamp) internal pure returns (string memory) {
(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute,) = timestamp.timestampToDateTime();
string memory _month;
if (month == 1) _month = 'Jan';
else if (month == 2) _month = 'Feb';
else if (month == 3) _month = 'Mar';
else if (month == 4) _month = 'Apr';
else if (month == 5) _month = 'May';
else if (month == 6) _month = 'Jun';
else if (month == 7) _month = 'Jul';
else if (month == 8) _month = 'Aug';
else if (month == 9) _month = 'Sep';
else if (month == 10) _month = 'Oct';
else if (month == 11) _month = 'Nov';
else _month = 'Dec';
return string.concat(
_month, ' ', day.toString(), ', ', year.toString(), ' ', _formatTime(hour), ':', _formatTime(minute), ' UTC'
);
}
/**
* @dev zero pads single digits
*/
function _formatTime(uint256 time) internal pure returns (string memory) {
if (time < 10) return string.concat('0', time.toString());
else return time.toString();
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {Address} from '@openzeppelin/utils/Address.sol';
// Open Dollar
// Version 1.7.0
contract ODProxy {
using Address for address;
error TargetAddressRequired();
error TargetCallFailed(bytes _response);
error OnlyOwner();
address public immutable OWNER;
constructor(address _owner) {
OWNER = _owner;
}
/**
* @notice Checks whether msg.sender can call an owned function
*/
modifier onlyOwner() {
if (msg.sender != OWNER) revert OnlyOwner();
_;
}
/**
* @dev protocol delegatecall function
*/
function execute(address _target, bytes memory _data) external payable onlyOwner returns (bytes memory _response) {
if (_target == address(0)) revert TargetAddressRequired();
_response = _target.functionDelegateCall(_data);
}
/**
* @dev arbitrary call function
* @notice prevents erc20 funds from getting stuck in proxy
*/
function arbitraryExecute(
address _target,
bytes memory _data
) external payable onlyOwner returns (bytes memory _response) {
_response = _target.functionCall(_data);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return 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 {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMathUpgradeable {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return 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 {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @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;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(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) {
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] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
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 Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.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, MathUpgradeable.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) {
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] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
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 Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import {ERC721Upgradeable, IERC721Upgradeable} from '@openzeppelin-upgradeable/token/ERC721/ERC721Upgradeable.sol';
import {ERC721EnumerableUpgradeable} from
'@openzeppelin-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol';
import {IODSafeManager} from '@interfaces/proxies/IODSafeManager.sol';
import {ODProxy} from '@contracts/proxies/ODProxy.sol';
import {NFTRenderer} from '@contracts/proxies/NFTRenderer.sol';
import {IVault721} from '@interfaces/proxies/IVault721.sol';
import {Modifiable} from '@contracts/utils/Modifiable.sol';
import {Authorizable} from '@contracts/utils/Authorizable.sol';
import {Assertions} from '@libraries/Assertions.sol';
import {Encoding} from '@libraries/Encoding.sol';
import {ISAFEEngine} from '@interfaces/ISAFEEngine.sol';
// Open Dollar
// Version 1.7.0
/**
* @notice Upgradeable contract used as singleton, but is not upgradeable
*/
contract Vault721 is ERC721EnumerableUpgradeable, Authorizable, Modifiable, IVault721 {
using Assertions for address;
using Encoding for bytes;
address public timelockController;
IODSafeManager public safeManager;
NFTRenderer public nftRenderer;
uint256 public blockDelay;
uint256 public timeDelay;
string public contractMetaData =
'{"name": "Open Dollar Vaults","description": "Open Dollar is a stablecoin protocol built on Arbitrum designed to help you earn yield and leverage your assets with safety and predictability.","image": "https://app.opendollar.com/collectionImage.png","external_link": "https://app.opendollar.com"}';
mapping(address proxy => address user) internal _proxyRegistry;
mapping(address user => address proxy) internal _userRegistry;
mapping(uint256 vaultId => NFVState nfvState) internal _nfvState;
mapping(address nftExchange => bool whitelisted) internal _allowlist;
constructor() Authorizable(msg.sender) {}
function initialize(
address _timelockController,
uint256 _blockDelay,
uint256 _timeDelay
) external initializer nonZero(_timelockController) {
timelockController = _timelockController;
if (!_isAuthorized(timelockController)) _addAuthorization(timelockController);
__ERC721_init('Open Dollar Vault', 'OD-NFV');
blockDelay = _blockDelay;
timeDelay = _timeDelay;
}
/**
* @dev control access for SafeManager
*/
modifier onlySafeManager() {
if (msg.sender != address(safeManager)) revert NotSafeManager();
_;
}
/**
* @dev enforce non-zero address params
*/
modifier nonZero(address _addr) {
if (_addr == address(0)) revert ZeroAddress();
_;
}
/// @inheritdoc IVault721
function initializeManager() external {
if (address(safeManager) == address(0)) safeManager = IODSafeManager(msg.sender);
}
/// @inheritdoc IVault721
function initializeRenderer() external {
if (address(nftRenderer) == address(0)) nftRenderer = NFTRenderer(msg.sender);
}
/// @inheritdoc IVault721
function getProxy(address _user) external view returns (address _proxy) {
_proxy = _userRegistry[_user];
}
/// @inheritdoc IVault721
function getNfvState(uint256 _vaultId) external view returns (NFVState memory) {
return _nfvState[_vaultId];
}
/// @inheritdoc IVault721
function getIsAllowlisted(address _user) external view returns (bool) {
return _allowlist[_user];
}
/// @inheritdoc IVault721
function build() external returns (address payable _proxy) {
if (!_shouldBuildProxy(msg.sender)) revert ProxyAlreadyExist();
_proxy = _build(msg.sender);
}
/// @inheritdoc IVault721
function build(address _user) external returns (address payable _proxy) {
if (!_shouldBuildProxy(_user)) revert ProxyAlreadyExist();
_proxy = _build(_user);
}
/// @inheritdoc IVault721
function build(address[] memory _users) external returns (address payable[] memory _proxies) {
uint256 len = _users.length;
_proxies = new address payable[](len);
for (uint256 i = 0; i < len; i++) {
if (!_shouldBuildProxy(_users[i])) revert ProxyAlreadyExist();
_proxies[i] = _build(_users[i]);
}
}
/// @inheritdoc IVault721
function mint(address _proxy, uint256 _safeId) external onlySafeManager {
require(_proxyRegistry[_proxy] != address(0), 'V721: non-native proxy');
address _user = _proxyRegistry[_proxy];
_safeMint(_user, _safeId);
}
/// @inheritdoc IVault721
function updateNfvState(uint256 _vaultId) external onlySafeManager {
(bytes32 _cType, uint256 _collateral, uint256 _debt, address _safeHandler) = _getNfvValue(_vaultId);
_nfvState[_vaultId] = NFVState({
cType: _cType,
collateral: _collateral,
debt: _debt,
lastBlockNumber: block.number,
lastBlockTimestamp: block.timestamp,
safeHandler: _safeHandler
});
emit NFVStateUpdated(_vaultId);
}
/**
* @dev allows DAO to update allowlist
*/
function _updateAllowlist(address _user, bool _allowed) internal nonZero(_user) {
_allowlist[_user] = _allowed;
}
/**
* @dev generate URI with updated vault information
*/
/// @inheritdoc ERC721Upgradeable
function tokenURI(uint256 _safeId) public view override returns (string memory uri) {
_requireMinted(_safeId);
uri = nftRenderer.render(_safeId);
}
/// @inheritdoc IVault721
function contractURI() public view returns (string memory uri) {
uri = string.concat('data:application/json;utf8,', contractMetaData);
}
/**
* @dev check that proxy does not exist OR that the user does not own proxy
*/
function _shouldBuildProxy(address _user) internal view returns (bool) {
return _userRegistry[_user] == address(0) || ODProxy(_userRegistry[_user]).OWNER() != _user;
}
/**
* @dev deploys ODProxy for user to interact with protocol
* updates _proxyRegistry and _userRegistry mappings for new ODProxy
*/
function _build(address _user) internal virtual returns (address payable _proxy) {
if (_proxyRegistry[_user] != address(0)) revert NotWallet();
_proxy = payable(address(new ODProxy(_user)));
_proxyRegistry[_proxy] = _user;
_userRegistry[_user] = _proxy;
emit CreateProxy(_user, address(_proxy));
}
/**
* @dev get generated debt and locked collateral of nfv by tokenId
*/
function _getNfvValue(uint256 _vaultId) internal view returns (bytes32, uint256, uint256, address) {
IODSafeManager.SAFEData memory safeMangerData = safeManager.safeData(_vaultId);
address safeHandler = safeMangerData.safeHandler;
if (safeHandler == address(0)) revert ZeroAddress();
bytes32 cType = safeMangerData.collateralType;
ISAFEEngine.SAFE memory SafeEngineData = ISAFEEngine(safeManager.safeEngine()).safes(cType, safeHandler);
return (cType, SafeEngineData.lockedCollateral, SafeEngineData.generatedDebt, safeHandler);
}
/**
* @dev prevent undesirable frontrun state change during token transferFrom
* @notice frontrunning that increases the lockedCollateral or decreases the generatedDebt is accepted
*/
function _enforceStaticState(address _operator, uint256 _tokenId) internal view {
(, uint256 _collateralNow, uint256 _debtNow,) = _getNfvValue(_tokenId);
NFVState memory _nfv = _nfvState[_tokenId];
if (_collateralNow < _nfv.collateral || _debtNow > _nfv.debt) revert StateViolation();
if (_allowlist[_operator]) {
if (block.number < _nfv.lastBlockNumber + blockDelay) revert BlockDelayNotOver();
} else {
if (block.timestamp < _nfv.lastBlockTimestamp + timeDelay) revert TimeDelayNotOver();
}
}
/**
* @dev allows DAO to update protocol implementation on NFTRenderer
*/
function _updateNftRenderer(
address _nftRenderer,
address _oracleRelayer,
address _taxCollector,
address _collateralJoinFactory
) internal {
address _safeManager = address(safeManager);
_safeManager.assertNonNull();
nftRenderer = NFTRenderer(_nftRenderer);
nftRenderer.setImplementation(_safeManager, _oracleRelayer, _taxCollector, _collateralJoinFactory);
}
/**
* @dev allows DAO to update protocol implementation of SafeManager
*
* WARNING: SafeManager should not be updated unless the new SafeManager
* is capable of correctly persisting the proper safeId as it relates to the
* current tokenId. Additional considerations regarding data migration of
* core contracts should be addressed.
*/
/// @inheritdoc Modifiable
function _modifyParameters(bytes32 _param, bytes memory _data) internal override {
address _address = _data.toAddress();
if (_param == 'safeManager') {
safeManager = IODSafeManager(_address.assertNonNull());
} else if (_param == 'timelockController') {
address oldController = timelockController;
_addAuthorization(_address.assertNonNull());
timelockController = _address;
_removeAuthorization(oldController);
} else if (_param == 'nftRenderer') {
nftRenderer = NFTRenderer(_address.assertNonNull());
} else if (_param == 'blockDelay') {
blockDelay = _data.toUint256();
} else if (_param == 'timeDelay') {
timeDelay = _data.toUint256();
} else if (_param == 'updateNFTRenderer') {
(address _nftRenderer, address _oracleRelayer, address _taxCollector, address _collateralJoinFactory) =
abi.decode(_data, (address, address, address, address));
_updateNftRenderer(
_nftRenderer.assertNonNull(),
_oracleRelayer.assertNonNull(),
_taxCollector.assertNonNull(),
_collateralJoinFactory.assertNonNull()
);
} else if (_param == 'updateAllowlist') {
(address _user, bool _bool) = abi.decode(_data, (address, bool));
_user.assertNonNull();
_updateAllowlist(_user, _bool);
} else if (_param == 'contractURI') {
contractMetaData = abi.decode(_data, (string));
} else {
revert UnrecognizedParam();
}
}
/**
* @dev enforce state before _transfer
*/
function _transfer(address _from, address _to, uint256 _tokenId) internal override {
_enforceStaticState(msg.sender, _tokenId);
super._transfer(_from, _to, _tokenId);
}
/**
* @dev _transfer calls `transferSAFEOwnership` on SafeManager
* @notice check that NFV receiver has proxy or build
*/
function _afterTokenTransfer(address _from, address _to, uint256 _tokenId, uint256) internal override {
require(_to != address(0), 'V721: no burn');
if (_from != address(0)) {
address payable proxy;
if (_shouldBuildProxy(_to)) {
proxy = _build(_to);
} else {
proxy = payable(_userRegistry[_to]);
}
IODSafeManager(safeManager).transferSAFEOwnership(_tokenId, address(proxy));
}
}
}
{
"compilationTarget": {
"src/contracts/proxies/Vault721.sol": "Vault721"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 10000
},
"remappings": [
":@console2/=forge-std/console2.sol;/",
":@contracts/=src/contracts/",
":@defi-wonderland/solidity-utils/=node_modules/@defi-wonderland/solidity-utils/solidity/",
":@interfaces/=src/interfaces/",
":@isolmate/=lib/isolmate/src/",
":@libraries/=src/libraries/",
":@openzeppelin-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
":@openzeppelin/=node_modules/@openzeppelin/contracts/",
":@script/=script/",
":@test/=test/",
":ds-test/=lib/ds-test/src/",
":forge-std/=lib/forge-std/src/",
":isolmate/=lib/isolmate/src/",
":prb-test/=lib/prb-test/src/"
]
}
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AlreadyAuthorized","type":"error"},{"inputs":[],"name":"BlockDelayNotOver","type":"error"},{"inputs":[],"name":"NotAuthorized","type":"error"},{"inputs":[],"name":"NotSafeManager","type":"error"},{"inputs":[],"name":"NotWallet","type":"error"},{"inputs":[],"name":"NullAddress","type":"error"},{"inputs":[],"name":"NullAddress","type":"error"},{"inputs":[],"name":"ProxyAlreadyExist","type":"error"},{"inputs":[],"name":"StateViolation","type":"error"},{"inputs":[],"name":"TimeDelayNotOver","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[],"name":"UnrecognizedCType","type":"error"},{"inputs":[],"name":"UnrecognizedParam","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_account","type":"address"}],"name":"AddAuthorization","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_user","type":"address"},{"indexed":true,"internalType":"address","name":"_proxy","type":"address"}],"name":"CreateProxy","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"_param","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"_cType","type":"bytes32"},{"indexed":false,"internalType":"bytes","name":"_data","type":"bytes"}],"name":"ModifyParameters","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_vaultId","type":"uint256"}],"name":"NFVStateUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_account","type":"address"}],"name":"RemoveAuthorization","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"addAuthorization","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"authorizedAccounts","outputs":[{"internalType":"bool","name":"_authorized","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"authorizedAccounts","outputs":[{"internalType":"address[]","name":"_accounts","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"blockDelay","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"_users","type":"address[]"}],"name":"build","outputs":[{"internalType":"address payable[]","name":"_proxies","type":"address[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"build","outputs":[{"internalType":"address payable","name":"_proxy","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"}],"name":"build","outputs":[{"internalType":"address payable","name":"_proxy","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"contractMetaData","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"contractURI","outputs":[{"internalType":"string","name":"uri","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"}],"name":"getIsAllowlisted","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_vaultId","type":"uint256"}],"name":"getNfvState","outputs":[{"components":[{"internalType":"bytes32","name":"cType","type":"bytes32"},{"internalType":"uint256","name":"collateral","type":"uint256"},{"internalType":"uint256","name":"debt","type":"uint256"},{"internalType":"uint256","name":"lastBlockNumber","type":"uint256"},{"internalType":"uint256","name":"lastBlockTimestamp","type":"uint256"},{"internalType":"address","name":"safeHandler","type":"address"}],"internalType":"struct IVault721.NFVState","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"}],"name":"getProxy","outputs":[{"internalType":"address","name":"_proxy","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_timelockController","type":"address"},{"internalType":"uint256","name":"_blockDelay","type":"uint256"},{"internalType":"uint256","name":"_timeDelay","type":"uint256"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"initializeManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"initializeRenderer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_proxy","type":"address"},{"internalType":"uint256","name":"_safeId","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_param","type":"bytes32"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"modifyParameters","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nftRenderer","outputs":[{"internalType":"contract NFTRenderer","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"removeAuthorization","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"safeManager","outputs":[{"internalType":"contract IODSafeManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"timeDelay","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"timelockController","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenOfOwnerByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_safeId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"uri","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_vaultId","type":"uint256"}],"name":"updateNfvState","outputs":[],"stateMutability":"nonpayable","type":"function"}]