Contract Source Code:
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import {MANAGER_ROLE, MINTER_ROLE, GAME_LOGIC_CONTRACT_ROLE, DEPLOYER_ROLE} from "../constants/RoleConstants.sol";
import {IS_SOULBOUND_CID, NAME_CID, PLAYER_CID, ID_CID, BALANCE_CID, CONTRACT_URI_CID, BASE_URI_CID, BASE_NAME_CID, MAX_SUPPLY_CID, BURN_COUNT_CID, MINT_COUNT_CID, OWNER_CID} from "../constants/ColumnConstants.sol";
import {IGameItems, ID} from "./IGameItems.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import {GameRegistryConsumer} from "../core/GameRegistryConsumer.sol";
import {IERC1155UpdateHandler} from "./IERC1155UpdateHandler.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {DataTable} from "../db/DataTable.sol";
import {ERC1155C} from "@creator-token-standards/erc1155c/ERC1155C.sol";
import {OwnableBasic} from "@creator-token-standards/access/OwnableBasic.sol";
import {BasicRoyalties} from "@creator-token-standards/programmable-royalties/BasicRoyalties.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ERC2981} from "@openzeppelin/contracts/token/common/ERC2981.sol";
import {ERC1155} from "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {ERC1155OpenZeppelin} from "@creator-token-standards/token/erc1155/ERC1155OpenZeppelin.sol";
import {IERC1155Receiver} from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/** @title ERC1155 contract for Game Items */
contract GameItems is
DataTable,
IGameItems,
ERC1155C,
OwnableBasic,
BasicRoyalties
{
/** TYPES **/
struct TypeInfo {
uint256 mints;
uint256 burns;
uint256 maxSupply;
}
using Address for address;
/** MEMBERS **/
/// @notice Handler for before update events
address public updateHandler;
string public uri_suffix;
/** EVENTS **/
/// @notice Emitted when contractURI has changed
event ContractURIUpdated(string uri);
/** ERRORS **/
/// @notice maxSupply needs to be higher than minted
error MaxSupplyTooLow(uint256 needed, uint256 actual);
/// @notice Token type has not been defined
error NonExistentTokenId(uint256);
/// @notice Amount to mint exceeds max supply
error NotEnoughSupply(uint256 needed, uint256 actual);
/**
* Initializer function for upgradeable contract
*/
constructor(address gameRegistryAddress, address royaltiesAddress, uint96 feeNumerator) DataTable(gameRegistryAddress, ID) ERC1155OpenZeppelin("") BasicRoyalties(royaltiesAddress, feeNumerator) {}
function initialize() external override onlyRole(DEPLOYER_ROLE) {
initializeTable("Gigaverse - Items", ID);
}
////////////////////
// Public Writes //
//////////////////
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public override(ERC1155, IERC1155) whenNotPaused {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public override(ERC1155, IERC1155) whenNotPaused {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not token owner or approved"
);
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non-ERC1155Receiver implementer");
}
}
}
////////////////////
// Public Reads ///
//////////////////
function balanceOf(address account, uint256 id) public view override(IERC1155, ERC1155) returns (uint256) {
return getDocUint256Value(getAccountTokenKey(account, id), BALANCE_CID);
}
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
) public view virtual override(IERC1155, ERC1155) returns (uint256[] memory) {
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
function owner() public view override(DataTable, Ownable) returns (address) {
return getTableAddressValue(OWNER_CID);
}
function contractURI() public view returns (string memory) {
return getTableStringValue(CONTRACT_URI_CID);
}
function getType(uint256 id) public view returns (TypeInfo memory) {
uint256 maxSupply = getDocUint256Value(id, MAX_SUPPLY_CID);
uint256 mints = getDocUint256Value(id, MINT_COUNT_CID);
uint256 burns = getDocUint256Value(id, BURN_COUNT_CID);
return TypeInfo(mints, burns, maxSupply);
}
function uri(uint256 id) public view override returns (string memory) {
string memory baseUri = getTableStringValue(BASE_URI_CID);
return string(abi.encodePacked(baseUri, Strings.toString(id), uri_suffix));
}
function tokenURI(uint256 _tokenId) public view returns (string memory) {
return uri(_tokenId);
}
function minted(
uint256 id
) external view virtual override(IGameItems) returns (uint256) {
return getDocUint256Value(id, MINT_COUNT_CID);
}
function tokenName(
uint256 tokenId
) public view virtual returns (string memory) {
if (hasDocStringValue(tokenId, NAME_CID)) {
return getDocStringValue(tokenId, NAME_CID);
} else {
return string(abi.encodePacked(getTableStringValue(BASE_NAME_CID), tokenId));
}
}
function getAccountTokenKey(address account, uint256 id) public pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(account, id)));
}
//////////////
// Manager //
////////////
function setContractURI(string calldata _uri) public onlyRole(MANAGER_ROLE) {
_setTableStringValue(CONTRACT_URI_CID, _uri);
emit ContractURIUpdated(_uri);
}
function setUri(string memory newUri) external onlyRole(MANAGER_ROLE) {
_setTableStringValue(BASE_URI_CID, newUri);
}
function setUriSuffix(string memory newUriSuffix) external onlyRole(MANAGER_ROLE) {
uri_suffix = newUriSuffix;
}
function setBaseTokenName(string memory baseTokenName) external onlyRole(MANAGER_ROLE) {
_setTableStringValue(BASE_NAME_CID, baseTokenName);
}
function setType(
uint256 id,
uint256 maxSupply
) public onlyRole(MANAGER_ROLE) {
TypeInfo memory typeData = getType(id);
if (typeData.mints > maxSupply) {
revert MaxSupplyTooLow(typeData.mints, maxSupply);
}
_setDocUint256Value(id, MAX_SUPPLY_CID, maxSupply);
}
function setTokenName(uint256 id, string memory name) public onlyRole(MANAGER_ROLE) {
_setDocStringValue(id, NAME_CID, name);
}
function setSoulBound(uint256 id, bool soulBound) public onlyRole(MANAGER_ROLE) {
_setDocBoolValue(id, IS_SOULBOUND_CID, soulBound);
}
function setTypeAndName(
uint256 id,
uint256 maxSupply,
string memory name
) external onlyRole(MANAGER_ROLE) {
setType(id, maxSupply);
setTokenName(id, name);
}
function setUpdateHandler(
address handlerAddress
) external onlyRole(MANAGER_ROLE) {
updateHandler = handlerAddress;
}
/////////////////////
// Game Contracts //
///////////////////
function mint(
address to,
uint256 id,
uint256 amount
) external override onlyRole(MINTER_ROLE) whenNotPaused {
_safeMint(to, id, amount);
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory /*data*/
) external onlyRole(MINTER_ROLE) whenNotPaused {
_confirmMintBatch(to, ids, amounts);
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts
) external onlyRole(MINTER_ROLE) whenNotPaused {
_confirmMintBatch(to, ids, amounts);
}
function burn(
address from,
uint256 id,
uint256 amount
) external override onlyRole(GAME_LOGIC_CONTRACT_ROLE) whenNotPaused {
_burn(from, id, amount);
}
function burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) external onlyRole(GAME_LOGIC_CONTRACT_ROLE) whenNotPaused {
require(ids.length == amounts.length, "Ids and amounts must have the same length");
for (uint256 i = 0; i < ids.length; i++) {
_burn(from, ids[i], amounts[i]);
}
}
////////////////////////
// Internal Helpers ///
//////////////////////
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal override {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
uint256[] memory ids = new uint256[](1);
ids[0] = id;
uint256[] memory amounts = new uint256[](1);
amounts[0] = amount;
uint256 fromBalance = balanceOf(from, id);
require(fromBalance >= amount, string.concat("ERC1155: insufficient balance for before transfer ", Strings.toString(fromBalance), " ", Strings.toString(amount)));
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeTransferAcceptanceCheckCustom(operator, from, to, id, amount, data);
}
function _doSafeTransferAcceptanceCheckCustom(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _safeMint(address to, uint256 id, uint256 amount) internal {
uint256 maxSupply = getDocUint256Value(id, MAX_SUPPLY_CID);
uint256 needed = getDocUint256Value(id, MINT_COUNT_CID) + amount;
if (needed > maxSupply) {
revert NotEnoughSupply(needed, maxSupply);
}
_incrementAmount(id, MINT_COUNT_CID, amount);
_mint(to, id, amount, "");
}
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal override {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
uint256[] memory ids = new uint256[](1);
ids[0] = id;
uint256[] memory amounts = new uint256[](1);
amounts[0] = amount;
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
}
function _confirmMintBatch(address to, uint256[] memory ids, uint256[] memory amounts) internal {
require(ids.length == amounts.length, "Ids and amounts must have the same length");
for (uint256 i = 0; i < ids.length; i++) {
_safeMint(to, ids[i], amounts[i]);
}
}
function _burn(
address from,
uint256 id,
uint256 amount
) internal override {
require(balanceOf(from, id) >= amount, "Not enough balance");
_incrementAmount(id, BURN_COUNT_CID, amount);
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
uint256[] memory ids = new uint256[](1);
ids[0] = id;
uint256[] memory amounts = new uint256[](1);
amounts[0] = amount;
uint256 fromBalance = balanceOf(from, id);
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override(
ERC1155C
) {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (updateHandler != address(0)) {
IERC1155UpdateHandler handlerRef = IERC1155UpdateHandler(
updateHandler
);
handlerRef.update(
address(this),
from,
to,
ids,
amounts
);
}
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
if (getDocBoolValue(id, IS_SOULBOUND_CID) && from != address(0) && to != address(0)) {
revert("Soulbound token cannot be transferred");
}
uint256 amount = amounts[i];
if (from != address(0)) {
_decrementAmount(getAccountTokenKey(from, id), BALANCE_CID, amount);
}
if (to != address(0)) {
uint256 accountKey = getAccountTokenKey(to, id);
_incrementAmount(accountKey, BALANCE_CID, amount);
if (getDocAddressValue(accountKey, PLAYER_CID) == address(0)) {
_setDocAddressValue(accountKey, PLAYER_CID, to);
_setDocUint256Value(accountKey, ID_CID, id);
}
}
}
if (ids.length == 1) {
emit TransferSingle(operator, from, to, ids[0], amounts[0]);
} else {
emit TransferBatch(operator, from, to, ids, amounts);
}
}
function supportsInterface(
bytes4 interfaceId
)
public
view
virtual
override(
ERC1155C,
IERC165,
ERC2981
)
returns (bool)
{
return
super.supportsInterface(interfaceId) ||
interfaceId == type(IGameItems).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.9;
// Pauser Role - Can pause the game
bytes32 constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// Minter Role - Can mint items, NFTs, and ERC20 currency
bytes32 constant MINTER_ROLE = keccak256("MINTER_ROLE");
// Manager Role - Can manage the shop, loot tables, and other game data
bytes32 constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
// Depoloyer Role - Can Deploy new Systems
bytes32 constant DEPLOYER_ROLE = keccak256("DEPLOYER_ROLE");
// Game Logic Contract - Contract that executes game logic and accesses other systems
bytes32 constant GAME_LOGIC_CONTRACT_ROLE = keccak256("GAME_LOGIC_CONTRACT_ROLE");
// For functions callable from game server
bytes32 constant SERVER_JUDGE_ROLE = keccak256("SERVER_JUDGE_ROLE");
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.9;
uint256 constant NAME_CID = uint256(keccak256("name"));
uint256 constant DESCRIPTION_CID = uint256(keccak256("description"));
uint256 constant LEVEL_CID = uint256(keccak256("level"));
uint256 constant IS_NOOB_CID = uint256(keccak256("is_noob"));
uint256 constant NOOB_TOKEN_CID = uint256(keccak256("noob_tokend_id"));
uint256 constant GIGA_NAME_TOKENDID_CID = uint256(keccak256("giganame_tokend_id"));
uint256 constant IS_GIGA_NAME_CID = uint256(keccak256("is_giga_name"));
uint256 constant GAME_ITEM_ID_CID = uint256(keccak256("game_item_id"));
uint256 constant UINT256_CID = uint256(keccak256("int256"));
uint256 constant ETH_MINT_PRICE_CID = uint256(keccak256("eth_mint_price"));
uint256 constant NEXT_DOCID_CID = uint256(keccak256("next_token_id"));
uint256 constant ID_CID = uint256(keccak256("id"));
uint256 constant BASE_NAME_CID = uint256(keccak256("base_name"));
uint256 constant BASE_URI_CID = uint256(keccak256("base_uri"));
uint256 constant LAST_TRANSFER_TIME_CID = uint256(keccak256("last_transfer_time"));
uint256 constant OWNER_CID = uint256(keccak256("owner"));
uint256 constant INITIALIZED_CID = uint256(keccak256("initialized"));
uint256 constant MAX_SUPPLY_CID = uint256(keccak256("max_supply"));
uint256 constant ADDRESS_CID = uint256(keccak256("address"));
uint256 constant IS_SOULBOUND_CID = uint256(keccak256("soulbound"));
uint256 constant TIME_BETWEEN_CID = uint256(keccak256("time_between"));
uint256 constant TIMESTAMP_CID = uint256(keccak256("timestamp"));
uint256 constant IMG_URL_CID = uint256(keccak256("img_url"));
uint256 constant PLAYER_CID = uint256(keccak256("player"));
uint256 constant MINT_COUNT_CID = uint256(keccak256("mint_count"));
uint256 constant CONTRACT_URI_CID = uint256(keccak256("contract_uri"));
uint256 constant IS_RECYCLABLE_CID = uint256(keccak256("is_recyclable"));
uint256 constant BURN_COUNT_CID = uint256(keccak256("burn_count"));
uint256 constant BALANCE_CID = uint256(keccak256("balance"));
uint256 constant ICON_URL_CID = uint256(keccak256("icon_url"));
uint256 constant DUNGEON_ID_CID = uint256(keccak256("dungeon_id"));
uint256 constant ENERGY_CID = uint256(keccak256("energy"));
uint256 constant IS_CANCELLED_CID = uint256(keccak256("is_cancelled"));
uint256 constant SPRITE_SHEET_URL_CID = uint256(keccak256("sprite_sheet_url"));
uint256 constant IMPORT_AMOUNT_CID = uint256(keccak256("import_amount"));
uint256 constant EXPORT_AMOUNT_CID = uint256(keccak256("export_amount"));
uint256 constant EXPORT_LICENSE_CID = uint256(keccak256("export_license"));
uint256 constant UNLOCKED_CID = uint256(keccak256("unlocked"));
uint256 constant FACTION_CID = uint256(keccak256("faction"));
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.9;
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
uint256 constant ID = uint256(keccak256("game.gigaverse.gameitems"));
interface IGameItems is IERC1155 {
/**
* Mints a ERC1155 token
*
* @param to Recipient of the token
* @param id Id of token to mint
* @param amount Quantity of token to mint
*/
function mint(address to, uint256 id, uint256 amount) external;
/**
* Burn a token - any payment / game logic should be handled in the game contract.
*
* @param from Account to burn from
* @param id Id of the token to burn
* @param amount Quantity to burn
*/
function burn(address from, uint256 id, uint256 amount) external;
/**
* @param id Id of the type to get data for
*
* @return How many of the given token id have been minted
*/
function minted(uint256 id) external view returns (uint256);
function burnBatch(address from, uint256[] memory ids, uint256[] memory amounts) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.13;
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {PAUSER_ROLE, MANAGER_ROLE} from "../constants/RoleConstants.sol";
import {ISystem} from "./ISystem.sol";
import {IGameRegistry, IERC165} from "./IGameRegistry.sol";
import {IDataStore, ID as DATA_STORE_ID} from "../db/IDataStore.sol";
import {DEPLOYER_ROLE} from "../constants/RoleConstants.sol";
/** @title Contract that lets a child contract access the GameRegistry contract */
abstract contract GameRegistryConsumer is
ReentrancyGuard,
ISystem
{
/// @notice Whether or not the contract is paused
bool private _paused;
/// @notice Reference to the game registry that this contract belongs to
IGameRegistry internal _gameRegistry;
/// @notice Id for the system/component
uint256 private _id;
/** EVENTS **/
/// @dev Emitted when the pause is triggered by `account`.
event Paused(address account);
/// @dev Emitted when the pause is lifted by `account`.
event Unpaused(address account);
/** ERRORS **/
/// @notice Not authorized to perform action
error MissingRole(address account, bytes32 expectedRole);
/** MODIFIERS **/
/// @notice Modifier to verify a user has the appropriate role to call a given function
modifier onlyRole(bytes32 role) {
_checkRole(role, msg.sender);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/** ERRORS **/
/// @notice Error if the game registry specified is invalid
error InvalidGameRegistry();
/** SETUP **/
/** @return ID for this system */
function getId() public view override returns (uint256) {
return _id;
}
/**
* Pause/Unpause the contract
*
* @param shouldPause Whether or pause or unpause
*/
function setPaused(bool shouldPause) external onlyRole(PAUSER_ROLE) {
if (shouldPause) {
_pause();
} else {
_unpause();
}
}
/**
* @dev Returns true if the contract OR the GameRegistry is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused || _gameRegistry.paused();
}
/**
* Sets the GameRegistry contract address for this contract
*
* @param gameRegistryAddress Address for the GameRegistry contract
*/
function setGameRegistry(
address gameRegistryAddress
) external onlyRole(MANAGER_ROLE) {
_gameRegistry = IGameRegistry(gameRegistryAddress);
if (gameRegistryAddress == address(0)) {
revert InvalidGameRegistry();
}
}
/** @return GameRegistry contract for this contract */
function getGameRegistry() external view returns (IGameRegistry) {
return _gameRegistry;
}
/** INTERNAL **/
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function _hasAccessRole(
bytes32 role,
address account
) internal view returns (bool) {
return _gameRegistry.hasAccessRole(role, account);
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!_gameRegistry.hasAccessRole(role, account)) {
revert MissingRole(account, role);
}
}
/** @return Returns the dataStore for this contract */
function _dataStore() internal view returns (IDataStore) {
return IDataStore(_getSystem(DATA_STORE_ID));
}
/** @return Address for a given system */
function _getSystem(uint256 systemId) internal view returns (address) {
return _gameRegistry.getSystem(systemId);
}
/** PAUSABLE **/
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual {
require(_paused == false, "Pausable: not paused");
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual {
require(_paused == true, "Pausable: not paused");
_paused = false;
emit Unpaused(msg.sender);
}
function initialize() external virtual onlyRole(DEPLOYER_ROLE) { }
/**
* Constructor for this contract
*
* @param gameRegistryAddress Address of the GameRegistry contract
* @param id Id of the system/component
*/
constructor(
address gameRegistryAddress,
uint256 id
) {
_gameRegistry = IGameRegistry(gameRegistryAddress);
if (gameRegistryAddress == address(0)) {
revert InvalidGameRegistry();
}
_paused = true;
_id = id;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.9;
interface IERC1155UpdateHandler {
/** @dev Emitted when a transfer is updated
* Update hook for GameItems. Performs any trait checks needed before transfer
*
* @param tokenContract Token contract address
* @param from From address
* @param to To address
* @param ids Ids to transfer
* @param values Values to transfer
*/
function update(
address tokenContract,
address from,
address to,
uint256[] memory ids,
uint256[] memory values
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.9;
import {DataStore, ID as DATA_STORE_ID} from "./DataStore.sol";
import {DEPLOYER_ROLE} from "../constants/RoleConstants.sol";
import {NAME_CID, ADDRESS_CID, ID_CID, NEXT_DOCID_CID, OWNER_CID} from "../constants/ColumnConstants.sol";
import {GameRegistryConsumer} from "../core/GameRegistryConsumer.sol";
contract DataTable is GameRegistryConsumer {
error AlreadyInitialized();
bool private _initialized;
constructor(address gameRegistryAddress, uint256 ID) GameRegistryConsumer(gameRegistryAddress, ID) {}
function owner() public view virtual returns (address) {
return getTableAddressValue(OWNER_CID);
}
function name() public view virtual returns (string memory) {
return getTableStringValue(NAME_CID);
}
function initializeTable(string memory nameToSet, uint256 id) internal {
if (_initialized) {
revert AlreadyInitialized();
}
_setTableAddressValue(ADDRESS_CID, address(this));
_setTableAddressValue(OWNER_CID, msg.sender);
_setTableStringValue(NAME_CID, nameToSet);
_setTableUint256Value(ID_CID, id);
_initialized = true;
}
function getTableId() public virtual view returns (uint256) {
return getId();
}
function _getAndIncrementAutoIncId() internal returns (uint256) {
uint256 currentId = getTableUint256Value(NEXT_DOCID_CID);
_setTableUint256Value(NEXT_DOCID_CID, currentId + 1);
return currentId + 1;
}
function _incrementAmount(uint256 docId, uint256 columnId, uint256 amount) internal {
uint256 currentAmount = getDocUint256Value(docId, columnId);
_setDocUint256Value(docId, columnId, currentAmount + amount);
}
function _decrementAmount(uint256 docId, uint256 columnId, uint256 amount) internal {
uint256 currentAmount = getDocUint256Value(docId, columnId);
_setDocUint256Value(docId, columnId, currentAmount - amount);
}
function _setTableStringValue(uint256 columnId, string memory value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setString(getTableId(), 0, columnId, value);
}
function _setTableUint256Value(uint256 columnId, uint256 value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setUint256(getTableId(), 0, columnId, value);
}
function _setTableAddressValue(uint256 columnId, address value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setAddress(getTableId(), 0, columnId, value);
}
function _setTableBoolValue(uint256 columnId, bool value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setBool(getTableId(), 0, columnId, value);
}
function _setTableAdddressValue(uint256 columnId, address value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setAddress(getTableId(), 0, columnId, value);
}
function _setTableUint256ArrayValue(uint256 columnId, uint256[] memory value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setUint256ArrayValue(getTableId(), 0, columnId, value);
}
function _setTableBoolArrayValue(uint256 columnId, bool[] memory value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setBoolArrayValue(getTableId(), 0, columnId, value);
}
function _setTableAddressArrayValue(uint256 columnId, address[] memory value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setAddressArrayValue(getTableId(), 0, columnId, value);
}
function _setDocAddressArrayValue(uint256 docId, uint256 columnId, address[] memory value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setAddressArrayValue(getTableId(), docId, columnId, value);
}
function _setDocBoolArrayValue(uint256 docId, uint256 columnId, bool[] memory value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setBoolArrayValue(getTableId(), docId, columnId, value);
}
function _setDocStringValue(uint256 docId, uint256 columnId, string memory value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setString(getTableId(), docId, columnId, value);
}
function _setDocUint256Value(uint256 docId, uint256 columnId, uint256 value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setUint256(getTableId(), docId, columnId, value);
}
function _setDocUint256ArrayValue(uint256 docId, uint256 columnId, uint256[] memory value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setUint256ArrayValue(getTableId(), docId, columnId, value);
}
function _setDocBoolValue(uint256 docId, uint256 columnId, bool value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setBool(getTableId(), docId, columnId, value);
}
function _setDocAddressValue(uint256 docId, uint256 columnId, address value) internal {
DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).setAddress(getTableId(), docId, columnId, value);
}
function getTableBoolValue(uint256 columnId) public view returns (bool) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).getBool(getTableId(), 0, columnId);
}
function getTableUint256Value(uint256 columnId) public view returns (uint256) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).getUint256(getTableId(), 0, columnId);
}
function getTableStringValue(uint256 columnId) public view returns (string memory) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).getString(getTableId(), 0, columnId);
}
function getTableAddressValue(uint256 columnId) public view returns (address) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).getAddress(getTableId(), 0, columnId);
}
function getTableUint256ArrayValue(uint256 columnId) public view returns (uint256[] memory) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).getUint256Array(getTableId(), 0, columnId);
}
function getDocUint256ArrayValue(uint256 docId, uint256 columnId) public view returns (uint256[] memory) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).getUint256Array(getTableId(), docId, columnId);
}
function getDocStringValue(uint256 docId, uint256 columnId) public view returns (string memory) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).getString(getTableId(), docId, columnId);
}
function getDocUint256Value(uint256 docId, uint256 columnId) public view returns (uint256) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).getUint256(getTableId(), docId, columnId);
}
function getDocBoolValue(uint256 docId, uint256 columnId) public view returns (bool) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).getBool(getTableId(), docId, columnId);
}
function getDocAddressValue(uint256 docId, uint256 columnId) public view returns (address) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).getAddress(getTableId(), docId, columnId);
}
function hasDocStringValue(uint256 docId, uint256 columnId) public view returns (bool) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).hasStringValue(getTableId(), docId, columnId);
}
function hasDocValue(uint256 docId, uint256 columnId) public view returns (bool) {
return DataStore(_gameRegistry.getSystem(DATA_STORE_ID)).hasValue(getTableId(), docId, columnId);
}
function getPlayerDocId(address player) public pure returns (uint256) {
return uint256(uint160(player));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../utils/AutomaticValidatorTransferApproval.sol";
import "../utils/CreatorTokenBase.sol";
import "../token/erc1155/ERC1155OpenZeppelin.sol";
import {TOKEN_TYPE_ERC1155} from "@limitbreak/permit-c/Constants.sol";
/**
* @title ERC1155C
* @author Limit Break, Inc.
* @notice Extends OpenZeppelin's ERC1155 implementation with Creator Token functionality, which
* allows the contract owner to update the transfer validation logic by managing a security policy in
* an external transfer validation security policy registry. See {CreatorTokenTransferValidator}.
*/
abstract contract ERC1155C is ERC1155OpenZeppelin, CreatorTokenBase, AutomaticValidatorTransferApproval {
/**
* @notice Overrides behavior of isApprovedFor all such that if an operator is not explicitly approved
* for all, the contract owner can optionally auto-approve the 721-C transfer validator for transfers.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool isApproved) {
isApproved = super.isApprovedForAll(owner, operator);
if (!isApproved) {
if (autoApproveTransfersFromValidator) {
isApproved = operator == address(getTransferValidator());
}
}
}
/**
* @notice Indicates whether the contract implements the specified interface.
* @dev Overrides supportsInterface in ERC165.
* @param interfaceId The interface id
* @return true if the contract implements the specified interface, false otherwise
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(ICreatorToken).interfaceId ||
interfaceId == type(ICreatorTokenLegacy).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @notice Returns the function selector for the transfer validator's validation function to be called
* @notice for transaction simulation.
*/
function getTransferValidationFunction() external pure returns (bytes4 functionSignature, bool isViewFunction) {
functionSignature = bytes4(keccak256("validateTransfer(address,address,address,uint256,uint256)"));
isViewFunction = false;
}
/// @dev Ties the open-zeppelin _beforeTokenTransfer hook to more granular transfer validation logic
function _beforeTokenTransfer(
address /*operator*/,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory /*data*/
) internal virtual override {
uint256 idsArrayLength = ids.length;
for (uint256 i = 0; i < idsArrayLength;) {
_validateBeforeTransfer(from, to, ids[i], amounts[i]);
unchecked {
++i;
}
}
}
/// @dev Ties the open-zeppelin _afterTokenTransfer hook to more granular transfer validation logic
function _afterTokenTransfer(
address /*operator*/,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory /*data*/
) internal virtual override {
uint256 idsArrayLength = ids.length;
for (uint256 i = 0; i < idsArrayLength;) {
_validateAfterTransfer(from, to, ids[i], amounts[i]);
unchecked {
++i;
}
}
}
function _tokenType() internal pure override returns(uint16) {
return uint16(TOKEN_TYPE_ERC1155);
}
}
/**
* @title ERC1155CInitializable
* @author Limit Break, Inc.
* @notice Initializable implementation of ERC1155C to allow for EIP-1167 proxy clones.
*/
abstract contract ERC1155CInitializable is ERC1155OpenZeppelinInitializable, CreatorTokenBase, AutomaticValidatorTransferApproval {
function initializeERC1155(string memory uri_) public override {
super.initializeERC1155(uri_);
_emitDefaultTransferValidator();
_registerTokenType(getTransferValidator());
}
/**
* @notice Overrides behavior of isApprovedFor all such that if an operator is not explicitly approved
* for all, the contract owner can optionally auto-approve the 721-C transfer validator for transfers.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool isApproved) {
isApproved = super.isApprovedForAll(owner, operator);
if (!isApproved) {
if (autoApproveTransfersFromValidator) {
isApproved = operator == address(getTransferValidator());
}
}
}
/**
* @notice Indicates whether the contract implements the specified interface.
* @dev Overrides supportsInterface in ERC165.
* @param interfaceId The interface id
* @return true if the contract implements the specified interface, false otherwise
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(ICreatorToken).interfaceId ||
interfaceId == type(ICreatorTokenLegacy).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @notice Returns the function selector for the transfer validator's validation function to be called
* @notice for transaction simulation.
*/
function getTransferValidationFunction() external pure returns (bytes4 functionSignature, bool isViewFunction) {
functionSignature = bytes4(keccak256("validateTransfer(address,address,address,uint256,uint256)"));
isViewFunction = false;
}
/// @dev Ties the open-zeppelin _beforeTokenTransfer hook to more granular transfer validation logic
function _beforeTokenTransfer(
address /*operator*/,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory /*data*/
) internal virtual override {
uint256 idsArrayLength = ids.length;
for (uint256 i = 0; i < idsArrayLength;) {
_validateBeforeTransfer(from, to, ids[i], amounts[i]);
unchecked {
++i;
}
}
}
/// @dev Ties the open-zeppelin _afterTokenTransfer hook to more granular transfer validation logic
function _afterTokenTransfer(
address /*operator*/,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory /*data*/
) internal virtual override {
uint256 idsArrayLength = ids.length;
for (uint256 i = 0; i < idsArrayLength;) {
_validateAfterTransfer(from, to, ids[i], amounts[i]);
unchecked {
++i;
}
}
}
function _tokenType() internal pure override returns(uint16) {
return uint16(TOKEN_TYPE_ERC1155);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./OwnablePermissions.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
abstract contract OwnableBasic is OwnablePermissions, Ownable {
function _requireCallerIsContractOwner() internal view virtual override {
_checkOwner();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/common/ERC2981.sol";
/**
* @title BasicRoyaltiesBase
* @author Limit Break, Inc.
* @dev Base functionality of an NFT mix-in contract implementing the most basic form of programmable royalties.
*/
abstract contract BasicRoyaltiesBase is ERC2981 {
event DefaultRoyaltySet(address indexed receiver, uint96 feeNumerator);
event TokenRoyaltySet(uint256 indexed tokenId, address indexed receiver, uint96 feeNumerator);
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual override {
super._setDefaultRoyalty(receiver, feeNumerator);
emit DefaultRoyaltySet(receiver, feeNumerator);
}
function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) internal virtual override {
super._setTokenRoyalty(tokenId, receiver, feeNumerator);
emit TokenRoyaltySet(tokenId, receiver, feeNumerator);
}
}
/**
* @title BasicRoyalties
* @author Limit Break, Inc.
* @notice Constructable BasicRoyalties Contract implementation.
*/
abstract contract BasicRoyalties is BasicRoyaltiesBase {
constructor(address receiver, uint96 feeNumerator) {
_setDefaultRoyalty(receiver, feeNumerator);
}
}
/**
* @title BasicRoyaltiesInitializable
* @author Limit Break, Inc.
* @notice Initializable BasicRoyalties Contract implementation to allow for EIP-1167 clones.
*/
abstract contract BasicRoyaltiesInitializable is BasicRoyaltiesBase {}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)
pragma solidity ^0.8.0;
import "../../interfaces/IERC2981.sol";
import "../../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 EIP. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*
* _Available since v4.5._
*/
abstract contract ERC2981 is IERC2981, ERC165 {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
/**
* @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 override returns (address, uint256) {
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, 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 {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: invalid receiver");
_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 {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: Invalid parameters");
_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];
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.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
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => 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 EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: address zero is not a valid owner");
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
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not token owner or approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not token owner or approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` 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 `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 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, 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.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, 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 EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts 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 `amount` tokens of token 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 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - 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 amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `ids` and `amounts` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non-ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non-ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token 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 amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
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 caller.
*/
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 `amount` tokens of token type `id` from `from` to `to`.
*
* 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 `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 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` 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 amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../../access/OwnablePermissions.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
abstract contract ERC1155OpenZeppelinBase is ERC1155 {
}
abstract contract ERC1155OpenZeppelin is ERC1155OpenZeppelinBase {
constructor(string memory uri_) ERC1155(uri_) {}
}
abstract contract ERC1155OpenZeppelinInitializable is OwnablePermissions, ERC1155OpenZeppelinBase {
error ERC1155OpenZeppelinInitializable__AlreadyInitializedERC1155();
bool private _erc1155Initialized;
function initializeERC1155(string memory uri_) public virtual {
_requireCallerIsContractOwner();
if(_erc1155Initialized) {
revert ERC1155OpenZeppelinInitializable__AlreadyInitializedERC1155();
}
_erc1155Initialized = true;
_setURI(uri_);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 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 ERC1155 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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* Defines a system the game engine
*/
interface ISystem {
/** @return The ID for the system. Ex: a uint256 casted keccak256 hash */
function getId() external view returns (uint256);
function initialize() external;
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
// @title Interface the game's ACL / Management Layer
interface IGameRegistry is IERC165 {
/**
* @dev Returns `true` if `account` has been granted `role`.
* @param role The role to query
* @param account The address to query
*/
function hasAccessRole(
bytes32 role,
address account
) external view returns (bool);
/**
* @return Whether or not the registry is paused
*/
function paused() external view returns (bool);
/**
* Registers a system by id
*
* @param systemId Id of the system
* @param systemAddress Address of the system contract
*/
function registerSystem(uint256 systemId, address systemAddress, bool isGameLogicContract) external;
/**
* @param systemId Id of the system
* @return System based on an id
*/
function getSystem(uint256 systemId) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
uint256 constant ID = uint256(keccak256("game.gigaverse.datastore"));
interface IDataStore {
enum ColumnType { NONE, UINT256, INT256, BOOL, ADDRESS, BYTES32, STRING, UINT256_ARRAY }
event ValueSet(uint256 indexed tableId, uint256 indexed docId, uint256 indexed colId, bytes32 value);
event StringValueSet(uint256 indexed tableId, uint256 indexed docId, uint256 indexed colId, string value);
event ArrayValueSet(uint256 indexed tableId, uint256 indexed docId, uint256 indexed colId, bytes32[] value);
event ColumnTypeSet(uint256 indexed colId, ColumnType columnType);
function setValue(uint256 tableId, uint256 docId, uint256 colId, bytes32 value) external;
function getValue(uint256 tableId, uint256 docId, uint256 colId) external view returns (bytes32);
function setColumnType(uint256 colId, ColumnType columnType) external;
function getColumnType(uint256 colId) external view returns (ColumnType);
// Type-specific setters
function setUint256(uint256 tableId, uint256 docId, uint256 colId, uint256 value) external;
function setInt256(uint256 tableId, uint256 docId, uint256 colId, int256 value) external;
function setBool(uint256 tableId, uint256 docId, uint256 colId, bool value) external;
function setAddress(uint256 tableId, uint256 docId, uint256 colId, address value) external;
function setBytes32(uint256 tableId, uint256 docId, uint256 colId, bytes32 value) external;
function setString(uint256 tableId, uint256 docId, uint256 colId, string memory value) external;
// Type-specific getters
function getUint256(uint256 tableId, uint256 docId, uint256 colId) external view returns (uint256);
function getInt256(uint256 tableId, uint256 docId, uint256 colId) external view returns (int256);
function getBool(uint256 tableId, uint256 docId, uint256 colId) external view returns (bool);
function getAddress(uint256 tableId, uint256 docId, uint256 colId) external view returns (address);
function getBytes32(uint256 tableId, uint256 docId, uint256 colId) external view returns (bytes32);
function getString(uint256 tableId, uint256 docId, uint256 colId) external view returns (string memory);
function deleteValue(uint256 tableId, uint256 docId, uint256 colId) external;
function hasValue(uint256 tableId, uint256 docId, uint256 colId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./DataTypes.sol";
import {IDataStore, ID} from "./IDataStore.sol";
import {GameRegistryConsumer} from "../core/GameRegistryConsumer.sol";
import {GAME_LOGIC_CONTRACT_ROLE} from "../constants/RoleConstants.sol";
contract DataStore is IDataStore, GameRegistryConsumer {
using DataTypes for *;
mapping(uint256 => mapping(uint256 => bytes32)) public datastore;
mapping(uint256 => mapping(uint256 => bytes32[])) public arrayStore;
mapping(uint256 => mapping(uint256 => string)) private stringStore;
mapping(uint256 => bytes32) public columnTypes;
constructor(address gameRegistryAddress) GameRegistryConsumer(gameRegistryAddress, ID) {}
function generateKey(uint256 docId, uint256 colId) public pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(docId, colId)));
}
function generateArrayKey (uint256 docId, uint256 colId) public pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(docId, colId, "__array")));
}
function setValue(uint256 tableId, uint256 docId, uint256 colId, bytes32 value) public onlyRole(GAME_LOGIC_CONTRACT_ROLE) {
datastore[tableId][uint256(keccak256(abi.encodePacked(docId, colId)))] = value;
emit ValueSet(tableId, docId, colId, value);
}
function setArrayValue(uint256 tableId, uint256 docId, uint256 colId, bytes32[] memory value) public onlyRole(GAME_LOGIC_CONTRACT_ROLE) {
arrayStore[tableId][generateArrayKey(docId, colId)] = value;
emit ArrayValueSet(tableId, docId, colId, value);
}
function setUint256ArrayValue(uint256 tableId, uint256 docId, uint256 colId, uint256[] memory value) public onlyRole(GAME_LOGIC_CONTRACT_ROLE) {
require (getColumnType(colId) == IDataStore.ColumnType.UINT256, "Column is not UINT256ARRAY");
bytes32[] memory packedValues = new bytes32[](value.length);
for (uint256 i = 0; i < value.length; i++) {
packedValues[i] = value[i].packUint256();
}
setArrayValue(tableId, docId, colId, packedValues);
}
function setBoolArrayValue(uint256 tableId, uint256 docId, uint256 colId, bool[] memory value) public onlyRole(GAME_LOGIC_CONTRACT_ROLE) {
require (getColumnType(colId) == IDataStore.ColumnType.BOOL, "Column is not BOOLARRAY");
bytes32[] memory packedValues = new bytes32[](value.length);
for (uint256 i = 0; i < value.length; i++) {
packedValues[i] = value[i].packBool();
}
setArrayValue(tableId, docId, colId, packedValues);
}
function setAddressArrayValue(uint256 tableId, uint256 docId, uint256 colId, address[] memory value) public onlyRole(GAME_LOGIC_CONTRACT_ROLE) {
require (getColumnType(colId) == IDataStore.ColumnType.ADDRESS, "Column is not ADDRESSARRAY");
bytes32[] memory packedValues = new bytes32[](value.length);
for (uint256 i = 0; i < value.length; i++) {
packedValues[i] = value[i].packAddress();
}
setArrayValue(tableId, docId, colId, packedValues);
}
function getUint256Array(uint256 tableId, uint256 docId, uint256 colId) public view returns (uint256[] memory) {
require (getColumnType(colId) == IDataStore.ColumnType.UINT256, "Column is not UINT256");
bytes32[] memory byteArray = arrayStore[tableId][generateArrayKey(docId, colId)];
uint256[] memory uintArray = new uint256[](byteArray.length);
for (uint256 i = 0; i < byteArray.length; i++) {
uintArray[i] = byteArray[i].unpackUint256();
}
return uintArray;
}
function getBoolArray(uint256 tableId, uint256 docId, uint256 colId) public view returns (bool[] memory) {
require (getColumnType(colId) == IDataStore.ColumnType.BOOL, "Column is not BOOL");
bytes32[] memory byteArray = arrayStore[tableId][generateArrayKey(docId, colId)];
bool[] memory boolArray = new bool[](byteArray.length);
for (uint256 i = 0; i < byteArray.length; i++) {
boolArray[i] = byteArray[i].unpackBool();
}
return boolArray;
}
function getAddressArray(uint256 tableId, uint256 docId, uint256 colId) public view returns (address[] memory) {
require (getColumnType(colId) == IDataStore.ColumnType.ADDRESS, "Column is not ADDRESS");
bytes32[] memory byteArray = arrayStore[tableId][generateArrayKey(docId, colId)];
address[] memory addressArray = new address[](byteArray.length);
for (uint256 i = 0; i < byteArray.length; i++) {
addressArray[i] = byteArray[i].unpackAddress();
}
return addressArray;
}
function getValue(uint256 tableId, uint256 docId, uint256 colId) public view returns (bytes32) {
return datastore[tableId][uint256(keccak256(abi.encodePacked(docId, colId)))];
}
function setColumnType(uint256 colId, IDataStore.ColumnType columnType) public onlyRole(GAME_LOGIC_CONTRACT_ROLE) {
require(!isColumnTypeSet(colId), "Column type already set");
columnTypes[colId] = bytes32(uint256(columnType));
emit ColumnTypeSet(colId, columnType);
}
function isColumnTypeSet(uint256 colId) public view returns (bool) {
return columnTypes[colId] != bytes32(0);
}
function getColumnType(uint256 colId) public view returns (IDataStore.ColumnType) {
bytes32 typeValue = columnTypes[colId];
require(typeValue != bytes32(0), "Column type not set");
return IDataStore.ColumnType(uint8(uint256(typeValue)));
}
// Type-specific setters
function setUint256(uint256 tableId, uint256 docId, uint256 colId, uint256 value) public onlyRole(GAME_LOGIC_CONTRACT_ROLE){
require(getColumnType(colId) == IDataStore.ColumnType.UINT256, "Column is not UINT256");
setValue(tableId, docId, colId, value.packUint256());
}
function setInt256(uint256 tableId, uint256 docId, uint256 colId, int256 value) public onlyRole(GAME_LOGIC_CONTRACT_ROLE){
require(getColumnType(colId) == IDataStore.ColumnType.INT256, "Column is not INT256");
setValue(tableId, docId, colId, value.packInt256());
}
function setBool(uint256 tableId, uint256 docId, uint256 colId, bool value) public onlyRole(GAME_LOGIC_CONTRACT_ROLE){
require(getColumnType(colId) == IDataStore.ColumnType.BOOL, "Column is not BOOL");
setValue(tableId, docId, colId, value.packBool());
}
function setAddress(uint256 tableId, uint256 docId, uint256 colId, address value) public onlyRole(GAME_LOGIC_CONTRACT_ROLE){
require(getColumnType(colId) == IDataStore.ColumnType.ADDRESS, "Column is not ADDRESS");
setValue(tableId, docId, colId, value.packAddress());
}
function setBytes32(uint256 tableId, uint256 docId, uint256 colId, bytes32 value) public onlyRole(GAME_LOGIC_CONTRACT_ROLE){
require(getColumnType(colId) == IDataStore.ColumnType.BYTES32, "Column is not BYTES32");
setValue(tableId, docId, colId, value);
}
function setString(uint256 tableId, uint256 docId, uint256 colId, string memory value) public onlyRole(GAME_LOGIC_CONTRACT_ROLE){
require(getColumnType(colId) == IDataStore.ColumnType.STRING, "Column is not STRING");
uint256 key = generateKey(docId, colId);
stringStore[tableId][key] = value;
emit StringValueSet(tableId, docId, colId, value);
}
function deleteValue(uint256 tableId, uint256 docId, uint256 colId) public onlyRole(GAME_LOGIC_CONTRACT_ROLE){
uint256 key = generateKey(docId, colId);
delete datastore[tableId][key];
}
// Type-specific getters
function getUint256(uint256 tableId, uint256 docId, uint256 colId) public view returns (uint256) {
require(getColumnType(colId) == IDataStore.ColumnType.UINT256, "Column is not UINT256");
return getValue(tableId, docId, colId).unpackUint256();
}
function getInt256(uint256 tableId, uint256 docId, uint256 colId) public view returns (int256) {
require(getColumnType(colId) == IDataStore.ColumnType.INT256, "Column is not INT256");
return getValue(tableId, docId, colId).unpackInt256();
}
function getBool(uint256 tableId, uint256 docId, uint256 colId) public view returns (bool) {
require(getColumnType(colId) == IDataStore.ColumnType.BOOL, "Column is not BOOL");
return getValue(tableId, docId, colId).unpackBool();
}
function getAddress(uint256 tableId, uint256 docId, uint256 colId) public view returns (address) {
require(getColumnType(colId) == IDataStore.ColumnType.ADDRESS, "Column is not ADDRESS");
return getValue(tableId, docId, colId).unpackAddress();
}
function getBytes32(uint256 tableId, uint256 docId, uint256 colId) public view returns (bytes32) {
require(getColumnType(colId) == IDataStore.ColumnType.BYTES32, "Column is not BYTES32");
return getValue(tableId, docId, colId);
}
function getString(uint256 tableId, uint256 docId, uint256 colId) public view returns (string memory) {
require(getColumnType(colId) == IDataStore.ColumnType.STRING, "Column is not STRING");
uint256 key = generateKey(docId, colId);
return stringStore[tableId][key];
}
function hasValue(uint256 tableId, uint256 docId, uint256 colId) public view returns (bool) {
uint256 key = generateKey(docId, colId);
return datastore[tableId][key] != bytes32(0);
}
function hasStringValue(uint256 tableId, uint256 docId, uint256 colId) public view returns (bool) {
uint256 key = generateKey(docId, colId);
return keccak256(bytes(stringStore[tableId][key])) != keccak256(bytes(""));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../access/OwnablePermissions.sol";
/**
* @title AutomaticValidatorTransferApproval
* @author Limit Break, Inc.
* @notice Base contract mix-in that provides boilerplate code giving the contract owner the
* option to automatically approve a 721-C transfer validator implementation for transfers.
*/
abstract contract AutomaticValidatorTransferApproval is OwnablePermissions {
/// @dev Emitted when the automatic approval flag is modified by the creator.
event AutomaticApprovalOfTransferValidatorSet(bool autoApproved);
/// @dev If true, the collection's transfer validator is automatically approved to transfer holder's tokens.
bool public autoApproveTransfersFromValidator;
/**
* @notice Sets if the transfer validator is automatically approved as an operator for all token owners.
*
* @dev Throws when the caller is not the contract owner.
*
* @param autoApprove If true, the collection's transfer validator will be automatically approved to
* transfer holder's tokens.
*/
function setAutomaticApprovalOfTransfersFromValidator(bool autoApprove) external {
_requireCallerIsContractOwner();
autoApproveTransfersFromValidator = autoApprove;
emit AutomaticApprovalOfTransferValidatorSet(autoApprove);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../access/OwnablePermissions.sol";
import "../interfaces/ICreatorToken.sol";
import "../interfaces/ICreatorTokenLegacy.sol";
import "../interfaces/ITransferValidator.sol";
import "./TransferValidation.sol";
import "../interfaces/ITransferValidatorSetTokenType.sol";
/**
* @title CreatorTokenBase
* @author Limit Break, Inc.
* @notice CreatorTokenBaseV3 is an abstract contract that provides basic functionality for managing token
* transfer policies through an implementation of ICreatorTokenTransferValidator/ICreatorTokenTransferValidatorV2/ICreatorTokenTransferValidatorV3.
* This contract is intended to be used as a base for creator-specific token contracts, enabling customizable transfer
* restrictions and security policies.
*
* <h4>Features:</h4>
* <ul>Ownable: This contract can have an owner who can set and update the transfer validator.</ul>
* <ul>TransferValidation: Implements the basic token transfer validation interface.</ul>
*
* <h4>Benefits:</h4>
* <ul>Provides a flexible and modular way to implement custom token transfer restrictions and security policies.</ul>
* <ul>Allows creators to enforce policies such as account and codehash blacklists, whitelists, and graylists.</ul>
* <ul>Can be easily integrated into other token contracts as a base contract.</ul>
*
* <h4>Intended Usage:</h4>
* <ul>Use as a base contract for creator token implementations that require advanced transfer restrictions and
* security policies.</ul>
* <ul>Set and update the ICreatorTokenTransferValidator implementation contract to enforce desired policies for the
* creator token.</ul>
*
* <h4>Compatibility:</h4>
* <ul>Backward and Forward Compatible - V1/V2/V3 Creator Token Base will work with V1/V2/V3 Transfer Validators.</ul>
*/
abstract contract CreatorTokenBase is OwnablePermissions, TransferValidation, ICreatorToken {
/// @dev Thrown when setting a transfer validator address that has no deployed code.
error CreatorTokenBase__InvalidTransferValidatorContract();
/// @dev The default transfer validator that will be used if no transfer validator has been set by the creator.
address public constant DEFAULT_TRANSFER_VALIDATOR = address(0x721C002B0059009a671D00aD1700c9748146cd1B);
/// @dev Used to determine if the default transfer validator is applied.
/// @dev Set to true when the creator sets a transfer validator address.
bool private isValidatorInitialized;
/// @dev Address of the transfer validator to apply to transactions.
address private transferValidator;
constructor() {
_emitDefaultTransferValidator();
_registerTokenType(DEFAULT_TRANSFER_VALIDATOR);
}
/**
* @notice Sets the transfer validator for the token contract.
*
* @dev Throws when provided validator contract is not the zero address and does not have code.
* @dev Throws when the caller is not the contract owner.
*
* @dev <h4>Postconditions:</h4>
* 1. The transferValidator address is updated.
* 2. The `TransferValidatorUpdated` event is emitted.
*
* @param transferValidator_ The address of the transfer validator contract.
*/
function setTransferValidator(address transferValidator_) public {
_requireCallerIsContractOwner();
bool isValidTransferValidator = transferValidator_.code.length > 0;
if(transferValidator_ != address(0) && !isValidTransferValidator) {
revert CreatorTokenBase__InvalidTransferValidatorContract();
}
emit TransferValidatorUpdated(address(getTransferValidator()), transferValidator_);
isValidatorInitialized = true;
transferValidator = transferValidator_;
_registerTokenType(transferValidator_);
}
/**
* @notice Returns the transfer validator contract address for this token contract.
*/
function getTransferValidator() public view override returns (address validator) {
validator = transferValidator;
if (validator == address(0)) {
if (!isValidatorInitialized) {
validator = DEFAULT_TRANSFER_VALIDATOR;
}
}
}
/**
* @dev Pre-validates a token transfer, reverting if the transfer is not allowed by this token's security policy.
* Inheriting contracts are responsible for overriding the _beforeTokenTransfer function, or its equivalent
* and calling _validateBeforeTransfer so that checks can be properly applied during token transfers.
*
* @dev Be aware that if the msg.sender is the transfer validator, the transfer is automatically permitted, as the
* transfer validator is expected to pre-validate the transfer.
*
* @dev Throws when the transfer doesn't comply with the collection's transfer policy, if the transferValidator is
* set to a non-zero address.
*
* @param caller The address of the caller.
* @param from The address of the sender.
* @param to The address of the receiver.
* @param tokenId The token id being transferred.
*/
function _preValidateTransfer(
address caller,
address from,
address to,
uint256 tokenId,
uint256 /*value*/) internal virtual override {
address validator = getTransferValidator();
if (validator != address(0)) {
if (msg.sender == validator) {
return;
}
ITransferValidator(validator).validateTransfer(caller, from, to, tokenId);
}
}
/**
* @dev Pre-validates a token transfer, reverting if the transfer is not allowed by this token's security policy.
* Inheriting contracts are responsible for overriding the _beforeTokenTransfer function, or its equivalent
* and calling _validateBeforeTransfer so that checks can be properly applied during token transfers.
*
* @dev Be aware that if the msg.sender is the transfer validator, the transfer is automatically permitted, as the
* transfer validator is expected to pre-validate the transfer.
*
* @dev Used for ERC20 and ERC1155 token transfers which have an amount value to validate in the transfer validator.
* @dev The `tokenId` for ERC20 tokens should be set to `0`.
*
* @dev Throws when the transfer doesn't comply with the collection's transfer policy, if the transferValidator is
* set to a non-zero address.
*
* @param caller The address of the caller.
* @param from The address of the sender.
* @param to The address of the receiver.
* @param tokenId The token id being transferred.
* @param amount The amount of token being transferred.
*/
function _preValidateTransfer(
address caller,
address from,
address to,
uint256 tokenId,
uint256 amount,
uint256 /*value*/) internal virtual override {
address validator = getTransferValidator();
if (validator != address(0)) {
if (msg.sender == validator) {
return;
}
ITransferValidator(validator).validateTransfer(caller, from, to, tokenId, amount);
}
}
function _tokenType() internal virtual pure returns(uint16);
function _registerTokenType(address validator) internal {
if (validator != address(0)) {
uint256 validatorCodeSize;
assembly {
validatorCodeSize := extcodesize(validator)
}
if(validatorCodeSize > 0) {
try ITransferValidatorSetTokenType(validator).setTokenTypeOfCollection(address(this), _tokenType()) {
} catch { }
}
}
}
/**
* @dev Used during contract deployment for constructable and cloneable creator tokens
* @dev to emit the `TransferValidatorUpdated` event signaling the validator for the contract
* @dev is the default transfer validator.
*/
function _emitDefaultTransferValidator() internal {
emit TransferValidatorUpdated(address(0), DEFAULT_TRANSFER_VALIDATOR);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @dev Constant bytes32 value of 0x000...000
bytes32 constant ZERO_BYTES32 = bytes32(0);
/// @dev Constant value of 0
uint256 constant ZERO = 0;
/// @dev Constant value of 1
uint256 constant ONE = 1;
/// @dev Constant value representing an open order in storage
uint8 constant ORDER_STATE_OPEN = 0;
/// @dev Constant value representing a filled order in storage
uint8 constant ORDER_STATE_FILLED = 1;
/// @dev Constant value representing a cancelled order in storage
uint8 constant ORDER_STATE_CANCELLED = 2;
/// @dev Constant value representing the ERC721 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC721 = 721;
/// @dev Constant value representing the ERC1155 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC1155 = 1155;
/// @dev Constant value representing the ERC20 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC20 = 20;
/// @dev Constant value to mask the upper bits of a signature that uses a packed `vs` value to extract `s`
bytes32 constant UPPER_BIT_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/// @dev EIP-712 typehash used for validating signature based stored approvals
bytes32 constant UPDATE_APPROVAL_TYPEHASH =
keccak256("UpdateApprovalBySignature(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 approvalExpiration,uint256 sigDeadline,uint256 masterNonce)");
/// @dev EIP-712 typehash used for validating a single use permit without additional data
bytes32 constant SINGLE_USE_PERMIT_TYPEHASH =
keccak256("PermitTransferFrom(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 expiration,uint256 masterNonce)");
/// @dev EIP-712 typehash used for validating a single use permit with additional data
string constant SINGLE_USE_PERMIT_TRANSFER_ADVANCED_TYPEHASH_STUB =
"PermitTransferFromWithAdditionalData(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 expiration,uint256 masterNonce,";
/// @dev EIP-712 typehash used for validating an order permit that updates storage as it fills
string constant PERMIT_ORDER_ADVANCED_TYPEHASH_STUB =
"PermitOrderWithAdditionalData(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 salt,address operator,uint256 expiration,uint256 masterNonce,";
/// @dev Pausable flag for stored approval transfers of ERC721 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC721 = 1 << 0;
/// @dev Pausable flag for stored approval transfers of ERC1155 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC1155 = 1 << 1;
/// @dev Pausable flag for stored approval transfers of ERC20 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC20 = 1 << 2;
/// @dev Pausable flag for single use permit transfers of ERC721 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC721 = 1 << 3;
/// @dev Pausable flag for single use permit transfers of ERC1155 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC1155 = 1 << 4;
/// @dev Pausable flag for single use permit transfers of ERC20 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC20 = 1 << 5;
/// @dev Pausable flag for order fill transfers of ERC1155 assets
uint256 constant PAUSABLE_ORDER_TRANSFER_FROM_ERC1155 = 1 << 6;
/// @dev Pausable flag for order fill transfers of ERC20 assets
uint256 constant PAUSABLE_ORDER_TRANSFER_FROM_ERC20 = 1 << 7;
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Context.sol";
abstract contract OwnablePermissions is Context {
function _requireCallerIsContractOwner() internal view virtual;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
library DataTypes {
// Pack and unpack uint256
function packUint256(uint256 value) internal pure returns (bytes32) {
return bytes32(value);
}
function unpackUint256(bytes32 packed) internal pure returns (uint256) {
return uint256(packed);
}
// Pack and unpack int256
function packInt256(int256 value) internal pure returns (bytes32) {
return bytes32(uint256(value));
}
function unpackInt256(bytes32 packed) internal pure returns (int256) {
return int256(uint256(packed));
}
// Pack and unpack address
function packAddress(address value) internal pure returns (bytes32) {
return bytes32(uint256(uint160(value)));
}
function unpackAddress(bytes32 packed) internal pure returns (address) {
return address(uint160(uint256(packed)));
}
// Pack and unpack bool
function packBool(bool value) internal pure returns (bytes32) {
return bytes32(uint256(value ? 1 : 0));
}
function unpackBool(bytes32 packed) internal pure returns (bool) {
return uint256(packed) == 1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ICreatorToken {
event TransferValidatorUpdated(address oldValidator, address newValidator);
function getTransferValidator() external view returns (address validator);
function setTransferValidator(address validator) external;
function getTransferValidationFunction() external view returns (bytes4 functionSignature, bool isViewFunction);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ICreatorTokenLegacy {
event TransferValidatorUpdated(address oldValidator, address newValidator);
function getTransferValidator() external view returns (address validator);
function setTransferValidator(address validator) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ITransferValidator {
function applyCollectionTransferPolicy(address caller, address from, address to) external view;
function validateTransfer(address caller, address from, address to) external view;
function validateTransfer(address caller, address from, address to, uint256 tokenId) external view;
function validateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount) external;
function beforeAuthorizedTransfer(address operator, address token, uint256 tokenId) external;
function afterAuthorizedTransfer(address token, uint256 tokenId) external;
function beforeAuthorizedTransfer(address operator, address token) external;
function afterAuthorizedTransfer(address token) external;
function beforeAuthorizedTransfer(address token, uint256 tokenId) external;
function beforeAuthorizedTransferWithAmount(address token, uint256 tokenId, uint256 amount) external;
function afterAuthorizedTransferWithAmount(address token, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @title TransferValidation
* @author Limit Break, Inc.
* @notice A mix-in that can be combined with ERC-721 contracts to provide more granular hooks.
* Openzeppelin's ERC721 contract only provides hooks for before and after transfer. This allows
* developers to validate or customize transfers within the context of a mint, a burn, or a transfer.
*/
abstract contract TransferValidation is Context {
/// @dev Thrown when the from and to address are both the zero address.
error ShouldNotMintToBurnAddress();
/*************************************************************************/
/* Transfers Without Amounts */
/*************************************************************************/
/// @dev Inheriting contracts should call this function in the _beforeTokenTransfer function to get more granular hooks.
function _validateBeforeTransfer(address from, address to, uint256 tokenId) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_preValidateMint(_msgSender(), to, tokenId, msg.value);
} else if(toZeroAddress) {
_preValidateBurn(_msgSender(), from, tokenId, msg.value);
} else {
_preValidateTransfer(_msgSender(), from, to, tokenId, msg.value);
}
}
/// @dev Inheriting contracts should call this function in the _afterTokenTransfer function to get more granular hooks.
function _validateAfterTransfer(address from, address to, uint256 tokenId) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_postValidateMint(_msgSender(), to, tokenId, msg.value);
} else if(toZeroAddress) {
_postValidateBurn(_msgSender(), from, tokenId, msg.value);
} else {
_postValidateTransfer(_msgSender(), from, to, tokenId, msg.value);
}
}
/// @dev Optional validation hook that fires before a mint
function _preValidateMint(address caller, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a mint
function _postValidateMint(address caller, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a burn
function _preValidateBurn(address caller, address from, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a burn
function _postValidateBurn(address caller, address from, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a transfer
function _preValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a transfer
function _postValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 value) internal virtual {}
/*************************************************************************/
/* Transfers With Amounts */
/*************************************************************************/
/// @dev Inheriting contracts should call this function in the _beforeTokenTransfer function to get more granular hooks.
function _validateBeforeTransfer(address from, address to, uint256 tokenId, uint256 amount) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_preValidateMint(_msgSender(), to, tokenId, amount, msg.value);
} else if(toZeroAddress) {
_preValidateBurn(_msgSender(), from, tokenId, amount, msg.value);
} else {
_preValidateTransfer(_msgSender(), from, to, tokenId, amount, msg.value);
}
}
/// @dev Inheriting contracts should call this function in the _afterTokenTransfer function to get more granular hooks.
function _validateAfterTransfer(address from, address to, uint256 tokenId, uint256 amount) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_postValidateMint(_msgSender(), to, tokenId, amount, msg.value);
} else if(toZeroAddress) {
_postValidateBurn(_msgSender(), from, tokenId, amount, msg.value);
} else {
_postValidateTransfer(_msgSender(), from, to, tokenId, amount, msg.value);
}
}
/// @dev Optional validation hook that fires before a mint
function _preValidateMint(address caller, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a mint
function _postValidateMint(address caller, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a burn
function _preValidateBurn(address caller, address from, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a burn
function _postValidateBurn(address caller, address from, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a transfer
function _preValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a transfer
function _postValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ITransferValidatorSetTokenType {
function setTokenTypeOfCollection(address collection, uint16 tokenType) external;
}