dexorder
This commit is contained in:
402
lib_openzeppelin_contracts/contracts/token/ERC1155/ERC1155.sol
Normal file
402
lib_openzeppelin_contracts/contracts/token/ERC1155/ERC1155.sol
Normal file
@@ -0,0 +1,402 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/ERC1155.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC1155} from "./IERC1155.sol";
|
||||
import {IERC1155MetadataURI} from "./extensions/IERC1155MetadataURI.sol";
|
||||
import {ERC1155Utils} from "./utils/ERC1155Utils.sol";
|
||||
import {Context} from "../../utils/Context.sol";
|
||||
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
|
||||
import {Arrays} from "../../utils/Arrays.sol";
|
||||
import {IERC1155Errors} from "../../interfaces/draft-IERC6093.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the basic standard multi-token.
|
||||
* See https://eips.ethereum.org/EIPS/eip-1155
|
||||
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
|
||||
*/
|
||||
abstract contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, IERC1155Errors {
|
||||
using Arrays for uint256[];
|
||||
using Arrays for address[];
|
||||
|
||||
mapping(uint256 id => mapping(address account => uint256)) private _balances;
|
||||
|
||||
mapping(address account => mapping(address operator => bool)) private _operatorApprovals;
|
||||
|
||||
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
|
||||
string private _uri;
|
||||
|
||||
/**
|
||||
* @dev See {_setURI}.
|
||||
*/
|
||||
constructor(string memory uri_) {
|
||||
_setURI(uri_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
|
||||
return
|
||||
interfaceId == type(IERC1155).interfaceId ||
|
||||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
|
||||
super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155MetadataURI-uri}.
|
||||
*
|
||||
* This implementation returns the same URI for *all* token types. It relies
|
||||
* on the token type ID substitution mechanism
|
||||
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC].
|
||||
*
|
||||
* Clients calling this function must replace the `\{id\}` substring with the
|
||||
* actual token type ID.
|
||||
*/
|
||||
function uri(uint256 /* id */) public view virtual returns (string memory) {
|
||||
return _uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155-balanceOf}.
|
||||
*/
|
||||
function balanceOf(address account, uint256 id) public view virtual returns (uint256) {
|
||||
return _balances[id][account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155-balanceOfBatch}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `accounts` and `ids` must have the same length.
|
||||
*/
|
||||
function balanceOfBatch(
|
||||
address[] memory accounts,
|
||||
uint256[] memory ids
|
||||
) public view virtual returns (uint256[] memory) {
|
||||
if (accounts.length != ids.length) {
|
||||
revert ERC1155InvalidArrayLength(ids.length, accounts.length);
|
||||
}
|
||||
|
||||
uint256[] memory batchBalances = new uint256[](accounts.length);
|
||||
|
||||
for (uint256 i = 0; i < accounts.length; ++i) {
|
||||
batchBalances[i] = balanceOf(accounts.unsafeMemoryAccess(i), ids.unsafeMemoryAccess(i));
|
||||
}
|
||||
|
||||
return batchBalances;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155-setApprovalForAll}.
|
||||
*/
|
||||
function setApprovalForAll(address operator, bool approved) public virtual {
|
||||
_setApprovalForAll(_msgSender(), operator, approved);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155-isApprovedForAll}.
|
||||
*/
|
||||
function isApprovedForAll(address account, address operator) public view virtual returns (bool) {
|
||||
return _operatorApprovals[account][operator];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155-safeTransferFrom}.
|
||||
*/
|
||||
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) public virtual {
|
||||
address sender = _msgSender();
|
||||
if (from != sender && !isApprovedForAll(from, sender)) {
|
||||
revert ERC1155MissingApprovalForAll(sender, from);
|
||||
}
|
||||
_safeTransferFrom(from, to, id, value, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155-safeBatchTransferFrom}.
|
||||
*/
|
||||
function safeBatchTransferFrom(
|
||||
address from,
|
||||
address to,
|
||||
uint256[] memory ids,
|
||||
uint256[] memory values,
|
||||
bytes memory data
|
||||
) public virtual {
|
||||
address sender = _msgSender();
|
||||
if (from != sender && !isApprovedForAll(from, sender)) {
|
||||
revert ERC1155MissingApprovalForAll(sender, from);
|
||||
}
|
||||
_safeBatchTransferFrom(from, to, ids, values, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`. Will mint (or burn) if `from`
|
||||
* (or `to`) is the zero address.
|
||||
*
|
||||
* Emits a {TransferSingle} event if the arrays contain one element, and {TransferBatch} otherwise.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - If `to` refers to a smart contract, it must implement either {IERC1155Receiver-onERC1155Received}
|
||||
* or {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value.
|
||||
* - `ids` and `values` must have the same length.
|
||||
*
|
||||
* NOTE: The ERC-1155 acceptance check is not performed in this function. See {_updateWithAcceptanceCheck} instead.
|
||||
*/
|
||||
function _update(address from, address to, uint256[] memory ids, uint256[] memory values) internal virtual {
|
||||
if (ids.length != values.length) {
|
||||
revert ERC1155InvalidArrayLength(ids.length, values.length);
|
||||
}
|
||||
|
||||
address operator = _msgSender();
|
||||
|
||||
for (uint256 i = 0; i < ids.length; ++i) {
|
||||
uint256 id = ids.unsafeMemoryAccess(i);
|
||||
uint256 value = values.unsafeMemoryAccess(i);
|
||||
|
||||
if (from != address(0)) {
|
||||
uint256 fromBalance = _balances[id][from];
|
||||
if (fromBalance < value) {
|
||||
revert ERC1155InsufficientBalance(from, fromBalance, value, id);
|
||||
}
|
||||
unchecked {
|
||||
// Overflow not possible: value <= fromBalance
|
||||
_balances[id][from] = fromBalance - value;
|
||||
}
|
||||
}
|
||||
|
||||
if (to != address(0)) {
|
||||
_balances[id][to] += value;
|
||||
}
|
||||
}
|
||||
|
||||
if (ids.length == 1) {
|
||||
uint256 id = ids.unsafeMemoryAccess(0);
|
||||
uint256 value = values.unsafeMemoryAccess(0);
|
||||
emit TransferSingle(operator, from, to, id, value);
|
||||
} else {
|
||||
emit TransferBatch(operator, from, to, ids, values);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Version of {_update} that performs the token acceptance check by calling
|
||||
* {IERC1155Receiver-onERC1155Received} or {IERC1155Receiver-onERC1155BatchReceived} on the receiver address if it
|
||||
* contains code (eg. is a smart contract at the moment of execution).
|
||||
*
|
||||
* IMPORTANT: Overriding this function is discouraged because it poses a reentrancy risk from the receiver. So any
|
||||
* update to the contract state after this function would break the check-effect-interaction pattern. Consider
|
||||
* overriding {_update} instead.
|
||||
*/
|
||||
function _updateWithAcceptanceCheck(
|
||||
address from,
|
||||
address to,
|
||||
uint256[] memory ids,
|
||||
uint256[] memory values,
|
||||
bytes memory data
|
||||
) internal virtual {
|
||||
_update(from, to, ids, values);
|
||||
if (to != address(0)) {
|
||||
address operator = _msgSender();
|
||||
if (ids.length == 1) {
|
||||
uint256 id = ids.unsafeMemoryAccess(0);
|
||||
uint256 value = values.unsafeMemoryAccess(0);
|
||||
ERC1155Utils.checkOnERC1155Received(operator, from, to, id, value, data);
|
||||
} else {
|
||||
ERC1155Utils.checkOnERC1155BatchReceived(operator, from, to, ids, values, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers a `value` tokens of token type `id` from `from` to `to`.
|
||||
*
|
||||
* Emits a {TransferSingle} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `to` cannot be the zero address.
|
||||
* - `from` must have a balance of tokens of type `id` of at least `value` amount.
|
||||
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
|
||||
* acceptance magic value.
|
||||
*/
|
||||
function _safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) internal {
|
||||
if (to == address(0)) {
|
||||
revert ERC1155InvalidReceiver(address(0));
|
||||
}
|
||||
if (from == address(0)) {
|
||||
revert ERC1155InvalidSender(address(0));
|
||||
}
|
||||
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
|
||||
_updateWithAcceptanceCheck(from, to, ids, values, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
|
||||
*
|
||||
* Emits a {TransferBatch} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
|
||||
* acceptance magic value.
|
||||
* - `ids` and `values` must have the same length.
|
||||
*/
|
||||
function _safeBatchTransferFrom(
|
||||
address from,
|
||||
address to,
|
||||
uint256[] memory ids,
|
||||
uint256[] memory values,
|
||||
bytes memory data
|
||||
) internal {
|
||||
if (to == address(0)) {
|
||||
revert ERC1155InvalidReceiver(address(0));
|
||||
}
|
||||
if (from == address(0)) {
|
||||
revert ERC1155InvalidSender(address(0));
|
||||
}
|
||||
_updateWithAcceptanceCheck(from, to, ids, values, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets a new URI for all token types, by relying on the token type ID
|
||||
* substitution mechanism
|
||||
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC].
|
||||
*
|
||||
* By this mechanism, any occurrence of the `\{id\}` substring in either the
|
||||
* URI or any of the values in the JSON file at said URI will be replaced by
|
||||
* clients with the token type ID.
|
||||
*
|
||||
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
|
||||
* interpreted by clients as
|
||||
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
|
||||
* for token type ID 0x4cce0.
|
||||
*
|
||||
* See {uri}.
|
||||
*
|
||||
* Because these URIs cannot be meaningfully represented by the {URI} event,
|
||||
* this function emits no events.
|
||||
*/
|
||||
function _setURI(string memory newuri) internal virtual {
|
||||
_uri = newuri;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Creates a `value` amount of tokens of type `id`, and assigns them to `to`.
|
||||
*
|
||||
* Emits a {TransferSingle} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `to` cannot be the zero address.
|
||||
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
|
||||
* acceptance magic value.
|
||||
*/
|
||||
function _mint(address to, uint256 id, uint256 value, bytes memory data) internal {
|
||||
if (to == address(0)) {
|
||||
revert ERC1155InvalidReceiver(address(0));
|
||||
}
|
||||
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
|
||||
_updateWithAcceptanceCheck(address(0), to, ids, values, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
|
||||
*
|
||||
* Emits a {TransferBatch} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `ids` and `values` must have the same length.
|
||||
* - `to` cannot be the zero address.
|
||||
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
|
||||
* acceptance magic value.
|
||||
*/
|
||||
function _mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) internal {
|
||||
if (to == address(0)) {
|
||||
revert ERC1155InvalidReceiver(address(0));
|
||||
}
|
||||
_updateWithAcceptanceCheck(address(0), to, ids, values, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Destroys a `value` amount of tokens of type `id` from `from`
|
||||
*
|
||||
* Emits a {TransferSingle} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `from` cannot be the zero address.
|
||||
* - `from` must have at least `value` amount of tokens of type `id`.
|
||||
*/
|
||||
function _burn(address from, uint256 id, uint256 value) internal {
|
||||
if (from == address(0)) {
|
||||
revert ERC1155InvalidSender(address(0));
|
||||
}
|
||||
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
|
||||
_updateWithAcceptanceCheck(from, address(0), ids, values, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
|
||||
*
|
||||
* Emits a {TransferBatch} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `from` cannot be the zero address.
|
||||
* - `from` must have at least `value` amount of tokens of type `id`.
|
||||
* - `ids` and `values` must have the same length.
|
||||
*/
|
||||
function _burnBatch(address from, uint256[] memory ids, uint256[] memory values) internal {
|
||||
if (from == address(0)) {
|
||||
revert ERC1155InvalidSender(address(0));
|
||||
}
|
||||
_updateWithAcceptanceCheck(from, address(0), ids, values, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Approve `operator` to operate on all of `owner` tokens
|
||||
*
|
||||
* Emits an {ApprovalForAll} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `operator` cannot be the zero address.
|
||||
*/
|
||||
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
|
||||
if (operator == address(0)) {
|
||||
revert ERC1155InvalidOperator(address(0));
|
||||
}
|
||||
_operatorApprovals[owner][operator] = approved;
|
||||
emit ApprovalForAll(owner, operator, approved);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Creates an array in memory with only one value for each of the elements provided.
|
||||
*/
|
||||
function _asSingletonArrays(
|
||||
uint256 element1,
|
||||
uint256 element2
|
||||
) private pure returns (uint256[] memory array1, uint256[] memory array2) {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
// Load the free memory pointer
|
||||
array1 := mload(0x40)
|
||||
// Set array length to 1
|
||||
mstore(array1, 1)
|
||||
// Store the single element at the next word after the length (where content starts)
|
||||
mstore(add(array1, 0x20), element1)
|
||||
|
||||
// Repeat for next array locating it right after the first array
|
||||
array2 := add(array1, 0x40)
|
||||
mstore(array2, 1)
|
||||
mstore(add(array2, 0x20), element2)
|
||||
|
||||
// Update the free memory pointer by pointing after the second array
|
||||
mstore(0x40, add(array2, 0x40))
|
||||
}
|
||||
}
|
||||
}
|
||||
123
lib_openzeppelin_contracts/contracts/token/ERC1155/IERC1155.sol
Normal file
123
lib_openzeppelin_contracts/contracts/token/ERC1155/IERC1155.sol
Normal file
@@ -0,0 +1,123 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.1) (token/ERC1155/IERC1155.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "../../utils/introspection/IERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev Required interface of an ERC-1155 compliant contract, as defined in the
|
||||
* https://eips.ethereum.org/EIPS/eip-1155[ERC].
|
||||
*/
|
||||
interface IERC1155 is IERC165 {
|
||||
/**
|
||||
* @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
|
||||
*/
|
||||
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
|
||||
|
||||
/**
|
||||
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
|
||||
* transfers.
|
||||
*/
|
||||
event TransferBatch(
|
||||
address indexed operator,
|
||||
address indexed from,
|
||||
address indexed to,
|
||||
uint256[] ids,
|
||||
uint256[] values
|
||||
);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
|
||||
* `approved`.
|
||||
*/
|
||||
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
|
||||
|
||||
/**
|
||||
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
|
||||
*
|
||||
* If an {URI} event was emitted for `id`, the standard
|
||||
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
|
||||
* returned by {IERC1155MetadataURI-uri}.
|
||||
*/
|
||||
event URI(string value, uint256 indexed id);
|
||||
|
||||
/**
|
||||
* @dev Returns the value of tokens of token type `id` owned by `account`.
|
||||
*/
|
||||
function balanceOf(address account, uint256 id) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `accounts` and `ids` must have the same length.
|
||||
*/
|
||||
function balanceOfBatch(
|
||||
address[] calldata accounts,
|
||||
uint256[] calldata ids
|
||||
) external view returns (uint256[] memory);
|
||||
|
||||
/**
|
||||
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
|
||||
*
|
||||
* Emits an {ApprovalForAll} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `operator` cannot be the zero address.
|
||||
*/
|
||||
function setApprovalForAll(address operator, bool approved) external;
|
||||
|
||||
/**
|
||||
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
|
||||
*
|
||||
* See {setApprovalForAll}.
|
||||
*/
|
||||
function isApprovedForAll(address account, address operator) external view returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
|
||||
*
|
||||
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
|
||||
* to an untrusted contract, when invoking {onERC1155Received} on the receiver.
|
||||
* Ensure to follow the checks-effects-interactions pattern and consider employing
|
||||
* reentrancy guards when interacting with untrusted contracts.
|
||||
*
|
||||
* Emits a {TransferSingle} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `to` cannot be the zero address.
|
||||
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
|
||||
* - `from` must have a balance of tokens of type `id` of at least `value` amount.
|
||||
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
|
||||
* acceptance magic value.
|
||||
*/
|
||||
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;
|
||||
|
||||
/**
|
||||
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
|
||||
*
|
||||
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
|
||||
* to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver.
|
||||
* Ensure to follow the checks-effects-interactions pattern and consider employing
|
||||
* reentrancy guards when interacting with untrusted contracts.
|
||||
*
|
||||
* Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `ids` and `values` must have the same length.
|
||||
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
|
||||
* acceptance magic value.
|
||||
*/
|
||||
function safeBatchTransferFrom(
|
||||
address from,
|
||||
address to,
|
||||
uint256[] calldata ids,
|
||||
uint256[] calldata values,
|
||||
bytes calldata data
|
||||
) external;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "../../utils/introspection/IERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev Interface that must be implemented by smart contracts in order to receive
|
||||
* ERC-1155 token transfers.
|
||||
*/
|
||||
interface IERC1155Receiver is IERC165 {
|
||||
/**
|
||||
* @dev Handles the receipt of a single ERC-1155 token type. This function is
|
||||
* called at the end of a `safeTransferFrom` after the balance has been updated.
|
||||
*
|
||||
* NOTE: To accept the transfer, this must return
|
||||
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
|
||||
* (i.e. 0xf23a6e61, or its own function selector).
|
||||
*
|
||||
* @param operator The address which initiated the transfer (i.e. msg.sender)
|
||||
* @param from The address which previously owned the token
|
||||
* @param id The ID of the token being transferred
|
||||
* @param value The amount of tokens being transferred
|
||||
* @param data Additional data with no specified format
|
||||
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
|
||||
*/
|
||||
function onERC1155Received(
|
||||
address operator,
|
||||
address from,
|
||||
uint256 id,
|
||||
uint256 value,
|
||||
bytes calldata data
|
||||
) external returns (bytes4);
|
||||
|
||||
/**
|
||||
* @dev Handles the receipt of a multiple ERC-1155 token types. This function
|
||||
* is called at the end of a `safeBatchTransferFrom` after the balances have
|
||||
* been updated.
|
||||
*
|
||||
* NOTE: To accept the transfer(s), this must return
|
||||
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
|
||||
* (i.e. 0xbc197c81, or its own function selector).
|
||||
*
|
||||
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
|
||||
* @param from The address which previously owned the token
|
||||
* @param ids An array containing ids of each token being transferred (order and length must match values array)
|
||||
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
|
||||
* @param data Additional data with no specified format
|
||||
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
|
||||
*/
|
||||
function onERC1155BatchReceived(
|
||||
address operator,
|
||||
address from,
|
||||
uint256[] calldata ids,
|
||||
uint256[] calldata values,
|
||||
bytes calldata data
|
||||
) external returns (bytes4);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
= ERC-1155
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc1155
|
||||
|
||||
This set of interfaces and contracts are all related to the https://eips.ethereum.org/EIPS/eip-1155[ERC-1155 Multi Token Standard].
|
||||
|
||||
The ERC consists of three interfaces which fulfill different roles, found here as {IERC1155}, {IERC1155MetadataURI} and {IERC1155Receiver}.
|
||||
|
||||
{ERC1155} implements the mandatory {IERC1155} interface, as well as the optional extension {IERC1155MetadataURI}, by relying on the substitution mechanism to use the same URI for all token types, dramatically reducing gas costs.
|
||||
|
||||
Additionally there are multiple custom extensions, including:
|
||||
|
||||
* designation of addresses that can pause token transfers for all users ({ERC1155Pausable}).
|
||||
* destruction of own tokens ({ERC1155Burnable}).
|
||||
|
||||
NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC-1155 (such as <<ERC1155-_mint-address-uint256-uint256-bytes-,`_mint`>>) and expose them as external functions in the way they prefer.
|
||||
|
||||
== Core
|
||||
|
||||
{{IERC1155}}
|
||||
|
||||
{{IERC1155MetadataURI}}
|
||||
|
||||
{{ERC1155}}
|
||||
|
||||
{{IERC1155Receiver}}
|
||||
|
||||
== Extensions
|
||||
|
||||
{{ERC1155Pausable}}
|
||||
|
||||
{{ERC1155Burnable}}
|
||||
|
||||
{{ERC1155Supply}}
|
||||
|
||||
{{ERC1155URIStorage}}
|
||||
|
||||
== Utilities
|
||||
|
||||
{{ERC1155Holder}}
|
||||
@@ -0,0 +1,28 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/ERC1155Burnable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC1155} from "../ERC1155.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {ERC1155} that allows token holders to destroy both their
|
||||
* own tokens and those that they have been approved to use.
|
||||
*/
|
||||
abstract contract ERC1155Burnable is ERC1155 {
|
||||
function burn(address account, uint256 id, uint256 value) public virtual {
|
||||
if (account != _msgSender() && !isApprovedForAll(account, _msgSender())) {
|
||||
revert ERC1155MissingApprovalForAll(_msgSender(), account);
|
||||
}
|
||||
|
||||
_burn(account, id, value);
|
||||
}
|
||||
|
||||
function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public virtual {
|
||||
if (account != _msgSender() && !isApprovedForAll(account, _msgSender())) {
|
||||
revert ERC1155MissingApprovalForAll(_msgSender(), account);
|
||||
}
|
||||
|
||||
_burnBatch(account, ids, values);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/ERC1155Pausable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC1155} from "../ERC1155.sol";
|
||||
import {Pausable} from "../../../utils/Pausable.sol";
|
||||
|
||||
/**
|
||||
* @dev ERC-1155 token with pausable token transfers, minting and burning.
|
||||
*
|
||||
* Useful for scenarios such as preventing trades until the end of an evaluation
|
||||
* period, or having an emergency switch for freezing all token transfers in the
|
||||
* event of a large bug.
|
||||
*
|
||||
* IMPORTANT: This contract does not include public pause and unpause functions. In
|
||||
* addition to inheriting this contract, you must define both functions, invoking the
|
||||
* {Pausable-_pause} and {Pausable-_unpause} internal functions, with appropriate
|
||||
* access control, e.g. using {AccessControl} or {Ownable}. Not doing so will
|
||||
* make the contract pause mechanism of the contract unreachable, and thus unusable.
|
||||
*/
|
||||
abstract contract ERC1155Pausable is ERC1155, Pausable {
|
||||
/**
|
||||
* @dev See {ERC1155-_update}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the contract must not be paused.
|
||||
*/
|
||||
function _update(
|
||||
address from,
|
||||
address to,
|
||||
uint256[] memory ids,
|
||||
uint256[] memory values
|
||||
) internal virtual override whenNotPaused {
|
||||
super._update(from, to, ids, values);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/ERC1155Supply.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC1155} from "../ERC1155.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of ERC-1155 that adds tracking of total supply per id.
|
||||
*
|
||||
* Useful for scenarios where Fungible and Non-fungible tokens have to be
|
||||
* clearly identified. Note: While a totalSupply of 1 might mean the
|
||||
* corresponding is an NFT, there is no guarantees that no other token with the
|
||||
* same id are not going to be minted.
|
||||
*
|
||||
* NOTE: This contract implies a global limit of 2**256 - 1 to the number of tokens
|
||||
* that can be minted.
|
||||
*
|
||||
* CAUTION: This extension should not be added in an upgrade to an already deployed contract.
|
||||
*/
|
||||
abstract contract ERC1155Supply is ERC1155 {
|
||||
mapping(uint256 id => uint256) private _totalSupply;
|
||||
uint256 private _totalSupplyAll;
|
||||
|
||||
/**
|
||||
* @dev Total value of tokens in with a given id.
|
||||
*/
|
||||
function totalSupply(uint256 id) public view virtual returns (uint256) {
|
||||
return _totalSupply[id];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Total value of tokens.
|
||||
*/
|
||||
function totalSupply() public view virtual returns (uint256) {
|
||||
return _totalSupplyAll;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Indicates whether any token exist with a given id, or not.
|
||||
*/
|
||||
function exists(uint256 id) public view virtual returns (bool) {
|
||||
return totalSupply(id) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {ERC1155-_update}.
|
||||
*/
|
||||
function _update(
|
||||
address from,
|
||||
address to,
|
||||
uint256[] memory ids,
|
||||
uint256[] memory values
|
||||
) internal virtual override {
|
||||
super._update(from, to, ids, values);
|
||||
|
||||
if (from == address(0)) {
|
||||
uint256 totalMintValue = 0;
|
||||
for (uint256 i = 0; i < ids.length; ++i) {
|
||||
uint256 value = values[i];
|
||||
// Overflow check required: The rest of the code assumes that totalSupply never overflows
|
||||
_totalSupply[ids[i]] += value;
|
||||
totalMintValue += value;
|
||||
}
|
||||
// Overflow check required: The rest of the code assumes that totalSupplyAll never overflows
|
||||
_totalSupplyAll += totalMintValue;
|
||||
}
|
||||
|
||||
if (to == address(0)) {
|
||||
uint256 totalBurnValue = 0;
|
||||
for (uint256 i = 0; i < ids.length; ++i) {
|
||||
uint256 value = values[i];
|
||||
|
||||
unchecked {
|
||||
// Overflow not possible: values[i] <= balanceOf(from, ids[i]) <= totalSupply(ids[i])
|
||||
_totalSupply[ids[i]] -= value;
|
||||
// Overflow not possible: sum_i(values[i]) <= sum_i(totalSupply(ids[i])) <= totalSupplyAll
|
||||
totalBurnValue += value;
|
||||
}
|
||||
}
|
||||
unchecked {
|
||||
// Overflow not possible: totalBurnValue = sum_i(values[i]) <= sum_i(totalSupply(ids[i])) <= totalSupplyAll
|
||||
_totalSupplyAll -= totalBurnValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/ERC1155URIStorage.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {Strings} from "../../../utils/Strings.sol";
|
||||
import {ERC1155} from "../ERC1155.sol";
|
||||
|
||||
/**
|
||||
* @dev ERC-1155 token with storage based token URI management.
|
||||
* Inspired by the {ERC721URIStorage} extension
|
||||
*/
|
||||
abstract contract ERC1155URIStorage is ERC1155 {
|
||||
using Strings for uint256;
|
||||
|
||||
// Optional base URI
|
||||
string private _baseURI = "";
|
||||
|
||||
// Optional mapping for token URIs
|
||||
mapping(uint256 tokenId => string) private _tokenURIs;
|
||||
|
||||
/**
|
||||
* @dev See {IERC1155MetadataURI-uri}.
|
||||
*
|
||||
* This implementation returns the concatenation of the `_baseURI`
|
||||
* and the token-specific uri if the latter is set
|
||||
*
|
||||
* This enables the following behaviors:
|
||||
*
|
||||
* - if `_tokenURIs[tokenId]` is set, then the result is the concatenation
|
||||
* of `_baseURI` and `_tokenURIs[tokenId]` (keep in mind that `_baseURI`
|
||||
* is empty per default);
|
||||
*
|
||||
* - if `_tokenURIs[tokenId]` is NOT set then we fallback to `super.uri()`
|
||||
* which in most cases will contain `ERC1155._uri`;
|
||||
*
|
||||
* - if `_tokenURIs[tokenId]` is NOT set, and if the parents do not have a
|
||||
* uri value set, then the result is empty.
|
||||
*/
|
||||
function uri(uint256 tokenId) public view virtual override returns (string memory) {
|
||||
string memory tokenURI = _tokenURIs[tokenId];
|
||||
|
||||
// If token URI is set, concatenate base URI and tokenURI (via string.concat).
|
||||
return bytes(tokenURI).length > 0 ? string.concat(_baseURI, tokenURI) : super.uri(tokenId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets `tokenURI` as the tokenURI of `tokenId`.
|
||||
*/
|
||||
function _setURI(uint256 tokenId, string memory tokenURI) internal virtual {
|
||||
_tokenURIs[tokenId] = tokenURI;
|
||||
emit URI(uri(tokenId), tokenId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets `baseURI` as the `_baseURI` for all tokens
|
||||
*/
|
||||
function _setBaseURI(string memory baseURI) internal virtual {
|
||||
_baseURI = baseURI;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/IERC1155MetadataURI.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC1155} from "../IERC1155.sol";
|
||||
|
||||
/**
|
||||
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
|
||||
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[ERC].
|
||||
*/
|
||||
interface IERC1155MetadataURI is IERC1155 {
|
||||
/**
|
||||
* @dev Returns the URI for token type `id`.
|
||||
*
|
||||
* If the `\{id\}` substring is present in the URI, it must be replaced by
|
||||
* clients with the actual token type ID.
|
||||
*/
|
||||
function uri(uint256 id) external view returns (string memory);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/utils/ERC1155Holder.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
|
||||
import {IERC1155Receiver} from "../IERC1155Receiver.sol";
|
||||
|
||||
/**
|
||||
* @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC-1155 tokens.
|
||||
*
|
||||
* IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
|
||||
* stuck.
|
||||
*/
|
||||
abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
|
||||
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
function onERC1155Received(
|
||||
address,
|
||||
address,
|
||||
uint256,
|
||||
uint256,
|
||||
bytes memory
|
||||
) public virtual override returns (bytes4) {
|
||||
return this.onERC1155Received.selector;
|
||||
}
|
||||
|
||||
function onERC1155BatchReceived(
|
||||
address,
|
||||
address,
|
||||
uint256[] memory,
|
||||
uint256[] memory,
|
||||
bytes memory
|
||||
) public virtual override returns (bytes4) {
|
||||
return this.onERC1155BatchReceived.selector;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC1155Receiver} from "../IERC1155Receiver.sol";
|
||||
import {IERC1155Errors} from "../../../interfaces/draft-IERC6093.sol";
|
||||
|
||||
/**
|
||||
* @dev Library that provide common ERC-1155 utility functions.
|
||||
*
|
||||
* See https://eips.ethereum.org/EIPS/eip-1155[ERC-1155].
|
||||
*/
|
||||
library ERC1155Utils {
|
||||
/**
|
||||
* @dev Performs an acceptance check for the provided `operator` by calling {IERC1155-onERC1155Received}
|
||||
* on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
|
||||
*
|
||||
* The acceptance call is not executed and treated as a no-op if the target address is doesn't contain code (i.e. an EOA).
|
||||
* Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept
|
||||
* the transfer.
|
||||
*/
|
||||
function checkOnERC1155Received(
|
||||
address operator,
|
||||
address from,
|
||||
address to,
|
||||
uint256 id,
|
||||
uint256 value,
|
||||
bytes memory data
|
||||
) internal {
|
||||
if (to.code.length > 0) {
|
||||
try IERC1155Receiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) {
|
||||
if (response != IERC1155Receiver.onERC1155Received.selector) {
|
||||
// Tokens rejected
|
||||
revert IERC1155Errors.ERC1155InvalidReceiver(to);
|
||||
}
|
||||
} catch (bytes memory reason) {
|
||||
if (reason.length == 0) {
|
||||
// non-IERC1155Receiver implementer
|
||||
revert IERC1155Errors.ERC1155InvalidReceiver(to);
|
||||
} else {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
revert(add(32, reason), mload(reason))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs a batch acceptance check for the provided `operator` by calling {IERC1155-onERC1155BatchReceived}
|
||||
* on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
|
||||
*
|
||||
* The acceptance call is not executed and treated as a no-op if the target address is doesn't contain code (i.e. an EOA).
|
||||
* Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept
|
||||
* the transfer.
|
||||
*/
|
||||
function checkOnERC1155BatchReceived(
|
||||
address operator,
|
||||
address from,
|
||||
address to,
|
||||
uint256[] memory ids,
|
||||
uint256[] memory values,
|
||||
bytes memory data
|
||||
) internal {
|
||||
if (to.code.length > 0) {
|
||||
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (
|
||||
bytes4 response
|
||||
) {
|
||||
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
|
||||
// Tokens rejected
|
||||
revert IERC1155Errors.ERC1155InvalidReceiver(to);
|
||||
}
|
||||
} catch (bytes memory reason) {
|
||||
if (reason.length == 0) {
|
||||
// non-IERC1155Receiver implementer
|
||||
revert IERC1155Errors.ERC1155InvalidReceiver(to);
|
||||
} else {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
revert(add(32, reason), mload(reason))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
312
lib_openzeppelin_contracts/contracts/token/ERC20/ERC20.sol
Normal file
312
lib_openzeppelin_contracts/contracts/token/ERC20/ERC20.sol
Normal file
@@ -0,0 +1,312 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "./IERC20.sol";
|
||||
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
|
||||
import {Context} from "../../utils/Context.sol";
|
||||
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the {IERC20} interface.
|
||||
*
|
||||
* This implementation is agnostic to the way tokens are created. This means
|
||||
* that a supply mechanism has to be added in a derived contract using {_mint}.
|
||||
*
|
||||
* TIP: For a detailed writeup see our guide
|
||||
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
|
||||
* to implement supply mechanisms].
|
||||
*
|
||||
* The default value of {decimals} is 18. To change this, you should override
|
||||
* this function so it returns a different value.
|
||||
*
|
||||
* We have followed general OpenZeppelin Contracts guidelines: functions revert
|
||||
* instead returning `false` on failure. This behavior is nonetheless
|
||||
* conventional and does not conflict with the expectations of ERC-20
|
||||
* applications.
|
||||
*/
|
||||
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
|
||||
mapping(address account => uint256) private _balances;
|
||||
|
||||
mapping(address account => mapping(address spender => uint256)) private _allowances;
|
||||
|
||||
uint256 private _totalSupply;
|
||||
|
||||
string private _name;
|
||||
string private _symbol;
|
||||
|
||||
/**
|
||||
* @dev Sets the values for {name} and {symbol}.
|
||||
*
|
||||
* All two of these values are immutable: they can only be set once during
|
||||
* construction.
|
||||
*/
|
||||
constructor(string memory name_, string memory symbol_) {
|
||||
_name = name_;
|
||||
_symbol = symbol_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the name of the token.
|
||||
*/
|
||||
function name() public view virtual returns (string memory) {
|
||||
return _name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the symbol of the token, usually a shorter version of the
|
||||
* name.
|
||||
*/
|
||||
function symbol() public view virtual returns (string memory) {
|
||||
return _symbol;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the number of decimals used to get its user representation.
|
||||
* For example, if `decimals` equals `2`, a balance of `505` tokens should
|
||||
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
|
||||
*
|
||||
* Tokens usually opt for a value of 18, imitating the relationship between
|
||||
* Ether and Wei. This is the default value returned by this function, unless
|
||||
* it's overridden.
|
||||
*
|
||||
* NOTE: This information is only used for _display_ purposes: it in
|
||||
* no way affects any of the arithmetic of the contract, including
|
||||
* {IERC20-balanceOf} and {IERC20-transfer}.
|
||||
*/
|
||||
function decimals() public view virtual returns (uint8) {
|
||||
return 18;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-totalSupply}.
|
||||
*/
|
||||
function totalSupply() public view virtual returns (uint256) {
|
||||
return _totalSupply;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-balanceOf}.
|
||||
*/
|
||||
function balanceOf(address account) public view virtual returns (uint256) {
|
||||
return _balances[account];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-transfer}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `to` cannot be the zero address.
|
||||
* - the caller must have a balance of at least `value`.
|
||||
*/
|
||||
function transfer(address to, uint256 value) public virtual returns (bool) {
|
||||
address owner = _msgSender();
|
||||
_transfer(owner, to, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-allowance}.
|
||||
*/
|
||||
function allowance(address owner, address spender) public view virtual returns (uint256) {
|
||||
return _allowances[owner][spender];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-approve}.
|
||||
*
|
||||
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
|
||||
* `transferFrom`. This is semantically equivalent to an infinite approval.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `spender` cannot be the zero address.
|
||||
*/
|
||||
function approve(address spender, uint256 value) public virtual returns (bool) {
|
||||
address owner = _msgSender();
|
||||
_approve(owner, spender, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC20-transferFrom}.
|
||||
*
|
||||
* Skips emitting an {Approval} event indicating an allowance update. This is not
|
||||
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
|
||||
*
|
||||
* NOTE: Does not update the allowance if the current allowance
|
||||
* is the maximum `uint256`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `from` and `to` cannot be the zero address.
|
||||
* - `from` must have a balance of at least `value`.
|
||||
* - the caller must have allowance for ``from``'s tokens of at least
|
||||
* `value`.
|
||||
*/
|
||||
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
|
||||
address spender = _msgSender();
|
||||
_spendAllowance(from, spender, value);
|
||||
_transfer(from, to, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from `from` to `to`.
|
||||
*
|
||||
* This internal function is equivalent to {transfer}, and can be used to
|
||||
* e.g. implement automatic token fees, slashing mechanisms, etc.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead.
|
||||
*/
|
||||
function _transfer(address from, address to, uint256 value) internal {
|
||||
if (from == address(0)) {
|
||||
revert ERC20InvalidSender(address(0));
|
||||
}
|
||||
if (to == address(0)) {
|
||||
revert ERC20InvalidReceiver(address(0));
|
||||
}
|
||||
_update(from, to, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
|
||||
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
|
||||
* this function.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function _update(address from, address to, uint256 value) internal virtual {
|
||||
if (from == address(0)) {
|
||||
// Overflow check required: The rest of the code assumes that totalSupply never overflows
|
||||
_totalSupply += value;
|
||||
} else {
|
||||
uint256 fromBalance = _balances[from];
|
||||
if (fromBalance < value) {
|
||||
revert ERC20InsufficientBalance(from, fromBalance, value);
|
||||
}
|
||||
unchecked {
|
||||
// Overflow not possible: value <= fromBalance <= totalSupply.
|
||||
_balances[from] = fromBalance - value;
|
||||
}
|
||||
}
|
||||
|
||||
if (to == address(0)) {
|
||||
unchecked {
|
||||
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
|
||||
_totalSupply -= value;
|
||||
}
|
||||
} else {
|
||||
unchecked {
|
||||
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
|
||||
_balances[to] += value;
|
||||
}
|
||||
}
|
||||
|
||||
emit Transfer(from, to, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
|
||||
* Relies on the `_update` mechanism
|
||||
*
|
||||
* Emits a {Transfer} event with `from` set to the zero address.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead.
|
||||
*/
|
||||
function _mint(address account, uint256 value) internal {
|
||||
if (account == address(0)) {
|
||||
revert ERC20InvalidReceiver(address(0));
|
||||
}
|
||||
_update(address(0), account, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
|
||||
* Relies on the `_update` mechanism.
|
||||
*
|
||||
* Emits a {Transfer} event with `to` set to the zero address.
|
||||
*
|
||||
* NOTE: This function is not virtual, {_update} should be overridden instead
|
||||
*/
|
||||
function _burn(address account, uint256 value) internal {
|
||||
if (account == address(0)) {
|
||||
revert ERC20InvalidSender(address(0));
|
||||
}
|
||||
_update(account, address(0), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
|
||||
*
|
||||
* This internal function is equivalent to `approve`, and can be used to
|
||||
* e.g. set automatic allowances for certain subsystems, etc.
|
||||
*
|
||||
* Emits an {Approval} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `owner` cannot be the zero address.
|
||||
* - `spender` cannot be the zero address.
|
||||
*
|
||||
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
|
||||
*/
|
||||
function _approve(address owner, address spender, uint256 value) internal {
|
||||
_approve(owner, spender, value, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
|
||||
*
|
||||
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
|
||||
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
|
||||
* `Approval` event during `transferFrom` operations.
|
||||
*
|
||||
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
|
||||
* true using the following override:
|
||||
*
|
||||
* ```solidity
|
||||
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
|
||||
* super._approve(owner, spender, value, true);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Requirements are the same as {_approve}.
|
||||
*/
|
||||
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
|
||||
if (owner == address(0)) {
|
||||
revert ERC20InvalidApprover(address(0));
|
||||
}
|
||||
if (spender == address(0)) {
|
||||
revert ERC20InvalidSpender(address(0));
|
||||
}
|
||||
_allowances[owner][spender] = value;
|
||||
if (emitEvent) {
|
||||
emit Approval(owner, spender, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
|
||||
*
|
||||
* Does not update the allowance value in case of infinite allowance.
|
||||
* Revert if not enough allowance is available.
|
||||
*
|
||||
* Does not emit an {Approval} event.
|
||||
*/
|
||||
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
|
||||
uint256 currentAllowance = allowance(owner, spender);
|
||||
if (currentAllowance != type(uint256).max) {
|
||||
if (currentAllowance < value) {
|
||||
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
|
||||
}
|
||||
unchecked {
|
||||
_approve(owner, spender, currentAllowance - value, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
79
lib_openzeppelin_contracts/contracts/token/ERC20/IERC20.sol
Normal file
79
lib_openzeppelin_contracts/contracts/token/ERC20/IERC20.sol
Normal file
@@ -0,0 +1,79 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC-20 standard as defined in the ERC.
|
||||
*/
|
||||
interface IERC20 {
|
||||
/**
|
||||
* @dev Emitted when `value` tokens are moved from one account (`from`) to
|
||||
* another (`to`).
|
||||
*
|
||||
* Note that `value` may be zero.
|
||||
*/
|
||||
event Transfer(address indexed from, address indexed to, uint256 value);
|
||||
|
||||
/**
|
||||
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
|
||||
* a call to {approve}. `value` is the new allowance.
|
||||
*/
|
||||
event Approval(address indexed owner, address indexed spender, uint256 value);
|
||||
|
||||
/**
|
||||
* @dev Returns the value of tokens in existence.
|
||||
*/
|
||||
function totalSupply() external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the value of tokens owned by `account`.
|
||||
*/
|
||||
function balanceOf(address account) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
|
||||
*
|
||||
* Returns a boolean value indicating whether the operation succeeded.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function transfer(address to, uint256 value) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Returns the remaining number of tokens that `spender` will be
|
||||
* allowed to spend on behalf of `owner` through {transferFrom}. This is
|
||||
* zero by default.
|
||||
*
|
||||
* This value changes when {approve} or {transferFrom} are called.
|
||||
*/
|
||||
function allowance(address owner, address spender) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
|
||||
* caller's tokens.
|
||||
*
|
||||
* Returns a boolean value indicating whether the operation succeeded.
|
||||
*
|
||||
* IMPORTANT: Beware that changing an allowance with this method brings the risk
|
||||
* that someone may use both the old and the new allowance by unfortunate
|
||||
* transaction ordering. One possible solution to mitigate this race
|
||||
* condition is to first reduce the spender's allowance to 0 and set the
|
||||
* desired value afterwards:
|
||||
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
|
||||
*
|
||||
* Emits an {Approval} event.
|
||||
*/
|
||||
function approve(address spender, uint256 value) external returns (bool);
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from `from` to `to` using the
|
||||
* allowance mechanism. `value` is then deducted from the caller's
|
||||
* allowance.
|
||||
*
|
||||
* Returns a boolean value indicating whether the operation succeeded.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function transferFrom(address from, address to, uint256 value) external returns (bool);
|
||||
}
|
||||
70
lib_openzeppelin_contracts/contracts/token/ERC20/README.adoc
Normal file
70
lib_openzeppelin_contracts/contracts/token/ERC20/README.adoc
Normal file
@@ -0,0 +1,70 @@
|
||||
= ERC-20
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc20
|
||||
|
||||
This set of interfaces, contracts, and utilities are all related to the https://eips.ethereum.org/EIPS/eip-20[ERC-20 Token Standard].
|
||||
|
||||
TIP: For an overview of ERC-20 tokens and a walk through on how to create a token contract read our xref:ROOT:erc20.adoc[ERC-20 guide].
|
||||
|
||||
There are a few core contracts that implement the behavior specified in the ERC:
|
||||
|
||||
* {IERC20}: the interface all ERC-20 implementations should conform to.
|
||||
* {IERC20Metadata}: the extended ERC-20 interface including the <<ERC20-name,`name`>>, <<ERC20-symbol,`symbol`>> and <<ERC20-decimals,`decimals`>> functions.
|
||||
* {ERC20}: the implementation of the ERC-20 interface, including the <<ERC20-name,`name`>>, <<ERC20-symbol,`symbol`>> and <<ERC20-decimals,`decimals`>> optional standard extension to the base interface.
|
||||
|
||||
Additionally there are multiple custom extensions, including:
|
||||
|
||||
* {ERC20Permit}: gasless approval of tokens (standardized as ERC-2612).
|
||||
* {ERC20Burnable}: destruction of own tokens.
|
||||
* {ERC20Capped}: enforcement of a cap to the total supply when minting tokens.
|
||||
* {ERC20Pausable}: ability to pause token transfers.
|
||||
* {ERC20FlashMint}: token level support for flash loans through the minting and burning of ephemeral tokens (standardized as ERC-3156).
|
||||
* {ERC20Votes}: support for voting and vote delegation.
|
||||
* {ERC20Wrapper}: wrapper to create an ERC-20 backed by another ERC-20, with deposit and withdraw methods. Useful in conjunction with {ERC20Votes}.
|
||||
* {ERC1363}: support for calling the target of a transfer or approval, enabling code execution on the receiver within a single transaction.
|
||||
* {ERC4626}: tokenized vault that manages shares (represented as ERC-20) that are backed by assets (another ERC-20).
|
||||
|
||||
Finally, there are some utilities to interact with ERC-20 contracts in various ways:
|
||||
|
||||
* {SafeERC20}: a wrapper around the interface that eliminates the need to handle boolean return values.
|
||||
|
||||
Other utilities that support ERC-20 assets can be found in codebase:
|
||||
|
||||
* ERC-20 tokens can be timelocked (held tokens for a beneficiary until a specified time) or vested (released following a given schedule) using a {VestingWallet}.
|
||||
|
||||
NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC-20 (such as <<ERC20-_mint-address-uint256-,`_mint`>>) and expose them as external functions in the way they prefer.
|
||||
|
||||
== Core
|
||||
|
||||
{{IERC20}}
|
||||
|
||||
{{IERC20Metadata}}
|
||||
|
||||
{{ERC20}}
|
||||
|
||||
== Extensions
|
||||
|
||||
{{IERC20Permit}}
|
||||
|
||||
{{ERC20Permit}}
|
||||
|
||||
{{ERC20Burnable}}
|
||||
|
||||
{{ERC20Capped}}
|
||||
|
||||
{{ERC20Pausable}}
|
||||
|
||||
{{ERC20Votes}}
|
||||
|
||||
{{ERC20Wrapper}}
|
||||
|
||||
{{ERC20FlashMint}}
|
||||
|
||||
{{ERC1363}}
|
||||
|
||||
{{ERC4626}}
|
||||
|
||||
== Utilities
|
||||
|
||||
{{SafeERC20}}
|
||||
@@ -0,0 +1,198 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
|
||||
|
||||
import {IERC1363} from "../../../interfaces/IERC1363.sol";
|
||||
import {IERC1363Receiver} from "../../../interfaces/IERC1363Receiver.sol";
|
||||
import {IERC1363Spender} from "../../../interfaces/IERC1363Spender.sol";
|
||||
|
||||
/**
|
||||
* @title ERC1363
|
||||
* @dev Extension of {ERC20} tokens that adds support for code execution after transfers and approvals
|
||||
* on recipient contracts. Calls after transfers are enabled through the {ERC1363-transferAndCall} and
|
||||
* {ERC1363-transferFromAndCall} methods while calls after approvals can be made with {ERC1363-approveAndCall}
|
||||
*/
|
||||
abstract contract ERC1363 is ERC20, ERC165, IERC1363 {
|
||||
/**
|
||||
* @dev Indicates a failure with the token `receiver`. Used in transfers.
|
||||
* @param receiver Address to which tokens are being transferred.
|
||||
*/
|
||||
error ERC1363InvalidReceiver(address receiver);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure with the token `spender`. Used in approvals.
|
||||
* @param spender Address that may be allowed to operate on tokens without being their owner.
|
||||
*/
|
||||
error ERC1363InvalidSpender(address spender);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure within the {transfer} part of a transferAndCall operation.
|
||||
*/
|
||||
error ERC1363TransferFailed(address to, uint256 value);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure within the {transferFrom} part of a transferFromAndCall operation.
|
||||
*/
|
||||
error ERC1363TransferFromFailed(address from, address to, uint256 value);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failure within the {approve} part of a approveAndCall operation.
|
||||
*/
|
||||
error ERC1363ApproveFailed(address spender, uint256 value);
|
||||
|
||||
/**
|
||||
* @inheritdoc IERC165
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
|
||||
return interfaceId == type(IERC1363).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from the caller's account to `to`
|
||||
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The target has code (i.e. is a contract).
|
||||
* - The target `to` must implement the {IERC1363Receiver} interface.
|
||||
* - The target must return the {IERC1363Receiver-onTransferReceived} selector to accept the transfer.
|
||||
* - The internal {transfer} must succeed (returned `true`).
|
||||
*/
|
||||
function transferAndCall(address to, uint256 value) public returns (bool) {
|
||||
return transferAndCall(to, value, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of {transferAndCall} that accepts an additional `data` parameter with
|
||||
* no specified format.
|
||||
*/
|
||||
function transferAndCall(address to, uint256 value, bytes memory data) public virtual returns (bool) {
|
||||
if (!transfer(to, value)) {
|
||||
revert ERC1363TransferFailed(to, value);
|
||||
}
|
||||
_checkOnTransferReceived(_msgSender(), to, value, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
|
||||
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The target has code (i.e. is a contract).
|
||||
* - The target `to` must implement the {IERC1363Receiver} interface.
|
||||
* - The target must return the {IERC1363Receiver-onTransferReceived} selector to accept the transfer.
|
||||
* - The internal {transferFrom} must succeed (returned `true`).
|
||||
*/
|
||||
function transferFromAndCall(address from, address to, uint256 value) public returns (bool) {
|
||||
return transferFromAndCall(from, to, value, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of {transferFromAndCall} that accepts an additional `data` parameter with
|
||||
* no specified format.
|
||||
*/
|
||||
function transferFromAndCall(
|
||||
address from,
|
||||
address to,
|
||||
uint256 value,
|
||||
bytes memory data
|
||||
) public virtual returns (bool) {
|
||||
if (!transferFrom(from, to, value)) {
|
||||
revert ERC1363TransferFromFailed(from, to, value);
|
||||
}
|
||||
_checkOnTransferReceived(from, to, value, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
|
||||
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The target has code (i.e. is a contract).
|
||||
* - The target `spender` must implement the {IERC1363Spender} interface.
|
||||
* - The target must return the {IERC1363Spender-onApprovalReceived} selector to accept the approval.
|
||||
* - The internal {approve} must succeed (returned `true`).
|
||||
*/
|
||||
function approveAndCall(address spender, uint256 value) public returns (bool) {
|
||||
return approveAndCall(spender, value, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of {approveAndCall} that accepts an additional `data` parameter with
|
||||
* no specified format.
|
||||
*/
|
||||
function approveAndCall(address spender, uint256 value, bytes memory data) public virtual returns (bool) {
|
||||
if (!approve(spender, value)) {
|
||||
revert ERC1363ApproveFailed(spender, value);
|
||||
}
|
||||
_checkOnApprovalReceived(spender, value, data);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs a call to {IERC1363Receiver-onTransferReceived} on a target address.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The target has code (i.e. is a contract).
|
||||
* - The target `to` must implement the {IERC1363Receiver} interface.
|
||||
* - The target must return the {IERC1363Receiver-onTransferReceived} selector to accept the transfer.
|
||||
*/
|
||||
function _checkOnTransferReceived(address from, address to, uint256 value, bytes memory data) private {
|
||||
if (to.code.length == 0) {
|
||||
revert ERC1363InvalidReceiver(to);
|
||||
}
|
||||
|
||||
try IERC1363Receiver(to).onTransferReceived(_msgSender(), from, value, data) returns (bytes4 retval) {
|
||||
if (retval != IERC1363Receiver.onTransferReceived.selector) {
|
||||
revert ERC1363InvalidReceiver(to);
|
||||
}
|
||||
} catch (bytes memory reason) {
|
||||
if (reason.length == 0) {
|
||||
revert ERC1363InvalidReceiver(to);
|
||||
} else {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
revert(add(32, reason), mload(reason))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs a call to {IERC1363Spender-onApprovalReceived} on a target address.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The target has code (i.e. is a contract).
|
||||
* - The target `spender` must implement the {IERC1363Spender} interface.
|
||||
* - The target must return the {IERC1363Spender-onApprovalReceived} selector to accept the approval.
|
||||
*/
|
||||
function _checkOnApprovalReceived(address spender, uint256 value, bytes memory data) private {
|
||||
if (spender.code.length == 0) {
|
||||
revert ERC1363InvalidSpender(spender);
|
||||
}
|
||||
|
||||
try IERC1363Spender(spender).onApprovalReceived(_msgSender(), value, data) returns (bytes4 retval) {
|
||||
if (retval != IERC1363Spender.onApprovalReceived.selector) {
|
||||
revert ERC1363InvalidSpender(spender);
|
||||
}
|
||||
} catch (bytes memory reason) {
|
||||
if (reason.length == 0) {
|
||||
revert ERC1363InvalidSpender(spender);
|
||||
} else {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
revert(add(32, reason), mload(reason))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
import {Context} from "../../../utils/Context.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {ERC20} that allows token holders to destroy both their own
|
||||
* tokens and those that they have an allowance for, in a way that can be
|
||||
* recognized off-chain (via event analysis).
|
||||
*/
|
||||
abstract contract ERC20Burnable is Context, ERC20 {
|
||||
/**
|
||||
* @dev Destroys a `value` amount of tokens from the caller.
|
||||
*
|
||||
* See {ERC20-_burn}.
|
||||
*/
|
||||
function burn(uint256 value) public virtual {
|
||||
_burn(_msgSender(), value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Destroys a `value` amount of tokens from `account`, deducting from
|
||||
* the caller's allowance.
|
||||
*
|
||||
* See {ERC20-_burn} and {ERC20-allowance}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the caller must have allowance for ``accounts``'s tokens of at least
|
||||
* `value`.
|
||||
*/
|
||||
function burnFrom(address account, uint256 value) public virtual {
|
||||
_spendAllowance(account, _msgSender(), value);
|
||||
_burn(account, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Capped.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
|
||||
*/
|
||||
abstract contract ERC20Capped is ERC20 {
|
||||
uint256 private immutable _cap;
|
||||
|
||||
/**
|
||||
* @dev Total supply cap has been exceeded.
|
||||
*/
|
||||
error ERC20ExceededCap(uint256 increasedSupply, uint256 cap);
|
||||
|
||||
/**
|
||||
* @dev The supplied cap is not a valid cap.
|
||||
*/
|
||||
error ERC20InvalidCap(uint256 cap);
|
||||
|
||||
/**
|
||||
* @dev Sets the value of the `cap`. This value is immutable, it can only be
|
||||
* set once during construction.
|
||||
*/
|
||||
constructor(uint256 cap_) {
|
||||
if (cap_ == 0) {
|
||||
revert ERC20InvalidCap(0);
|
||||
}
|
||||
_cap = cap_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the cap on the token's total supply.
|
||||
*/
|
||||
function cap() public view virtual returns (uint256) {
|
||||
return _cap;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {ERC20-_update}.
|
||||
*/
|
||||
function _update(address from, address to, uint256 value) internal virtual override {
|
||||
super._update(from, to, value);
|
||||
|
||||
if (from == address(0)) {
|
||||
uint256 maxSupply = cap();
|
||||
uint256 supply = totalSupply();
|
||||
if (supply > maxSupply) {
|
||||
revert ERC20ExceededCap(supply, maxSupply);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20FlashMint.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC3156FlashBorrower} from "../../../interfaces/IERC3156FlashBorrower.sol";
|
||||
import {IERC3156FlashLender} from "../../../interfaces/IERC3156FlashLender.sol";
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the ERC-3156 Flash loans extension, as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
|
||||
*
|
||||
* Adds the {flashLoan} method, which provides flash loan support at the token
|
||||
* level. By default there is no fee, but this can be changed by overriding {flashFee}.
|
||||
*
|
||||
* NOTE: When this extension is used along with the {ERC20Capped} or {ERC20Votes} extensions,
|
||||
* {maxFlashLoan} will not correctly reflect the maximum that can be flash minted. We recommend
|
||||
* overriding {maxFlashLoan} so that it correctly reflects the supply cap.
|
||||
*/
|
||||
abstract contract ERC20FlashMint is ERC20, IERC3156FlashLender {
|
||||
bytes32 private constant RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
|
||||
|
||||
/**
|
||||
* @dev The loan token is not valid.
|
||||
*/
|
||||
error ERC3156UnsupportedToken(address token);
|
||||
|
||||
/**
|
||||
* @dev The requested loan exceeds the max loan value for `token`.
|
||||
*/
|
||||
error ERC3156ExceededMaxLoan(uint256 maxLoan);
|
||||
|
||||
/**
|
||||
* @dev The receiver of a flashloan is not a valid {IERC3156FlashBorrower-onFlashLoan} implementer.
|
||||
*/
|
||||
error ERC3156InvalidReceiver(address receiver);
|
||||
|
||||
/**
|
||||
* @dev Returns the maximum amount of tokens available for loan.
|
||||
* @param token The address of the token that is requested.
|
||||
* @return The amount of token that can be loaned.
|
||||
*
|
||||
* NOTE: This function does not consider any form of supply cap, so in case
|
||||
* it's used in a token with a cap like {ERC20Capped}, make sure to override this
|
||||
* function to integrate the cap instead of `type(uint256).max`.
|
||||
*/
|
||||
function maxFlashLoan(address token) public view virtual returns (uint256) {
|
||||
return token == address(this) ? type(uint256).max - totalSupply() : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the fee applied when doing flash loans. This function calls
|
||||
* the {_flashFee} function which returns the fee applied when doing flash
|
||||
* loans.
|
||||
* @param token The token to be flash loaned.
|
||||
* @param value The amount of tokens to be loaned.
|
||||
* @return The fees applied to the corresponding flash loan.
|
||||
*/
|
||||
function flashFee(address token, uint256 value) public view virtual returns (uint256) {
|
||||
if (token != address(this)) {
|
||||
revert ERC3156UnsupportedToken(token);
|
||||
}
|
||||
return _flashFee(token, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the fee applied when doing flash loans. By default this
|
||||
* implementation has 0 fees. This function can be overloaded to make
|
||||
* the flash loan mechanism deflationary.
|
||||
* @param token The token to be flash loaned.
|
||||
* @param value The amount of tokens to be loaned.
|
||||
* @return The fees applied to the corresponding flash loan.
|
||||
*/
|
||||
function _flashFee(address token, uint256 value) internal view virtual returns (uint256) {
|
||||
// silence warning about unused variable without the addition of bytecode.
|
||||
token;
|
||||
value;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the receiver address of the flash fee. By default this
|
||||
* implementation returns the address(0) which means the fee amount will be burnt.
|
||||
* This function can be overloaded to change the fee receiver.
|
||||
* @return The address for which the flash fee will be sent to.
|
||||
*/
|
||||
function _flashFeeReceiver() internal view virtual returns (address) {
|
||||
return address(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs a flash loan. New tokens are minted and sent to the
|
||||
* `receiver`, who is required to implement the {IERC3156FlashBorrower}
|
||||
* interface. By the end of the flash loan, the receiver is expected to own
|
||||
* value + fee tokens and have them approved back to the token contract itself so
|
||||
* they can be burned.
|
||||
* @param receiver The receiver of the flash loan. Should implement the
|
||||
* {IERC3156FlashBorrower-onFlashLoan} interface.
|
||||
* @param token The token to be flash loaned. Only `address(this)` is
|
||||
* supported.
|
||||
* @param value The amount of tokens to be loaned.
|
||||
* @param data An arbitrary datafield that is passed to the receiver.
|
||||
* @return `true` if the flash loan was successful.
|
||||
*/
|
||||
// This function can reenter, but it doesn't pose a risk because it always preserves the property that the amount
|
||||
// minted at the beginning is always recovered and burned at the end, or else the entire function will revert.
|
||||
// slither-disable-next-line reentrancy-no-eth
|
||||
function flashLoan(
|
||||
IERC3156FlashBorrower receiver,
|
||||
address token,
|
||||
uint256 value,
|
||||
bytes calldata data
|
||||
) public virtual returns (bool) {
|
||||
uint256 maxLoan = maxFlashLoan(token);
|
||||
if (value > maxLoan) {
|
||||
revert ERC3156ExceededMaxLoan(maxLoan);
|
||||
}
|
||||
uint256 fee = flashFee(token, value);
|
||||
_mint(address(receiver), value);
|
||||
if (receiver.onFlashLoan(_msgSender(), token, value, fee, data) != RETURN_VALUE) {
|
||||
revert ERC3156InvalidReceiver(address(receiver));
|
||||
}
|
||||
address flashFeeReceiver = _flashFeeReceiver();
|
||||
_spendAllowance(address(receiver), address(this), value + fee);
|
||||
if (fee == 0 || flashFeeReceiver == address(0)) {
|
||||
_burn(address(receiver), value + fee);
|
||||
} else {
|
||||
_burn(address(receiver), value);
|
||||
_transfer(address(receiver), flashFeeReceiver, fee);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Pausable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
import {Pausable} from "../../../utils/Pausable.sol";
|
||||
|
||||
/**
|
||||
* @dev ERC-20 token with pausable token transfers, minting and burning.
|
||||
*
|
||||
* Useful for scenarios such as preventing trades until the end of an evaluation
|
||||
* period, or having an emergency switch for freezing all token transfers in the
|
||||
* event of a large bug.
|
||||
*
|
||||
* IMPORTANT: This contract does not include public pause and unpause functions. In
|
||||
* addition to inheriting this contract, you must define both functions, invoking the
|
||||
* {Pausable-_pause} and {Pausable-_unpause} internal functions, with appropriate
|
||||
* access control, e.g. using {AccessControl} or {Ownable}. Not doing so will
|
||||
* make the contract pause mechanism of the contract unreachable, and thus unusable.
|
||||
*/
|
||||
abstract contract ERC20Pausable is ERC20, Pausable {
|
||||
/**
|
||||
* @dev See {ERC20-_update}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the contract must not be paused.
|
||||
*/
|
||||
function _update(address from, address to, uint256 value) internal virtual override whenNotPaused {
|
||||
super._update(from, to, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20Permit} from "./IERC20Permit.sol";
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
|
||||
import {EIP712} from "../../../utils/cryptography/EIP712.sol";
|
||||
import {Nonces} from "../../../utils/Nonces.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
|
||||
*
|
||||
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
|
||||
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
|
||||
* need to send a transaction, and thus is not required to hold Ether at all.
|
||||
*/
|
||||
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
|
||||
bytes32 private constant PERMIT_TYPEHASH =
|
||||
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
|
||||
|
||||
/**
|
||||
* @dev Permit deadline has expired.
|
||||
*/
|
||||
error ERC2612ExpiredSignature(uint256 deadline);
|
||||
|
||||
/**
|
||||
* @dev Mismatched signature.
|
||||
*/
|
||||
error ERC2612InvalidSigner(address signer, address owner);
|
||||
|
||||
/**
|
||||
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
|
||||
*
|
||||
* It's a good idea to use the same `name` that is defined as the ERC-20 token name.
|
||||
*/
|
||||
constructor(string memory name) EIP712(name, "1") {}
|
||||
|
||||
/**
|
||||
* @inheritdoc IERC20Permit
|
||||
*/
|
||||
function permit(
|
||||
address owner,
|
||||
address spender,
|
||||
uint256 value,
|
||||
uint256 deadline,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) public virtual {
|
||||
if (block.timestamp > deadline) {
|
||||
revert ERC2612ExpiredSignature(deadline);
|
||||
}
|
||||
|
||||
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
|
||||
|
||||
bytes32 hash = _hashTypedDataV4(structHash);
|
||||
|
||||
address signer = ECDSA.recover(hash, v, r, s);
|
||||
if (signer != owner) {
|
||||
revert ERC2612InvalidSigner(signer, owner);
|
||||
}
|
||||
|
||||
_approve(owner, spender, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IERC20Permit
|
||||
*/
|
||||
function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
|
||||
return super.nonces(owner);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IERC20Permit
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
|
||||
return _domainSeparatorV4();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Votes.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC20} from "../ERC20.sol";
|
||||
import {Votes} from "../../../governance/utils/Votes.sol";
|
||||
import {Checkpoints} from "../../../utils/structs/Checkpoints.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of ERC-20 to support Compound-like voting and delegation. This version is more generic than Compound's,
|
||||
* and supports token supply up to 2^208^ - 1, while COMP is limited to 2^96^ - 1.
|
||||
*
|
||||
* NOTE: This contract does not provide interface compatibility with Compound's COMP token.
|
||||
*
|
||||
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
|
||||
* by calling the {Votes-delegate} function directly, or by providing a signature to be used with {Votes-delegateBySig}. Voting
|
||||
* power can be queried through the public accessors {Votes-getVotes} and {Votes-getPastVotes}.
|
||||
*
|
||||
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
|
||||
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
|
||||
*/
|
||||
abstract contract ERC20Votes is ERC20, Votes {
|
||||
/**
|
||||
* @dev Total supply cap has been exceeded, introducing a risk of votes overflowing.
|
||||
*/
|
||||
error ERC20ExceededSafeSupply(uint256 increasedSupply, uint256 cap);
|
||||
|
||||
/**
|
||||
* @dev Maximum token supply. Defaults to `type(uint208).max` (2^208^ - 1).
|
||||
*
|
||||
* This maximum is enforced in {_update}. It limits the total supply of the token, which is otherwise a uint256,
|
||||
* so that checkpoints can be stored in the Trace208 structure used by {Votes}. Increasing this value will not
|
||||
* remove the underlying limitation, and will cause {_update} to fail because of a math overflow in
|
||||
* {Votes-_transferVotingUnits}. An override could be used to further restrict the total supply (to a lower value) if
|
||||
* additional logic requires it. When resolving override conflicts on this function, the minimum should be
|
||||
* returned.
|
||||
*/
|
||||
function _maxSupply() internal view virtual returns (uint256) {
|
||||
return type(uint208).max;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Move voting power when tokens are transferred.
|
||||
*
|
||||
* Emits a {IVotes-DelegateVotesChanged} event.
|
||||
*/
|
||||
function _update(address from, address to, uint256 value) internal virtual override {
|
||||
super._update(from, to, value);
|
||||
if (from == address(0)) {
|
||||
uint256 supply = totalSupply();
|
||||
uint256 cap = _maxSupply();
|
||||
if (supply > cap) {
|
||||
revert ERC20ExceededSafeSupply(supply, cap);
|
||||
}
|
||||
}
|
||||
_transferVotingUnits(from, to, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the voting units of an `account`.
|
||||
*
|
||||
* WARNING: Overriding this function may compromise the internal vote accounting.
|
||||
* `ERC20Votes` assumes tokens map to voting units 1:1 and this is not easy to change.
|
||||
*/
|
||||
function _getVotingUnits(address account) internal view virtual override returns (uint256) {
|
||||
return balanceOf(account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Get number of checkpoints for `account`.
|
||||
*/
|
||||
function numCheckpoints(address account) public view virtual returns (uint32) {
|
||||
return _numCheckpoints(account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Get the `pos`-th checkpoint for `account`.
|
||||
*/
|
||||
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoints.Checkpoint208 memory) {
|
||||
return _checkpoints(account, pos);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Wrapper.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
|
||||
import {SafeERC20} from "../utils/SafeERC20.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of the ERC-20 token contract to support token wrapping.
|
||||
*
|
||||
* Users can deposit and withdraw "underlying tokens" and receive a matching number of "wrapped tokens". This is useful
|
||||
* in conjunction with other modules. For example, combining this wrapping mechanism with {ERC20Votes} will allow the
|
||||
* wrapping of an existing "basic" ERC-20 into a governance token.
|
||||
*
|
||||
* WARNING: Any mechanism in which the underlying token changes the {balanceOf} of an account without an explicit transfer
|
||||
* may desynchronize this contract's supply and its underlying balance. Please exercise caution when wrapping tokens that
|
||||
* may undercollateralize the wrapper (i.e. wrapper's total supply is higher than its underlying balance). See {_recover}
|
||||
* for recovering value accrued to the wrapper.
|
||||
*/
|
||||
abstract contract ERC20Wrapper is ERC20 {
|
||||
IERC20 private immutable _underlying;
|
||||
|
||||
/**
|
||||
* @dev The underlying token couldn't be wrapped.
|
||||
*/
|
||||
error ERC20InvalidUnderlying(address token);
|
||||
|
||||
constructor(IERC20 underlyingToken) {
|
||||
if (underlyingToken == this) {
|
||||
revert ERC20InvalidUnderlying(address(this));
|
||||
}
|
||||
_underlying = underlyingToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {ERC20-decimals}.
|
||||
*/
|
||||
function decimals() public view virtual override returns (uint8) {
|
||||
try IERC20Metadata(address(_underlying)).decimals() returns (uint8 value) {
|
||||
return value;
|
||||
} catch {
|
||||
return super.decimals();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the address of the underlying ERC-20 token that is being wrapped.
|
||||
*/
|
||||
function underlying() public view returns (IERC20) {
|
||||
return _underlying;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens.
|
||||
*/
|
||||
function depositFor(address account, uint256 value) public virtual returns (bool) {
|
||||
address sender = _msgSender();
|
||||
if (sender == address(this)) {
|
||||
revert ERC20InvalidSender(address(this));
|
||||
}
|
||||
if (account == address(this)) {
|
||||
revert ERC20InvalidReceiver(account);
|
||||
}
|
||||
SafeERC20.safeTransferFrom(_underlying, sender, address(this), value);
|
||||
_mint(account, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Allow a user to burn a number of wrapped tokens and withdraw the corresponding number of underlying tokens.
|
||||
*/
|
||||
function withdrawTo(address account, uint256 value) public virtual returns (bool) {
|
||||
if (account == address(this)) {
|
||||
revert ERC20InvalidReceiver(account);
|
||||
}
|
||||
_burn(_msgSender(), value);
|
||||
SafeERC20.safeTransfer(_underlying, account, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Mint wrapped token to cover any underlyingTokens that would have been transferred by mistake or acquired from
|
||||
* rebasing mechanisms. Internal function that can be exposed with access control if desired.
|
||||
*/
|
||||
function _recover(address account) internal virtual returns (uint256) {
|
||||
uint256 value = _underlying.balanceOf(address(this)) - totalSupply();
|
||||
_mint(account, value);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
|
||||
import {SafeERC20} from "../utils/SafeERC20.sol";
|
||||
import {IERC4626} from "../../../interfaces/IERC4626.sol";
|
||||
import {Math} from "../../../utils/math/Math.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the ERC-4626 "Tokenized Vault Standard" as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
|
||||
*
|
||||
* This extension allows the minting and burning of "shares" (represented using the ERC-20 inheritance) in exchange for
|
||||
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
|
||||
* the ERC-20 standard. Any additional extensions included along it would affect the "shares" token represented by this
|
||||
* contract and not the "assets" token which is an independent contract.
|
||||
*
|
||||
* [CAUTION]
|
||||
* ====
|
||||
* In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
|
||||
* with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
|
||||
* attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
|
||||
* deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
|
||||
* similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
|
||||
* verifying the amount received is as expected, using a wrapper that performs these checks such as
|
||||
* https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
|
||||
*
|
||||
* Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.
|
||||
* The `_decimalsOffset()` corresponds to an offset in the decimal representation between the underlying asset's decimals
|
||||
* and the vault decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which
|
||||
* itself determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default
|
||||
* offset (0) makes it non-profitable even if an attacker is able to capture value from multiple user deposits, as a result
|
||||
* of the value being captured by the virtual shares (out of the attacker's donation) matching the attacker's expected gains.
|
||||
* With a larger offset, the attack becomes orders of magnitude more expensive than it is profitable. More details about the
|
||||
* underlying math can be found xref:erc4626.adoc#inflation-attack[here].
|
||||
*
|
||||
* The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
|
||||
* to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
|
||||
* will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
|
||||
* bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
|
||||
* `_convertToShares` and `_convertToAssets` functions.
|
||||
*
|
||||
* To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
|
||||
* ====
|
||||
*/
|
||||
abstract contract ERC4626 is ERC20, IERC4626 {
|
||||
using Math for uint256;
|
||||
|
||||
IERC20 private immutable _asset;
|
||||
uint8 private immutable _underlyingDecimals;
|
||||
|
||||
/**
|
||||
* @dev Attempted to deposit more assets than the max amount for `receiver`.
|
||||
*/
|
||||
error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
|
||||
|
||||
/**
|
||||
* @dev Attempted to mint more shares than the max amount for `receiver`.
|
||||
*/
|
||||
error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
|
||||
|
||||
/**
|
||||
* @dev Attempted to withdraw more assets than the max amount for `receiver`.
|
||||
*/
|
||||
error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
|
||||
|
||||
/**
|
||||
* @dev Attempted to redeem more shares than the max amount for `receiver`.
|
||||
*/
|
||||
error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
|
||||
|
||||
/**
|
||||
* @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).
|
||||
*/
|
||||
constructor(IERC20 asset_) {
|
||||
(bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
|
||||
_underlyingDecimals = success ? assetDecimals : 18;
|
||||
_asset = asset_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
|
||||
*/
|
||||
function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
|
||||
(bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
|
||||
abi.encodeCall(IERC20Metadata.decimals, ())
|
||||
);
|
||||
if (success && encodedDecimals.length >= 32) {
|
||||
uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
|
||||
if (returnedDecimals <= type(uint8).max) {
|
||||
return (true, uint8(returnedDecimals));
|
||||
}
|
||||
}
|
||||
return (false, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
|
||||
* "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
|
||||
* asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
|
||||
*
|
||||
* See {IERC20Metadata-decimals}.
|
||||
*/
|
||||
function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
|
||||
return _underlyingDecimals + _decimalsOffset();
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-asset}. */
|
||||
function asset() public view virtual returns (address) {
|
||||
return address(_asset);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-totalAssets}. */
|
||||
function totalAssets() public view virtual returns (uint256) {
|
||||
return _asset.balanceOf(address(this));
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-convertToShares}. */
|
||||
function convertToShares(uint256 assets) public view virtual returns (uint256) {
|
||||
return _convertToShares(assets, Math.Rounding.Floor);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-convertToAssets}. */
|
||||
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
|
||||
return _convertToAssets(shares, Math.Rounding.Floor);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-maxDeposit}. */
|
||||
function maxDeposit(address) public view virtual returns (uint256) {
|
||||
return type(uint256).max;
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-maxMint}. */
|
||||
function maxMint(address) public view virtual returns (uint256) {
|
||||
return type(uint256).max;
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-maxWithdraw}. */
|
||||
function maxWithdraw(address owner) public view virtual returns (uint256) {
|
||||
return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-maxRedeem}. */
|
||||
function maxRedeem(address owner) public view virtual returns (uint256) {
|
||||
return balanceOf(owner);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-previewDeposit}. */
|
||||
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
|
||||
return _convertToShares(assets, Math.Rounding.Floor);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-previewMint}. */
|
||||
function previewMint(uint256 shares) public view virtual returns (uint256) {
|
||||
return _convertToAssets(shares, Math.Rounding.Ceil);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-previewWithdraw}. */
|
||||
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
|
||||
return _convertToShares(assets, Math.Rounding.Ceil);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-previewRedeem}. */
|
||||
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
|
||||
return _convertToAssets(shares, Math.Rounding.Floor);
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-deposit}. */
|
||||
function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
|
||||
uint256 maxAssets = maxDeposit(receiver);
|
||||
if (assets > maxAssets) {
|
||||
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
|
||||
}
|
||||
|
||||
uint256 shares = previewDeposit(assets);
|
||||
_deposit(_msgSender(), receiver, assets, shares);
|
||||
|
||||
return shares;
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-mint}. */
|
||||
function mint(uint256 shares, address receiver) public virtual returns (uint256) {
|
||||
uint256 maxShares = maxMint(receiver);
|
||||
if (shares > maxShares) {
|
||||
revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
|
||||
}
|
||||
|
||||
uint256 assets = previewMint(shares);
|
||||
_deposit(_msgSender(), receiver, assets, shares);
|
||||
|
||||
return assets;
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-withdraw}. */
|
||||
function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
|
||||
uint256 maxAssets = maxWithdraw(owner);
|
||||
if (assets > maxAssets) {
|
||||
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
|
||||
}
|
||||
|
||||
uint256 shares = previewWithdraw(assets);
|
||||
_withdraw(_msgSender(), receiver, owner, assets, shares);
|
||||
|
||||
return shares;
|
||||
}
|
||||
|
||||
/** @dev See {IERC4626-redeem}. */
|
||||
function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
|
||||
uint256 maxShares = maxRedeem(owner);
|
||||
if (shares > maxShares) {
|
||||
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
|
||||
}
|
||||
|
||||
uint256 assets = previewRedeem(shares);
|
||||
_withdraw(_msgSender(), receiver, owner, assets, shares);
|
||||
|
||||
return assets;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal conversion function (from assets to shares) with support for rounding direction.
|
||||
*/
|
||||
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
|
||||
return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Internal conversion function (from shares to assets) with support for rounding direction.
|
||||
*/
|
||||
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
|
||||
return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Deposit/mint common workflow.
|
||||
*/
|
||||
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
|
||||
// If _asset is ERC-777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
|
||||
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
|
||||
// calls the vault, which is assumed not malicious.
|
||||
//
|
||||
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
|
||||
// assets are transferred and before the shares are minted, which is a valid state.
|
||||
// slither-disable-next-line reentrancy-no-eth
|
||||
SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
|
||||
_mint(receiver, shares);
|
||||
|
||||
emit Deposit(caller, receiver, assets, shares);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Withdraw/redeem common workflow.
|
||||
*/
|
||||
function _withdraw(
|
||||
address caller,
|
||||
address receiver,
|
||||
address owner,
|
||||
uint256 assets,
|
||||
uint256 shares
|
||||
) internal virtual {
|
||||
if (caller != owner) {
|
||||
_spendAllowance(owner, caller, shares);
|
||||
}
|
||||
|
||||
// If _asset is ERC-777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
|
||||
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
|
||||
// calls the vault, which is assumed not malicious.
|
||||
//
|
||||
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
|
||||
// shares are burned and after the assets are transferred, which is a valid state.
|
||||
_burn(owner, shares);
|
||||
SafeERC20.safeTransfer(_asset, receiver, assets);
|
||||
|
||||
emit Withdraw(caller, receiver, owner, assets, shares);
|
||||
}
|
||||
|
||||
function _decimalsOffset() internal view virtual returns (uint8) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "../IERC20.sol";
|
||||
|
||||
/**
|
||||
* @dev Interface for the optional metadata functions from the ERC-20 standard.
|
||||
*/
|
||||
interface IERC20Metadata is IERC20 {
|
||||
/**
|
||||
* @dev Returns the name of the token.
|
||||
*/
|
||||
function name() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @dev Returns the symbol of the token.
|
||||
*/
|
||||
function symbol() external view returns (string memory);
|
||||
|
||||
/**
|
||||
* @dev Returns the decimals places of the token.
|
||||
*/
|
||||
function decimals() external view returns (uint8);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
|
||||
*
|
||||
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
|
||||
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
|
||||
* need to send a transaction, and thus is not required to hold Ether at all.
|
||||
*
|
||||
* ==== Security Considerations
|
||||
*
|
||||
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
|
||||
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
|
||||
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
|
||||
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
|
||||
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
|
||||
* generally recommended is:
|
||||
*
|
||||
* ```solidity
|
||||
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
|
||||
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
|
||||
* doThing(..., value);
|
||||
* }
|
||||
*
|
||||
* function doThing(..., uint256 value) public {
|
||||
* token.safeTransferFrom(msg.sender, address(this), value);
|
||||
* ...
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
|
||||
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
|
||||
* {SafeERC20-safeTransferFrom}).
|
||||
*
|
||||
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
|
||||
* contracts should have entry points that don't rely on permit.
|
||||
*/
|
||||
interface IERC20Permit {
|
||||
/**
|
||||
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
|
||||
* given ``owner``'s signed approval.
|
||||
*
|
||||
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
|
||||
* ordering also apply here.
|
||||
*
|
||||
* Emits an {Approval} event.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `spender` cannot be the zero address.
|
||||
* - `deadline` must be a timestamp in the future.
|
||||
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
|
||||
* over the EIP712-formatted function arguments.
|
||||
* - the signature must use ``owner``'s current nonce (see {nonces}).
|
||||
*
|
||||
* For more information on the signature format, see the
|
||||
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
|
||||
* section].
|
||||
*
|
||||
* CAUTION: See Security Considerations above.
|
||||
*/
|
||||
function permit(
|
||||
address owner,
|
||||
address spender,
|
||||
uint256 value,
|
||||
uint256 deadline,
|
||||
uint8 v,
|
||||
bytes32 r,
|
||||
bytes32 s
|
||||
) external;
|
||||
|
||||
/**
|
||||
* @dev Returns the current nonce for `owner`. This value must be
|
||||
* included whenever a signature is generated for {permit}.
|
||||
*
|
||||
* Every successful call to {permit} increases ``owner``'s nonce by one. This
|
||||
* prevents a signature from being used multiple times.
|
||||
*/
|
||||
function nonces(address owner) external view returns (uint256);
|
||||
|
||||
/**
|
||||
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
|
||||
*/
|
||||
// solhint-disable-next-line func-name-mixedcase
|
||||
function DOMAIN_SEPARATOR() external view returns (bytes32);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC20} from "../IERC20.sol";
|
||||
import {IERC1363} from "../../../interfaces/IERC1363.sol";
|
||||
import {Address} from "../../../utils/Address.sol";
|
||||
|
||||
/**
|
||||
* @title SafeERC20
|
||||
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
|
||||
* contract returns false). Tokens that return no value (and instead revert or
|
||||
* throw on failure) are also supported, non-reverting calls are assumed to be
|
||||
* successful.
|
||||
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
|
||||
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
|
||||
*/
|
||||
library SafeERC20 {
|
||||
using Address for address;
|
||||
|
||||
/**
|
||||
* @dev An operation with an ERC-20 token failed.
|
||||
*/
|
||||
error SafeERC20FailedOperation(address token);
|
||||
|
||||
/**
|
||||
* @dev Indicates a failed `decreaseAllowance` request.
|
||||
*/
|
||||
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
|
||||
|
||||
/**
|
||||
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
|
||||
* non-reverting calls are assumed to be successful.
|
||||
*/
|
||||
function safeTransfer(IERC20 token, address to, uint256 value) internal {
|
||||
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
|
||||
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
|
||||
*/
|
||||
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
|
||||
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
|
||||
* non-reverting calls are assumed to be successful.
|
||||
*/
|
||||
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
|
||||
uint256 oldAllowance = token.allowance(address(this), spender);
|
||||
forceApprove(token, spender, oldAllowance + value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
|
||||
* value, non-reverting calls are assumed to be successful.
|
||||
*/
|
||||
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
|
||||
unchecked {
|
||||
uint256 currentAllowance = token.allowance(address(this), spender);
|
||||
if (currentAllowance < requestedDecrease) {
|
||||
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
|
||||
}
|
||||
forceApprove(token, spender, currentAllowance - requestedDecrease);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
|
||||
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
|
||||
* to be set to zero before setting it to a non-zero value, such as USDT.
|
||||
*/
|
||||
function forceApprove(IERC20 token, address spender, uint256 value) internal {
|
||||
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
|
||||
|
||||
if (!_callOptionalReturnBool(token, approvalCall)) {
|
||||
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
|
||||
_callOptionalReturn(token, approvalCall);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
|
||||
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
|
||||
* targeting contracts.
|
||||
*
|
||||
* Reverts if the returned value is other than `true`.
|
||||
*/
|
||||
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
|
||||
if (to.code.length == 0) {
|
||||
safeTransfer(token, to, value);
|
||||
} else if (!token.transferAndCall(to, value, data)) {
|
||||
revert SafeERC20FailedOperation(address(token));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
|
||||
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
|
||||
* targeting contracts.
|
||||
*
|
||||
* Reverts if the returned value is other than `true`.
|
||||
*/
|
||||
function transferFromAndCallRelaxed(
|
||||
IERC1363 token,
|
||||
address from,
|
||||
address to,
|
||||
uint256 value,
|
||||
bytes memory data
|
||||
) internal {
|
||||
if (to.code.length == 0) {
|
||||
safeTransferFrom(token, from, to, value);
|
||||
} else if (!token.transferFromAndCall(from, to, value, data)) {
|
||||
revert SafeERC20FailedOperation(address(token));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
|
||||
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
|
||||
* targeting contracts.
|
||||
*
|
||||
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
|
||||
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
|
||||
* once without retrying, and relies on the returned value to be true.
|
||||
*
|
||||
* Reverts if the returned value is other than `true`.
|
||||
*/
|
||||
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
|
||||
if (to.code.length == 0) {
|
||||
forceApprove(token, to, value);
|
||||
} else if (!token.approveAndCall(to, value, data)) {
|
||||
revert SafeERC20FailedOperation(address(token));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
|
||||
* on the return value: the return value is optional (but if data is returned, it must not be false).
|
||||
* @param token The token targeted by the call.
|
||||
* @param data The call data (encoded using abi.encode or one of its variants).
|
||||
*/
|
||||
function _callOptionalReturn(IERC20 token, bytes memory data) private {
|
||||
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
|
||||
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
|
||||
// the target address contains contract code and also asserts for success in the low-level call.
|
||||
|
||||
bytes memory returndata = address(token).functionCall(data);
|
||||
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
|
||||
revert SafeERC20FailedOperation(address(token));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
|
||||
* on the return value: the return value is optional (but if data is returned, it must not be false).
|
||||
* @param token The token targeted by the call.
|
||||
* @param data The call data (encoded using abi.encode or one of its variants).
|
||||
*
|
||||
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
|
||||
*/
|
||||
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
|
||||
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
|
||||
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
|
||||
// and not revert is the subcall reverts.
|
||||
|
||||
(bool success, bytes memory returndata) = address(token).call(data);
|
||||
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
|
||||
}
|
||||
}
|
||||
455
lib_openzeppelin_contracts/contracts/token/ERC721/ERC721.sol
Normal file
455
lib_openzeppelin_contracts/contracts/token/ERC721/ERC721.sol
Normal file
@@ -0,0 +1,455 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721} from "./IERC721.sol";
|
||||
import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
|
||||
import {ERC721Utils} from "./utils/ERC721Utils.sol";
|
||||
import {Context} from "../../utils/Context.sol";
|
||||
import {Strings} from "../../utils/Strings.sol";
|
||||
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
|
||||
import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including
|
||||
* the Metadata extension, but not including the Enumerable extension, which is available separately as
|
||||
* {ERC721Enumerable}.
|
||||
*/
|
||||
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
|
||||
using Strings for uint256;
|
||||
|
||||
// Token name
|
||||
string private _name;
|
||||
|
||||
// Token symbol
|
||||
string private _symbol;
|
||||
|
||||
mapping(uint256 tokenId => address) private _owners;
|
||||
|
||||
mapping(address owner => uint256) private _balances;
|
||||
|
||||
mapping(uint256 tokenId => address) private _tokenApprovals;
|
||||
|
||||
mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;
|
||||
|
||||
/**
|
||||
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
|
||||
*/
|
||||
constructor(string memory name_, string memory symbol_) {
|
||||
_name = name_;
|
||||
_symbol = symbol_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
|
||||
return
|
||||
interfaceId == type(IERC721).interfaceId ||
|
||||
interfaceId == type(IERC721Metadata).interfaceId ||
|
||||
super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-balanceOf}.
|
||||
*/
|
||||
function balanceOf(address owner) public view virtual returns (uint256) {
|
||||
if (owner == address(0)) {
|
||||
revert ERC721InvalidOwner(address(0));
|
||||
}
|
||||
return _balances[owner];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-ownerOf}.
|
||||
*/
|
||||
function ownerOf(uint256 tokenId) public view virtual returns (address) {
|
||||
return _requireOwned(tokenId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Metadata-name}.
|
||||
*/
|
||||
function name() public view virtual returns (string memory) {
|
||||
return _name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Metadata-symbol}.
|
||||
*/
|
||||
function symbol() public view virtual returns (string memory) {
|
||||
return _symbol;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Metadata-tokenURI}.
|
||||
*/
|
||||
function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
|
||||
_requireOwned(tokenId);
|
||||
|
||||
string memory baseURI = _baseURI();
|
||||
return bytes(baseURI).length > 0 ? string.concat(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 {
|
||||
_approve(to, tokenId, _msgSender());
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-getApproved}.
|
||||
*/
|
||||
function getApproved(uint256 tokenId) public view virtual returns (address) {
|
||||
_requireOwned(tokenId);
|
||||
|
||||
return _getApproved(tokenId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-setApprovalForAll}.
|
||||
*/
|
||||
function setApprovalForAll(address operator, bool approved) public virtual {
|
||||
_setApprovalForAll(_msgSender(), operator, approved);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-isApprovedForAll}.
|
||||
*/
|
||||
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
|
||||
return _operatorApprovals[owner][operator];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-transferFrom}.
|
||||
*/
|
||||
function transferFrom(address from, address to, uint256 tokenId) public virtual {
|
||||
if (to == address(0)) {
|
||||
revert ERC721InvalidReceiver(address(0));
|
||||
}
|
||||
// Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
|
||||
// (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
|
||||
address previousOwner = _update(to, tokenId, _msgSender());
|
||||
if (previousOwner != from) {
|
||||
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-safeTransferFrom}.
|
||||
*/
|
||||
function safeTransferFrom(address from, address to, uint256 tokenId) public {
|
||||
safeTransferFrom(from, to, tokenId, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721-safeTransferFrom}.
|
||||
*/
|
||||
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
|
||||
transferFrom(from, to, tokenId);
|
||||
ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
|
||||
*
|
||||
* IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
|
||||
* core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances
|
||||
* consistent with ownership. The invariant to preserve is 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`.
|
||||
*/
|
||||
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
|
||||
return _owners[tokenId];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
|
||||
*/
|
||||
function _getApproved(uint256 tokenId) internal view virtual returns (address) {
|
||||
return _tokenApprovals[tokenId];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
|
||||
* particular (ignoring whether it is owned by `owner`).
|
||||
*
|
||||
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
|
||||
* assumption.
|
||||
*/
|
||||
function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
|
||||
return
|
||||
spender != address(0) &&
|
||||
(owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
|
||||
* Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets
|
||||
* the `spender` for the specific `tokenId`.
|
||||
*
|
||||
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
|
||||
* assumption.
|
||||
*/
|
||||
function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
|
||||
if (!_isAuthorized(owner, spender, tokenId)) {
|
||||
if (owner == address(0)) {
|
||||
revert ERC721NonexistentToken(tokenId);
|
||||
} else {
|
||||
revert ERC721InsufficientApproval(spender, tokenId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
|
||||
*
|
||||
* NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
|
||||
* a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
|
||||
*
|
||||
* WARNING: Increasing an account's balance using this function tends to be paired with an override of the
|
||||
* {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
|
||||
* remain consistent with one another.
|
||||
*/
|
||||
function _increaseBalance(address account, uint128 value) internal virtual {
|
||||
unchecked {
|
||||
_balances[account] += value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
|
||||
* (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
|
||||
*
|
||||
* The `auth` argument is optional. If the value passed is non 0, then this function will check that
|
||||
* `auth` is either the owner of the token, or approved to operate on the token (by the owner).
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*
|
||||
* NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
|
||||
*/
|
||||
function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
|
||||
address from = _ownerOf(tokenId);
|
||||
|
||||
// Perform (optional) operator check
|
||||
if (auth != address(0)) {
|
||||
_checkAuthorized(from, auth, tokenId);
|
||||
}
|
||||
|
||||
// Execute the update
|
||||
if (from != address(0)) {
|
||||
// Clear approval. No need to re-authorize or emit the Approval event
|
||||
_approve(address(0), tokenId, address(0), false);
|
||||
|
||||
unchecked {
|
||||
_balances[from] -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (to != address(0)) {
|
||||
unchecked {
|
||||
_balances[to] += 1;
|
||||
}
|
||||
}
|
||||
|
||||
_owners[tokenId] = to;
|
||||
|
||||
emit Transfer(from, to, tokenId);
|
||||
|
||||
return from;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 {
|
||||
if (to == address(0)) {
|
||||
revert ERC721InvalidReceiver(address(0));
|
||||
}
|
||||
address previousOwner = _update(to, tokenId, address(0));
|
||||
if (previousOwner != address(0)) {
|
||||
revert ERC721InvalidSender(address(0));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
|
||||
*
|
||||
* 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 {
|
||||
_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);
|
||||
ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 {
|
||||
address previousOwner = _update(address(0), tokenId, address(0));
|
||||
if (previousOwner == address(0)) {
|
||||
revert ERC721NonexistentToken(tokenId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 {
|
||||
if (to == address(0)) {
|
||||
revert ERC721InvalidReceiver(address(0));
|
||||
}
|
||||
address previousOwner = _update(to, tokenId, address(0));
|
||||
if (previousOwner == address(0)) {
|
||||
revert ERC721NonexistentToken(tokenId);
|
||||
} else if (previousOwner != from) {
|
||||
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
|
||||
* are aware of the ERC-721 standard 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 like {safeTransferFrom} in the sense that it invokes
|
||||
* {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
|
||||
* implement alternative mechanisms to perform token transfer, such as signature-based.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `tokenId` token must exist and be owned by `from`.
|
||||
* - `to` cannot be the zero address.
|
||||
* - `from` cannot be the zero address.
|
||||
* - 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) internal {
|
||||
_safeTransfer(from, to, tokenId, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
|
||||
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
|
||||
*/
|
||||
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
|
||||
_transfer(from, to, tokenId);
|
||||
ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Approve `to` to operate on `tokenId`
|
||||
*
|
||||
* The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
|
||||
* either the owner of the token, or approved to operate on all tokens held by this owner.
|
||||
*
|
||||
* Emits an {Approval} event.
|
||||
*
|
||||
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
|
||||
*/
|
||||
function _approve(address to, uint256 tokenId, address auth) internal {
|
||||
_approve(to, tokenId, auth, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
|
||||
* emitted in the context of transfers.
|
||||
*/
|
||||
function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
|
||||
// Avoid reading the owner unless necessary
|
||||
if (emitEvent || auth != address(0)) {
|
||||
address owner = _requireOwned(tokenId);
|
||||
|
||||
// We do not use _isAuthorized because single-token approvals should not be able to call approve
|
||||
if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
|
||||
revert ERC721InvalidApprover(auth);
|
||||
}
|
||||
|
||||
if (emitEvent) {
|
||||
emit Approval(owner, to, tokenId);
|
||||
}
|
||||
}
|
||||
|
||||
_tokenApprovals[tokenId] = to;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Approve `operator` to operate on all of `owner` tokens
|
||||
*
|
||||
* Requirements:
|
||||
* - operator can't be the address zero.
|
||||
*
|
||||
* Emits an {ApprovalForAll} event.
|
||||
*/
|
||||
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
|
||||
if (operator == address(0)) {
|
||||
revert ERC721InvalidOperator(operator);
|
||||
}
|
||||
_operatorApprovals[owner][operator] = approved;
|
||||
emit ApprovalForAll(owner, operator, approved);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
|
||||
* Returns the owner.
|
||||
*
|
||||
* Overrides to ownership logic should be done to {_ownerOf}.
|
||||
*/
|
||||
function _requireOwned(uint256 tokenId) internal view returns (address) {
|
||||
address owner = _ownerOf(tokenId);
|
||||
if (owner == address(0)) {
|
||||
revert ERC721NonexistentToken(tokenId);
|
||||
}
|
||||
return owner;
|
||||
}
|
||||
}
|
||||
135
lib_openzeppelin_contracts/contracts/token/ERC721/IERC721.sol
Normal file
135
lib_openzeppelin_contracts/contracts/token/ERC721/IERC721.sol
Normal file
@@ -0,0 +1,135 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC165} from "../../utils/introspection/IERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev Required interface of an ERC-721 compliant contract.
|
||||
*/
|
||||
interface IERC721 is IERC165 {
|
||||
/**
|
||||
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
|
||||
*/
|
||||
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
|
||||
*/
|
||||
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
|
||||
|
||||
/**
|
||||
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
|
||||
*/
|
||||
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
|
||||
|
||||
/**
|
||||
* @dev Returns the number of tokens in ``owner``'s account.
|
||||
*/
|
||||
function balanceOf(address owner) external view returns (uint256 balance);
|
||||
|
||||
/**
|
||||
* @dev Returns the owner of the `tokenId` token.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `tokenId` must exist.
|
||||
*/
|
||||
function ownerOf(uint256 tokenId) external view returns (address owner);
|
||||
|
||||
/**
|
||||
* @dev Safely transfers `tokenId` token from `from` to `to`.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `from` cannot be the zero address.
|
||||
* - `to` cannot be the zero address.
|
||||
* - `tokenId` token must exist and be owned by `from`.
|
||||
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
|
||||
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
|
||||
* a safe transfer.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
|
||||
|
||||
/**
|
||||
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
|
||||
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `from` cannot be the zero address.
|
||||
* - `to` cannot be the zero address.
|
||||
* - `tokenId` token must exist and be owned by `from`.
|
||||
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
|
||||
* {setApprovalForAll}.
|
||||
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
|
||||
* a safe transfer.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function safeTransferFrom(address from, address to, uint256 tokenId) external;
|
||||
|
||||
/**
|
||||
* @dev Transfers `tokenId` token from `from` to `to`.
|
||||
*
|
||||
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
|
||||
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
|
||||
* understand this adds an external call which potentially creates a reentrancy vulnerability.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `from` cannot be the zero address.
|
||||
* - `to` cannot be the zero address.
|
||||
* - `tokenId` token must be owned by `from`.
|
||||
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
|
||||
*
|
||||
* Emits a {Transfer} event.
|
||||
*/
|
||||
function transferFrom(address from, address to, uint256 tokenId) external;
|
||||
|
||||
/**
|
||||
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
|
||||
* The approval is cleared when the token is transferred.
|
||||
*
|
||||
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The caller must own the token or be an approved operator.
|
||||
* - `tokenId` must exist.
|
||||
*
|
||||
* Emits an {Approval} event.
|
||||
*/
|
||||
function approve(address to, uint256 tokenId) external;
|
||||
|
||||
/**
|
||||
* @dev Approve or remove `operator` as an operator for the caller.
|
||||
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The `operator` cannot be the address zero.
|
||||
*
|
||||
* Emits an {ApprovalForAll} event.
|
||||
*/
|
||||
function setApprovalForAll(address operator, bool approved) external;
|
||||
|
||||
/**
|
||||
* @dev Returns the account approved for `tokenId` token.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `tokenId` must exist.
|
||||
*/
|
||||
function getApproved(uint256 tokenId) external view returns (address operator);
|
||||
|
||||
/**
|
||||
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
|
||||
*
|
||||
* See {setApprovalForAll}
|
||||
*/
|
||||
function isApprovedForAll(address owner, address operator) external view returns (bool);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
/**
|
||||
* @title ERC-721 token receiver interface
|
||||
* @dev Interface for any contract that wants to support safeTransfers
|
||||
* from ERC-721 asset contracts.
|
||||
*/
|
||||
interface IERC721Receiver {
|
||||
/**
|
||||
* @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);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
= ERC-721
|
||||
|
||||
[.readme-notice]
|
||||
NOTE: This document is better viewed at https://docs.openzeppelin.com/contracts/api/token/erc721
|
||||
|
||||
This set of interfaces, contracts, and utilities are all related to the https://eips.ethereum.org/EIPS/eip-721[ERC-721 Non-Fungible Token Standard].
|
||||
|
||||
TIP: For a walk through on how to create an ERC-721 token read our xref:ROOT:erc721.adoc[ERC-721 guide].
|
||||
|
||||
The ERC specifies four interfaces:
|
||||
|
||||
* {IERC721}: Core functionality required in all compliant implementation.
|
||||
* {IERC721Metadata}: Optional extension that adds name, symbol, and token URI, almost always included.
|
||||
* {IERC721Enumerable}: Optional extension that allows enumerating the tokens on chain, often not included since it requires large gas overhead.
|
||||
* {IERC721Receiver}: An interface that must be implemented by contracts if they want to accept tokens through `safeTransferFrom`.
|
||||
|
||||
OpenZeppelin Contracts provides implementations of all four interfaces:
|
||||
|
||||
* {ERC721}: The core and metadata extensions, with a base URI mechanism.
|
||||
* {ERC721Enumerable}: The enumerable extension.
|
||||
* {ERC721Holder}: A bare bones implementation of the receiver interface.
|
||||
|
||||
Additionally there are a few of other extensions:
|
||||
|
||||
* {ERC721Consecutive}: An implementation of https://eips.ethereum.org/EIPS/eip-2309[ERC-2309] for minting batchs of tokens during construction, in accordance with ERC-721.
|
||||
* {ERC721URIStorage}: A more flexible but more expensive way of storing metadata.
|
||||
* {ERC721Votes}: Support for voting and vote delegation.
|
||||
* {ERC721Royalty}: A way to signal royalty information following ERC-2981.
|
||||
* {ERC721Pausable}: A primitive to pause contract operation.
|
||||
* {ERC721Burnable}: A way for token holders to burn their own tokens.
|
||||
* {ERC721Wrapper}: Wrapper to create an ERC-721 backed by another ERC-721, with deposit and withdraw methods. Useful in conjunction with {ERC721Votes}.
|
||||
|
||||
NOTE: This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC-721 (such as <<ERC721-_mint-address-uint256-,`_mint`>>) and expose them as external functions in the way they prefer.
|
||||
|
||||
== Core
|
||||
|
||||
{{IERC721}}
|
||||
|
||||
{{IERC721Metadata}}
|
||||
|
||||
{{IERC721Enumerable}}
|
||||
|
||||
{{ERC721}}
|
||||
|
||||
{{ERC721Enumerable}}
|
||||
|
||||
{{IERC721Receiver}}
|
||||
|
||||
== Extensions
|
||||
|
||||
{{ERC721Pausable}}
|
||||
|
||||
{{ERC721Burnable}}
|
||||
|
||||
{{ERC721Consecutive}}
|
||||
|
||||
{{ERC721URIStorage}}
|
||||
|
||||
{{ERC721Votes}}
|
||||
|
||||
{{ERC721Royalty}}
|
||||
|
||||
{{ERC721Wrapper}}
|
||||
|
||||
== Utilities
|
||||
|
||||
{{ERC721Holder}}
|
||||
@@ -0,0 +1,26 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Burnable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC721} from "../ERC721.sol";
|
||||
import {Context} from "../../../utils/Context.sol";
|
||||
|
||||
/**
|
||||
* @title ERC-721 Burnable Token
|
||||
* @dev ERC-721 Token that can be burned (destroyed).
|
||||
*/
|
||||
abstract contract ERC721Burnable is Context, ERC721 {
|
||||
/**
|
||||
* @dev Burns `tokenId`. See {ERC721-_burn}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - The caller must own `tokenId` or be an approved operator.
|
||||
*/
|
||||
function burn(uint256 tokenId) public virtual {
|
||||
// Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
|
||||
// (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
|
||||
_update(address(0), tokenId, _msgSender());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Consecutive.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC721} from "../ERC721.sol";
|
||||
import {IERC2309} from "../../../interfaces/IERC2309.sol";
|
||||
import {BitMaps} from "../../../utils/structs/BitMaps.sol";
|
||||
import {Checkpoints} from "../../../utils/structs/Checkpoints.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the ERC-2309 "Consecutive Transfer Extension" as defined in
|
||||
* https://eips.ethereum.org/EIPS/eip-2309[ERC-2309].
|
||||
*
|
||||
* This extension allows the minting of large batches of tokens, during contract construction only. For upgradeable
|
||||
* contracts this implies that batch minting is only available during proxy deployment, and not in subsequent upgrades.
|
||||
* These batches are limited to 5000 tokens at a time by default to accommodate off-chain indexers.
|
||||
*
|
||||
* Using this extension removes the ability to mint single tokens during contract construction. This ability is
|
||||
* regained after construction. During construction, only batch minting is allowed.
|
||||
*
|
||||
* IMPORTANT: This extension does not call the {_update} function for tokens minted in batch. Any logic added to this
|
||||
* function through overrides will not be triggered when token are minted in batch. You may want to also override
|
||||
* {_increaseBalance} or {_mintConsecutive} to account for these mints.
|
||||
*
|
||||
* IMPORTANT: When overriding {_mintConsecutive}, be careful about call ordering. {ownerOf} may return invalid
|
||||
* values during the {_mintConsecutive} execution if the super call is not called first. To be safe, execute the
|
||||
* super call before your custom logic.
|
||||
*/
|
||||
abstract contract ERC721Consecutive is IERC2309, ERC721 {
|
||||
using BitMaps for BitMaps.BitMap;
|
||||
using Checkpoints for Checkpoints.Trace160;
|
||||
|
||||
Checkpoints.Trace160 private _sequentialOwnership;
|
||||
BitMaps.BitMap private _sequentialBurn;
|
||||
|
||||
/**
|
||||
* @dev Batch mint is restricted to the constructor.
|
||||
* Any batch mint not emitting the {IERC721-Transfer} event outside of the constructor
|
||||
* is non ERC-721 compliant.
|
||||
*/
|
||||
error ERC721ForbiddenBatchMint();
|
||||
|
||||
/**
|
||||
* @dev Exceeds the max amount of mints per batch.
|
||||
*/
|
||||
error ERC721ExceededMaxBatchMint(uint256 batchSize, uint256 maxBatch);
|
||||
|
||||
/**
|
||||
* @dev Individual minting is not allowed.
|
||||
*/
|
||||
error ERC721ForbiddenMint();
|
||||
|
||||
/**
|
||||
* @dev Batch burn is not supported.
|
||||
*/
|
||||
error ERC721ForbiddenBatchBurn();
|
||||
|
||||
/**
|
||||
* @dev Maximum size of a batch of consecutive tokens. This is designed to limit stress on off-chain indexing
|
||||
* services that have to record one entry per token, and have protections against "unreasonably large" batches of
|
||||
* tokens.
|
||||
*
|
||||
* NOTE: Overriding the default value of 5000 will not cause on-chain issues, but may result in the asset not being
|
||||
* correctly supported by off-chain indexing services (including marketplaces).
|
||||
*/
|
||||
function _maxBatchSize() internal view virtual returns (uint96) {
|
||||
return 5000;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {ERC721-_ownerOf}. Override that checks the sequential ownership structure for tokens that have
|
||||
* been minted as part of a batch, and not yet transferred.
|
||||
*/
|
||||
function _ownerOf(uint256 tokenId) internal view virtual override returns (address) {
|
||||
address owner = super._ownerOf(tokenId);
|
||||
|
||||
// If token is owned by the core, or beyond consecutive range, return base value
|
||||
if (owner != address(0) || tokenId > type(uint96).max || tokenId < _firstConsecutiveId()) {
|
||||
return owner;
|
||||
}
|
||||
|
||||
// Otherwise, check the token was not burned, and fetch ownership from the anchors
|
||||
// Note: no need for safe cast, we know that tokenId <= type(uint96).max
|
||||
return _sequentialBurn.get(tokenId) ? address(0) : address(_sequentialOwnership.lowerLookup(uint96(tokenId)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Mint a batch of tokens of length `batchSize` for `to`. Returns the token id of the first token minted in the
|
||||
* batch; if `batchSize` is 0, returns the number of consecutive ids minted so far.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `batchSize` must not be greater than {_maxBatchSize}.
|
||||
* - The function is called in the constructor of the contract (directly or indirectly).
|
||||
*
|
||||
* CAUTION: Does not emit a `Transfer` event. This is ERC-721 compliant as long as it is done inside of the
|
||||
* constructor, which is enforced by this function.
|
||||
*
|
||||
* CAUTION: Does not invoke `onERC721Received` on the receiver.
|
||||
*
|
||||
* Emits a {IERC2309-ConsecutiveTransfer} event.
|
||||
*/
|
||||
function _mintConsecutive(address to, uint96 batchSize) internal virtual returns (uint96) {
|
||||
uint96 next = _nextConsecutiveId();
|
||||
|
||||
// minting a batch of size 0 is a no-op
|
||||
if (batchSize > 0) {
|
||||
if (address(this).code.length > 0) {
|
||||
revert ERC721ForbiddenBatchMint();
|
||||
}
|
||||
if (to == address(0)) {
|
||||
revert ERC721InvalidReceiver(address(0));
|
||||
}
|
||||
|
||||
uint256 maxBatchSize = _maxBatchSize();
|
||||
if (batchSize > maxBatchSize) {
|
||||
revert ERC721ExceededMaxBatchMint(batchSize, maxBatchSize);
|
||||
}
|
||||
|
||||
// push an ownership checkpoint & emit event
|
||||
uint96 last = next + batchSize - 1;
|
||||
_sequentialOwnership.push(last, uint160(to));
|
||||
|
||||
// The invariant required by this function is preserved because the new sequentialOwnership checkpoint
|
||||
// is attributing ownership of `batchSize` new tokens to account `to`.
|
||||
_increaseBalance(to, batchSize);
|
||||
|
||||
emit ConsecutiveTransfer(next, last, address(0), to);
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {ERC721-_update}. Override version that restricts normal minting to after construction.
|
||||
*
|
||||
* WARNING: Using {ERC721Consecutive} prevents minting during construction in favor of {_mintConsecutive}.
|
||||
* After construction, {_mintConsecutive} is no longer available and minting through {_update} becomes available.
|
||||
*/
|
||||
function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {
|
||||
address previousOwner = super._update(to, tokenId, auth);
|
||||
|
||||
// only mint after construction
|
||||
if (previousOwner == address(0) && address(this).code.length == 0) {
|
||||
revert ERC721ForbiddenMint();
|
||||
}
|
||||
|
||||
// record burn
|
||||
if (
|
||||
to == address(0) && // if we burn
|
||||
tokenId < _nextConsecutiveId() && // and the tokenId was minted in a batch
|
||||
!_sequentialBurn.get(tokenId) // and the token was never marked as burnt
|
||||
) {
|
||||
_sequentialBurn.set(tokenId);
|
||||
}
|
||||
|
||||
return previousOwner;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Used to offset the first token id in {_nextConsecutiveId}
|
||||
*/
|
||||
function _firstConsecutiveId() internal view virtual returns (uint96) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the next tokenId to mint using {_mintConsecutive}. It will return {_firstConsecutiveId}
|
||||
* if no consecutive tokenId has been minted before.
|
||||
*/
|
||||
function _nextConsecutiveId() private view returns (uint96) {
|
||||
(bool exists, uint96 latestId, ) = _sequentialOwnership.latestCheckpoint();
|
||||
return exists ? latestId + 1 : _firstConsecutiveId();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Enumerable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC721} from "../ERC721.sol";
|
||||
import {IERC721Enumerable} from "./IERC721Enumerable.sol";
|
||||
import {IERC165} from "../../../utils/introspection/ERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev This implements an optional extension of {ERC721} defined in the ERC that adds enumerability
|
||||
* of all the token ids in the contract as well as all token ids owned by each account.
|
||||
*
|
||||
* CAUTION: {ERC721} extensions that implement custom `balanceOf` logic, such as {ERC721Consecutive},
|
||||
* interfere with enumerability and should not be used together with {ERC721Enumerable}.
|
||||
*/
|
||||
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
|
||||
mapping(address owner => mapping(uint256 index => uint256)) private _ownedTokens;
|
||||
mapping(uint256 tokenId => uint256) private _ownedTokensIndex;
|
||||
|
||||
uint256[] private _allTokens;
|
||||
mapping(uint256 tokenId => uint256) private _allTokensIndex;
|
||||
|
||||
/**
|
||||
* @dev An `owner`'s token query was out of bounds for `index`.
|
||||
*
|
||||
* NOTE: The owner being `address(0)` indicates a global out of bounds index.
|
||||
*/
|
||||
error ERC721OutOfBoundsIndex(address owner, uint256 index);
|
||||
|
||||
/**
|
||||
* @dev Batch mint is not allowed.
|
||||
*/
|
||||
error ERC721EnumerableForbiddenBatchMint();
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
|
||||
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
|
||||
*/
|
||||
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {
|
||||
if (index >= balanceOf(owner)) {
|
||||
revert ERC721OutOfBoundsIndex(owner, index);
|
||||
}
|
||||
return _ownedTokens[owner][index];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Enumerable-totalSupply}.
|
||||
*/
|
||||
function totalSupply() public view virtual returns (uint256) {
|
||||
return _allTokens.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Enumerable-tokenByIndex}.
|
||||
*/
|
||||
function tokenByIndex(uint256 index) public view virtual returns (uint256) {
|
||||
if (index >= totalSupply()) {
|
||||
revert ERC721OutOfBoundsIndex(address(0), index);
|
||||
}
|
||||
return _allTokens[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {ERC721-_update}.
|
||||
*/
|
||||
function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {
|
||||
address previousOwner = super._update(to, tokenId, auth);
|
||||
|
||||
if (previousOwner == address(0)) {
|
||||
_addTokenToAllTokensEnumeration(tokenId);
|
||||
} else if (previousOwner != to) {
|
||||
_removeTokenFromOwnerEnumeration(previousOwner, tokenId);
|
||||
}
|
||||
if (to == address(0)) {
|
||||
_removeTokenFromAllTokensEnumeration(tokenId);
|
||||
} else if (previousOwner != to) {
|
||||
_addTokenToOwnerEnumeration(to, tokenId);
|
||||
}
|
||||
|
||||
return previousOwner;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 = balanceOf(to) - 1;
|
||||
_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 = balanceOf(from);
|
||||
uint256 tokenIndex = _ownedTokensIndex[tokenId];
|
||||
|
||||
mapping(uint256 index => uint256) storage _ownedTokensByOwner = _ownedTokens[from];
|
||||
|
||||
// When the token to delete is the last token, the swap operation is unnecessary
|
||||
if (tokenIndex != lastTokenIndex) {
|
||||
uint256 lastTokenId = _ownedTokensByOwner[lastTokenIndex];
|
||||
|
||||
_ownedTokensByOwner[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 _ownedTokensByOwner[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();
|
||||
}
|
||||
|
||||
/**
|
||||
* See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch
|
||||
*/
|
||||
function _increaseBalance(address account, uint128 amount) internal virtual override {
|
||||
if (amount > 0) {
|
||||
revert ERC721EnumerableForbiddenBatchMint();
|
||||
}
|
||||
super._increaseBalance(account, amount);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Pausable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC721} from "../ERC721.sol";
|
||||
import {Pausable} from "../../../utils/Pausable.sol";
|
||||
|
||||
/**
|
||||
* @dev ERC-721 token with pausable token transfers, minting and burning.
|
||||
*
|
||||
* Useful for scenarios such as preventing trades until the end of an evaluation
|
||||
* period, or having an emergency switch for freezing all token transfers in the
|
||||
* event of a large bug.
|
||||
*
|
||||
* IMPORTANT: This contract does not include public pause and unpause functions. In
|
||||
* addition to inheriting this contract, you must define both functions, invoking the
|
||||
* {Pausable-_pause} and {Pausable-_unpause} internal functions, with appropriate
|
||||
* access control, e.g. using {AccessControl} or {Ownable}. Not doing so will
|
||||
* make the contract pause mechanism of the contract unreachable, and thus unusable.
|
||||
*/
|
||||
abstract contract ERC721Pausable is ERC721, Pausable {
|
||||
/**
|
||||
* @dev See {ERC721-_update}.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - the contract must not be paused.
|
||||
*/
|
||||
function _update(
|
||||
address to,
|
||||
uint256 tokenId,
|
||||
address auth
|
||||
) internal virtual override whenNotPaused returns (address) {
|
||||
return super._update(to, tokenId, auth);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Royalty.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC721} from "../ERC721.sol";
|
||||
import {ERC2981} from "../../common/ERC2981.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of ERC-721 with the ERC-2981 NFT Royalty Standard, a standardized way to retrieve royalty payment
|
||||
* information.
|
||||
*
|
||||
* Royalty information can be specified globally for all token ids via {ERC2981-_setDefaultRoyalty}, and/or individually
|
||||
* for specific token ids via {ERC2981-_setTokenRoyalty}. The latter takes precedence over the first.
|
||||
*
|
||||
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
|
||||
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the ERC. Marketplaces are expected to
|
||||
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
|
||||
*/
|
||||
abstract contract ERC721Royalty is ERC2981, ERC721 {
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) {
|
||||
return super.supportsInterface(interfaceId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721URIStorage.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC721} from "../ERC721.sol";
|
||||
import {Strings} from "../../../utils/Strings.sol";
|
||||
import {IERC4906} from "../../../interfaces/IERC4906.sol";
|
||||
import {IERC165} from "../../../interfaces/IERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev ERC-721 token with storage based token URI management.
|
||||
*/
|
||||
abstract contract ERC721URIStorage is IERC4906, ERC721 {
|
||||
using Strings for uint256;
|
||||
|
||||
// Interface ID as defined in ERC-4906. This does not correspond to a traditional interface ID as ERC-4906 only
|
||||
// defines events and does not include any external function.
|
||||
bytes4 private constant ERC4906_INTERFACE_ID = bytes4(0x49064906);
|
||||
|
||||
// Optional mapping for token URIs
|
||||
mapping(uint256 tokenId => string) private _tokenURIs;
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) {
|
||||
return interfaceId == ERC4906_INTERFACE_ID || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {IERC721Metadata-tokenURI}.
|
||||
*/
|
||||
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
|
||||
_requireOwned(tokenId);
|
||||
|
||||
string memory _tokenURI = _tokenURIs[tokenId];
|
||||
string memory base = _baseURI();
|
||||
|
||||
// If there is no base URI, return the token URI.
|
||||
if (bytes(base).length == 0) {
|
||||
return _tokenURI;
|
||||
}
|
||||
// If both are set, concatenate the baseURI and tokenURI (via string.concat).
|
||||
if (bytes(_tokenURI).length > 0) {
|
||||
return string.concat(base, _tokenURI);
|
||||
}
|
||||
|
||||
return super.tokenURI(tokenId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
|
||||
*
|
||||
* Emits {MetadataUpdate}.
|
||||
*/
|
||||
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
|
||||
_tokenURIs[tokenId] = _tokenURI;
|
||||
emit MetadataUpdate(tokenId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Votes.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {ERC721} from "../ERC721.sol";
|
||||
import {Votes} from "../../../governance/utils/Votes.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of ERC-721 to support voting and delegation as implemented by {Votes}, where each individual NFT counts
|
||||
* as 1 vote unit.
|
||||
*
|
||||
* Tokens do not count as votes until they are delegated, because votes must be tracked which incurs an additional cost
|
||||
* on every transfer. Token holders can either delegate to a trusted representative who will decide how to make use of
|
||||
* the votes in governance decisions, or they can delegate to themselves to be their own representative.
|
||||
*/
|
||||
abstract contract ERC721Votes is ERC721, Votes {
|
||||
/**
|
||||
* @dev See {ERC721-_update}. Adjusts votes when tokens are transferred.
|
||||
*
|
||||
* Emits a {IVotes-DelegateVotesChanged} event.
|
||||
*/
|
||||
function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {
|
||||
address previousOwner = super._update(to, tokenId, auth);
|
||||
|
||||
_transferVotingUnits(previousOwner, to, 1);
|
||||
|
||||
return previousOwner;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the balance of `account`.
|
||||
*
|
||||
* WARNING: Overriding this function will likely result in incorrect vote tracking.
|
||||
*/
|
||||
function _getVotingUnits(address account) internal view virtual override returns (uint256) {
|
||||
return balanceOf(account);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch.
|
||||
*/
|
||||
function _increaseBalance(address account, uint128 amount) internal virtual override {
|
||||
super._increaseBalance(account, amount);
|
||||
_transferVotingUnits(address(0), account, amount);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Wrapper.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721, ERC721} from "../ERC721.sol";
|
||||
import {IERC721Receiver} from "../IERC721Receiver.sol";
|
||||
|
||||
/**
|
||||
* @dev Extension of the ERC-721 token contract to support token wrapping.
|
||||
*
|
||||
* Users can deposit and withdraw an "underlying token" and receive a "wrapped token" with a matching tokenId. This is
|
||||
* useful in conjunction with other modules. For example, combining this wrapping mechanism with {ERC721Votes} will allow
|
||||
* the wrapping of an existing "basic" ERC-721 into a governance token.
|
||||
*/
|
||||
abstract contract ERC721Wrapper is ERC721, IERC721Receiver {
|
||||
IERC721 private immutable _underlying;
|
||||
|
||||
/**
|
||||
* @dev The received ERC-721 token couldn't be wrapped.
|
||||
*/
|
||||
error ERC721UnsupportedToken(address token);
|
||||
|
||||
constructor(IERC721 underlyingToken) {
|
||||
_underlying = underlyingToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Allow a user to deposit underlying tokens and mint the corresponding tokenIds.
|
||||
*/
|
||||
function depositFor(address account, uint256[] memory tokenIds) public virtual returns (bool) {
|
||||
uint256 length = tokenIds.length;
|
||||
for (uint256 i = 0; i < length; ++i) {
|
||||
uint256 tokenId = tokenIds[i];
|
||||
|
||||
// This is an "unsafe" transfer that doesn't call any hook on the receiver. With underlying() being trusted
|
||||
// (by design of this contract) and no other contracts expected to be called from there, we are safe.
|
||||
// slither-disable-next-line reentrancy-no-eth
|
||||
underlying().transferFrom(_msgSender(), address(this), tokenId);
|
||||
_safeMint(account, tokenId);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Allow a user to burn wrapped tokens and withdraw the corresponding tokenIds of the underlying tokens.
|
||||
*/
|
||||
function withdrawTo(address account, uint256[] memory tokenIds) public virtual returns (bool) {
|
||||
uint256 length = tokenIds.length;
|
||||
for (uint256 i = 0; i < length; ++i) {
|
||||
uint256 tokenId = tokenIds[i];
|
||||
// Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
|
||||
// (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
|
||||
_update(address(0), tokenId, _msgSender());
|
||||
// Checks were already performed at this point, and there's no way to retake ownership or approval from
|
||||
// the wrapped tokenId after this point, so it's safe to remove the reentrancy check for the next line.
|
||||
// slither-disable-next-line reentrancy-no-eth
|
||||
underlying().safeTransferFrom(address(this), account, tokenId);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Overrides {IERC721Receiver-onERC721Received} to allow minting on direct ERC-721 transfers to
|
||||
* this contract.
|
||||
*
|
||||
* In case there's data attached, it validates that the operator is this contract, so only trusted data
|
||||
* is accepted from {depositFor}.
|
||||
*
|
||||
* WARNING: Doesn't work with unsafe transfers (eg. {IERC721-transferFrom}). Use {ERC721Wrapper-_recover}
|
||||
* for recovering in that scenario.
|
||||
*/
|
||||
function onERC721Received(address, address from, uint256 tokenId, bytes memory) public virtual returns (bytes4) {
|
||||
if (address(underlying()) != _msgSender()) {
|
||||
revert ERC721UnsupportedToken(_msgSender());
|
||||
}
|
||||
_safeMint(from, tokenId);
|
||||
return IERC721Receiver.onERC721Received.selector;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Mint a wrapped token to cover any underlyingToken that would have been transferred by mistake. Internal
|
||||
* function that can be exposed with access control if desired.
|
||||
*/
|
||||
function _recover(address account, uint256 tokenId) internal virtual returns (uint256) {
|
||||
address owner = underlying().ownerOf(tokenId);
|
||||
if (owner != address(this)) {
|
||||
revert ERC721IncorrectOwner(address(this), tokenId, owner);
|
||||
}
|
||||
_safeMint(account, tokenId);
|
||||
return tokenId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Returns the underlying token.
|
||||
*/
|
||||
function underlying() public view virtual returns (IERC721) {
|
||||
return _underlying;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721} from "../IERC721.sol";
|
||||
|
||||
/**
|
||||
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
|
||||
* @dev See https://eips.ethereum.org/EIPS/eip-721
|
||||
*/
|
||||
interface IERC721Enumerable is IERC721 {
|
||||
/**
|
||||
* @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);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721} from "../IERC721.sol";
|
||||
|
||||
/**
|
||||
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
|
||||
* @dev See https://eips.ethereum.org/EIPS/eip-721
|
||||
*/
|
||||
interface IERC721Metadata is IERC721 {
|
||||
/**
|
||||
* @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);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/utils/ERC721Holder.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721Receiver} from "../IERC721Receiver.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the {IERC721Receiver} interface.
|
||||
*
|
||||
* Accepts all token transfers.
|
||||
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
|
||||
* {IERC721-setApprovalForAll}.
|
||||
*/
|
||||
abstract contract ERC721Holder is IERC721Receiver {
|
||||
/**
|
||||
* @dev See {IERC721Receiver-onERC721Received}.
|
||||
*
|
||||
* Always returns `IERC721Receiver.onERC721Received.selector`.
|
||||
*/
|
||||
function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
|
||||
return this.onERC721Received.selector;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC721Receiver} from "../IERC721Receiver.sol";
|
||||
import {IERC721Errors} from "../../../interfaces/draft-IERC6093.sol";
|
||||
|
||||
/**
|
||||
* @dev Library that provide common ERC-721 utility functions.
|
||||
*
|
||||
* See https://eips.ethereum.org/EIPS/eip-721[ERC-721].
|
||||
*/
|
||||
library ERC721Utils {
|
||||
/**
|
||||
* @dev Performs an acceptance check for the provided `operator` by calling {IERC721-onERC721Received}
|
||||
* on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
|
||||
*
|
||||
* The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
|
||||
* Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept
|
||||
* the transfer.
|
||||
*/
|
||||
function checkOnERC721Received(
|
||||
address operator,
|
||||
address from,
|
||||
address to,
|
||||
uint256 tokenId,
|
||||
bytes memory data
|
||||
) internal {
|
||||
if (to.code.length > 0) {
|
||||
try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {
|
||||
if (retval != IERC721Receiver.onERC721Received.selector) {
|
||||
// Token rejected
|
||||
revert IERC721Errors.ERC721InvalidReceiver(to);
|
||||
}
|
||||
} catch (bytes memory reason) {
|
||||
if (reason.length == 0) {
|
||||
// non-IERC721Receiver implementer
|
||||
revert IERC721Errors.ERC721InvalidReceiver(to);
|
||||
} else {
|
||||
/// @solidity memory-safe-assembly
|
||||
assembly {
|
||||
revert(add(32, reason), mload(reason))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
140
lib_openzeppelin_contracts/contracts/token/common/ERC2981.sol
Normal file
140
lib_openzeppelin_contracts/contracts/token/common/ERC2981.sol
Normal file
@@ -0,0 +1,140 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// OpenZeppelin Contracts (last updated v5.0.0) (token/common/ERC2981.sol)
|
||||
|
||||
pragma solidity ^0.8.20;
|
||||
|
||||
import {IERC2981} from "../../interfaces/IERC2981.sol";
|
||||
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
|
||||
|
||||
/**
|
||||
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
|
||||
*
|
||||
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
|
||||
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
|
||||
*
|
||||
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
|
||||
* fee is specified in basis points by default.
|
||||
*
|
||||
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
|
||||
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the ERC. Marketplaces are expected to
|
||||
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
|
||||
*/
|
||||
abstract contract ERC2981 is IERC2981, ERC165 {
|
||||
struct RoyaltyInfo {
|
||||
address receiver;
|
||||
uint96 royaltyFraction;
|
||||
}
|
||||
|
||||
RoyaltyInfo private _defaultRoyaltyInfo;
|
||||
mapping(uint256 tokenId => RoyaltyInfo) private _tokenRoyaltyInfo;
|
||||
|
||||
/**
|
||||
* @dev The default royalty set is invalid (eg. (numerator / denominator) >= 1).
|
||||
*/
|
||||
error ERC2981InvalidDefaultRoyalty(uint256 numerator, uint256 denominator);
|
||||
|
||||
/**
|
||||
* @dev The default royalty receiver is invalid.
|
||||
*/
|
||||
error ERC2981InvalidDefaultRoyaltyReceiver(address receiver);
|
||||
|
||||
/**
|
||||
* @dev The royalty set for an specific `tokenId` is invalid (eg. (numerator / denominator) >= 1).
|
||||
*/
|
||||
error ERC2981InvalidTokenRoyalty(uint256 tokenId, uint256 numerator, uint256 denominator);
|
||||
|
||||
/**
|
||||
* @dev The royalty receiver for `tokenId` is invalid.
|
||||
*/
|
||||
error ERC2981InvalidTokenRoyaltyReceiver(uint256 tokenId, address receiver);
|
||||
|
||||
/**
|
||||
* @dev See {IERC165-supportsInterface}.
|
||||
*/
|
||||
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
|
||||
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritdoc IERC2981
|
||||
*/
|
||||
function royaltyInfo(uint256 tokenId, uint256 salePrice) public view virtual returns (address, uint256) {
|
||||
RoyaltyInfo storage _royaltyInfo = _tokenRoyaltyInfo[tokenId];
|
||||
address royaltyReceiver = _royaltyInfo.receiver;
|
||||
uint96 royaltyFraction = _royaltyInfo.royaltyFraction;
|
||||
|
||||
if (royaltyReceiver == address(0)) {
|
||||
royaltyReceiver = _defaultRoyaltyInfo.receiver;
|
||||
royaltyFraction = _defaultRoyaltyInfo.royaltyFraction;
|
||||
}
|
||||
|
||||
uint256 royaltyAmount = (salePrice * royaltyFraction) / _feeDenominator();
|
||||
|
||||
return (royaltyReceiver, royaltyAmount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
|
||||
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
|
||||
* override.
|
||||
*/
|
||||
function _feeDenominator() internal pure virtual returns (uint96) {
|
||||
return 10000;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets the royalty information that all ids in this contract will default to.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `receiver` cannot be the zero address.
|
||||
* - `feeNumerator` cannot be greater than the fee denominator.
|
||||
*/
|
||||
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
|
||||
uint256 denominator = _feeDenominator();
|
||||
if (feeNumerator > denominator) {
|
||||
// Royalty fee will exceed the sale price
|
||||
revert ERC2981InvalidDefaultRoyalty(feeNumerator, denominator);
|
||||
}
|
||||
if (receiver == address(0)) {
|
||||
revert ERC2981InvalidDefaultRoyaltyReceiver(address(0));
|
||||
}
|
||||
|
||||
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Removes default royalty information.
|
||||
*/
|
||||
function _deleteDefaultRoyalty() internal virtual {
|
||||
delete _defaultRoyaltyInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Sets the royalty information for a specific token id, overriding the global default.
|
||||
*
|
||||
* Requirements:
|
||||
*
|
||||
* - `receiver` cannot be the zero address.
|
||||
* - `feeNumerator` cannot be greater than the fee denominator.
|
||||
*/
|
||||
function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) internal virtual {
|
||||
uint256 denominator = _feeDenominator();
|
||||
if (feeNumerator > denominator) {
|
||||
// Royalty fee will exceed the sale price
|
||||
revert ERC2981InvalidTokenRoyalty(tokenId, feeNumerator, denominator);
|
||||
}
|
||||
if (receiver == address(0)) {
|
||||
revert ERC2981InvalidTokenRoyaltyReceiver(tokenId, address(0));
|
||||
}
|
||||
|
||||
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
|
||||
}
|
||||
|
||||
/**
|
||||
* @dev Resets royalty information for the token id back to the global default.
|
||||
*/
|
||||
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
|
||||
delete _tokenRoyaltyInfo[tokenId];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
= Common (Tokens)
|
||||
|
||||
Functionality that is common to multiple token standards.
|
||||
|
||||
* {ERC2981}: NFT Royalties compatible with both ERC-721 and ERC-1155.
|
||||
** For ERC-721 consider {ERC721Royalty} which clears the royalty information from storage on burn.
|
||||
|
||||
== Contracts
|
||||
|
||||
{{ERC2981}}
|
||||
Reference in New Issue
Block a user