Transaction Hash:
Block:
22799793 at Jun-28-2025 01:57:11 AM +UTC
Transaction Fee:
0.000086068738213284 ETH
$0.21
Gas Used:
254,823 Gas / 0.337758908 Gwei
Emitted Events:
524 |
TransparentUpgradeableProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000001dd098e09f7ce3418a079b87788b1e52111503f1, 0x0000000000000000000000008842677c4df444f956b5b9a7934e762b13942106, 0x000000000000000000000000000000630000000000000000000000000000009c )
|
525 |
LANDProxy.0x9d9dd80a56a16f715df6eb40b771e24ff8cbea6eed9de28473ce0f28fe5602a9( 0x9d9dd80a56a16f715df6eb40b771e24ff8cbea6eed9de28473ce0f28fe5602a9, 0x000000000000000000000000000000630000000000000000000000000000009c, 0x0000000000000000000000008842677c4df444f956b5b9a7934e762b13942106 )
|
526 |
TransparentUpgradeableProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000001dd098e09f7ce3418a079b87788b1e52111503f1, 0x0000000000000000000000008842677c4df444f956b5b9a7934e762b13942106, 0x000000000000000000000000000000620000000000000000000000000000009e )
|
527 |
LANDProxy.0x9d9dd80a56a16f715df6eb40b771e24ff8cbea6eed9de28473ce0f28fe5602a9( 0x9d9dd80a56a16f715df6eb40b771e24ff8cbea6eed9de28473ce0f28fe5602a9, 0x000000000000000000000000000000620000000000000000000000000000009e, 0x0000000000000000000000008842677c4df444f956b5b9a7934e762b13942106 )
|
528 |
TransparentUpgradeableProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000001dd098e09f7ce3418a079b87788b1e52111503f1, 0x0000000000000000000000008842677c4df444f956b5b9a7934e762b13942106, 0x000000000000000000000000000000620000000000000000000000000000009d )
|
529 |
LANDProxy.0x9d9dd80a56a16f715df6eb40b771e24ff8cbea6eed9de28473ce0f28fe5602a9( 0x9d9dd80a56a16f715df6eb40b771e24ff8cbea6eed9de28473ce0f28fe5602a9, 0x000000000000000000000000000000620000000000000000000000000000009d, 0x0000000000000000000000008842677c4df444f956b5b9a7934e762b13942106 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x0eAD9737...2917Ca426 | |||||
0x1DD098e0...2111503f1 | |||||
0x79940B12...512FC98dE |
0.007255138439908921 Eth
Nonce: 324
|
0.007169069701695637 Eth
Nonce: 325
| 0.000086068738213284 | ||
0x95222290...5CC4BAfe5
Miner
| (beaverbuild) | 22.852385894751081546 Eth | 22.852385912588691546 Eth | 0.00000001783761 | |
0xF87E3149...1d56D5d4d |
Execution Trace
0x1dd098e09f7ce3418a079b87788b1e52111503f1.720ebbd9( )
TransparentUpgradeableProxy.42842e0e( )
AetherianLandOperatorRights.safeTransferFrom( from=0x1DD098e09F7Ce3418a079b87788b1e52111503f1, to=0x8842677c4df444f956B5B9a7934E762b13942106, tokenId=33687954325172907882874086135745052934300 )
AdminUpgradeabilityProxy.1d11016a( )
EstateRegistry.setLandUpdateOperator( estateId=2092, landId=33687954325172907882874086135745052934300, operator=0x8842677c4df444f956B5B9a7934E762b13942106 )
LANDProxy.b0b02c60( )
-
LANDRegistry.setUpdateOperator( assetId=33687954325172907882874086135745052934300, operator=0x8842677c4df444f956B5B9a7934E762b13942106 )
-
TransparentUpgradeableProxy.42842e0e( )
AetherianLandOperatorRights.safeTransferFrom( from=0x1DD098e09F7Ce3418a079b87788b1e52111503f1, to=0x8842677c4df444f956B5B9a7934E762b13942106, tokenId=33347671958251969419410711528313284722846 )
AdminUpgradeabilityProxy.1d11016a( )
EstateRegistry.setLandUpdateOperator( estateId=2092, landId=33347671958251969419410711528313284722846, operator=0x8842677c4df444f956B5B9a7934E762b13942106 )
LANDProxy.b0b02c60( )
-
LANDRegistry.setUpdateOperator( assetId=33347671958251969419410711528313284722846, operator=0x8842677c4df444f956B5B9a7934E762b13942106 )
-
TransparentUpgradeableProxy.42842e0e( )
AetherianLandOperatorRights.safeTransferFrom( from=0x1DD098e09F7Ce3418a079b87788b1e52111503f1, to=0x8842677c4df444f956B5B9a7934E762b13942106, tokenId=33347671958251969419410711528313284722845 )
AdminUpgradeabilityProxy.1d11016a( )
EstateRegistry.setLandUpdateOperator( estateId=2092, landId=33347671958251969419410711528313284722845, operator=0x8842677c4df444f956B5B9a7934E762b13942106 )
LANDProxy.b0b02c60( )
-
LANDRegistry.setUpdateOperator( assetId=33347671958251969419410711528313284722845, operator=0x8842677c4df444f956B5B9a7934E762b13942106 )
-
File 1 of 6: TransparentUpgradeableProxy
File 2 of 6: LANDProxy
File 3 of 6: AetherianLandOperatorRights
File 4 of 6: AdminUpgradeabilityProxy
File 5 of 6: EstateRegistry
File 6 of 6: LANDRegistry
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol"; // Kept for backwards compatibility with older versions of Hardhat and Truffle plugins. contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy { constructor(address logic, address admin, bytes memory data) payable TransparentUpgradeableProxy(logic, admin, data) {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967Proxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _getAdmin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeToAndCall(newImplementation, data, true); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./TransparentUpgradeableProxy.sol"; import "../../access/Ownable.sol"; /** * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. */ contract ProxyAdmin is Ownable { /** * @dev Returns the current implementation of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the current admin of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of `proxy` to `newAdmin`. * * Requirements: * * - This contract must be the current admin of `proxy`. */ function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See * {TransparentUpgradeableProxy-upgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( Address.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 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"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (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 functionCall(target, data, "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"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(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) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(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) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT 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 () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { 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 { emit OwnershipTransferred(_owner, address(0)); _owner = 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"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is ERC1967Upgrade { function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol"; abstract contract Proxiable is UUPSUpgradeable { function _authorizeUpgrade(address newImplementation) internal override { _beforeUpgrade(newImplementation); } function _beforeUpgrade(address newImplementation) internal virtual; } contract ChildOfProxiable is Proxiable { function _beforeUpgrade(address newImplementation) internal virtual override {} }
File 2 of 6: LANDProxy
pragma solidity ^0.4.18; // File: contracts/land/LANDStorage.sol contract LANDStorage { mapping (address => uint) latestPing; uint256 constant clearLow = 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000; uint256 constant clearHigh = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff; uint256 constant factor = 0x100000000000000000000000000000000; mapping (address => bool) authorizedDeploy; } // File: contracts/upgradable/OwnableStorage.sol contract OwnableStorage { address public owner; function OwnableStorage() internal { owner = msg.sender; } } // File: contracts/upgradable/ProxyStorage.sol contract ProxyStorage { /** * Current contract to which we are proxing */ address public currentContract; address public proxyOwner; } // File: erc821/contracts/AssetRegistryStorage.sol contract AssetRegistryStorage { string internal _name; string internal _symbol; string internal _description; /** * Stores the total count of assets managed by this registry */ uint256 internal _count; /** * Stores an array of assets owned by a given account */ mapping(address => uint256[]) internal _assetsOf; /** * Stores the current holder of an asset */ mapping(uint256 => address) internal _holderOf; /** * Stores the index of an asset in the `_assetsOf` array of its holder */ mapping(uint256 => uint256) internal _indexOfAsset; /** * Stores the data associated with an asset */ mapping(uint256 => string) internal _assetData; /** * For a given account, for a given opperator, store whether that operator is * allowed to transfer and modify assets on behalf of them. */ mapping(address => mapping(address => bool)) internal _operators; /** * Simple reentrancy lock */ bool internal _reentrancy; } // File: contracts/Storage.sol contract Storage is ProxyStorage, OwnableStorage, AssetRegistryStorage, LANDStorage { } // File: contracts/upgradable/DelegateProxy.sol contract DelegateProxy { /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); assembly { let result := delegatecall(sub(gas, 10000), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } function isContract(address _target) constant internal returns (bool) { uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: contracts/upgradable/IApplication.sol contract IApplication { function initialize(bytes data) public; } // File: contracts/upgradable/Ownable.sol contract Ownable is Storage { event OwnerUpdate(address _prevOwner, address _newOwner); function bytesToAddress (bytes b) pure public returns (address) { uint result = 0; for (uint i = b.length-1; i+1 > 0; i--) { uint c = uint(b[i]); uint to_inc = c * ( 16 ** ((b.length - i-1) * 2)); result += to_inc; } return address(result); } modifier onlyOwner { assert(msg.sender == owner); _; } function initialize(bytes data) public { owner = bytesToAddress(data); } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != owner); owner = _newOwner; } } // File: contracts/upgradable/Proxy.sol contract Proxy is Storage, DelegateProxy { event Upgrade(address indexed newContract, bytes initializedWith); event OwnerUpdate(address _prevOwner, address _newOwner); function Proxy() public { proxyOwner = msg.sender; } modifier onlyProxyOwner() { require(msg.sender == proxyOwner); _; } function transferOwnership(address _newOwner) public onlyProxyOwner { require(_newOwner != proxyOwner); OwnerUpdate(proxyOwner, _newOwner); proxyOwner = _newOwner; } function upgrade(IApplication newContract, bytes data) public onlyProxyOwner { currentContract = newContract; IApplication(this).initialize(data); Upgrade(newContract, data); } function () payable public { require(currentContract != 0); // if app code hasn't been set yet, don't call delegatedFwd(currentContract, msg.data); } } // File: contracts/upgradable/LANDProxy.sol contract LANDProxy is Storage, Proxy { }
File 3 of 6: AetherianLandOperatorRights
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { 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); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @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 ReentrancyGuardUpgradeable is Initializable { // 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; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _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() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [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 functionCall(target, data, "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"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(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) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason 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 { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @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] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // 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: AGPL pragma solidity >=0.8.7 <0.9.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./interfaces/ILANDRegistry.sol"; import "./interfaces/IEstateRegistry.sol"; import "./interfaces/IExclusiveManagerExpiryTable.sol"; import "./interfaces/IExclusiveUpdateManager.sol"; import "./scratch/MassERC721Upgradeable.sol"; // MassERC721 has reentrancy so we don't need to import it again contract AetherianLandOperatorRights is Initializable, MassERC721Upgradeable, OwnableUpgradeable { uint8 constant xfloor = 62; uint8 constant yfloor = 59; uint256 constant clearLow = 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000; uint256 constant clearHigh = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff; uint256 constant maskOutAddr = 0x0000000000000000000000000000000000000000fffff0000000000000000000; uint256 constant factor = 0x100000000000000000000000000000000; struct ExclusiveManager { uint64 expiry; // UNIX timetsamp corresponding to the expiry time address managerAddress; // address of the exclusive manager } ILANDRegistry private landContract; IEstateRegistry private estateContract; uint256 private estateId; IExclusiveManagerExpiryTable private expiryTable; // Standard update manager much like LANDs mapping(address => mapping(address => bool)) public updateManagers; // When an exclusive update manager is set for a parcel only the exclusive manager may call `setUpdateOperator` // Once the expiry is passed the ALOR owner and their standard update managers can once again control setUpdateOperator // Exclusive Update Managers lockout transfers while they are active // IMPORTANT: there is a risk of soft-locking your ALORs operator rights until the exclusiver manager expires // : To alleviate this we do not allow people to set an expiry more than one year into the future mapping(uint256 => ExclusiveManager) public exclusiveUpdateManagers; function initialize( uint256[713] calldata mapData, address landContractAddress, address estateContractAddress, address expiryTableContractAddress, uint256 _estateId ) public initializer { __MassERC721Upgradeable_init("Aetherian Land Operator Rights", "ALOR", 10005); __Ownable_init(); __ALOR_Map_init(/*holderData,*/ mapData/*, compactIndexTree*/); __ALOR_DCL_interop_init(landContractAddress,estateContractAddress,_estateId); __ALOR_Exclusive_Manager_init(expiryTableContractAddress); } function __ALOR_Map_init( uint256[713] calldata mapData ) internal onlyInitializing { // holderData first 160 bits of each entry is the new holders address // The next 16bits is the holding amount, index is holderId // mapData each uint256 is value to be put into the _owners map. for(uint16 yseg = 0; yseg < 7; yseg++) { for(uint16 xseg = 0; (xseg < 102) && (xseg < 101 || yseg < 6); xseg++) { uint16 ind = (yseg * 102) + xseg; uint256 mapSlotData = mapData[ind]; uint16 tokenBlockId = (xseg << 4) + yseg; assembly { mstore(0,tokenBlockId) mstore(32,_owners.slot) let hash := keccak256(0,64) sstore(hash, mapSlotData) } /* ** Why aren't we emitting Transfer events here? ** (1) They're expensive 10005 transfer events would use up WAYY to much gas ** (2) If you read the ERC721 standard we can mint as many tokens as we want, ** without a mint event at contract creation */ } } } function __ALOR_DCL_interop_init( address landContractAddress, address estateContractAddress, uint256 _estateId ) internal onlyInitializing { landContract = ILANDRegistry(landContractAddress); estateContract = IEstateRegistry(estateContractAddress); estateId = _estateId; } function __ALOR_Exclusive_Manager_init( address expiryTableContractAddress ) internal onlyInitializing { expiryTable = IExclusiveManagerExpiryTable(expiryTableContractAddress); emit NewManagerExpiryTable(expiryTableContractAddress); } // this function overwrites holder data balances and frees holderIds that are no longer in use function patchHolderDataFault(uint256[] calldata holderData, uint16[] calldata oldHolderIds) external onlyOwner { for(uint16 i = 0; i < holderData.length; i++) { //holderId is index + 1 address holderAddr = address(uint160(holderData[i] >> 96)); uint16 balance = uint16((holderData[i] & maskOutAddr) >> 80); _holderInfo[holderAddr].balance = balance; } for(uint16 i = 0; i < oldHolderIds.length; i++) { // can't call the internal function because we only wish to dealloc the `_holderAddrs` entries _holderAddrs[oldHolderIds[i]] = address(0); _freshHolderIdStack.push(oldHolderIds[i]); } } // this is a seperate function which fixes the parcels who were owned by orphaned holders function patchMapData(uint16[] calldata plotIds, uint16[] calldata correctedHolderIds) external onlyOwner { for(uint i = 0; i < plotIds.length; i++) { uint16 tokenPageId = plotIds[i] >> 4; // token page ID is 12 most significant bits uint16 segId = plotIds[i] & 0xF; // token segment ID at 4 least sig bits _owners[tokenPageId][segId] = correctedHolderIds[i]; } } modifier onlyValidManager(uint256 tokenId) { address tokenOwner = ownerOf(tokenId); if(_isUnderExclusiveManagement(tokenId)) { require( msg.sender == exclusiveUpdateManagers[tokenId].managerAddress, "ALOR: Plot is under an exclusive update manager" ); } else { require( msg.sender == tokenOwner || _isManagerOf(msg.sender,tokenOwner), "ALOR: You are neither the owner nor a update manager" ); } _; } modifier onlyValidManagerMany(uint256[] calldata tokenIds) { for(uint i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; address tokenOwner = ownerOf(tokenId); if(_isUnderExclusiveManagement(tokenId)) { require( msg.sender == exclusiveUpdateManagers[tokenId].managerAddress, "ALOR: Plot is under an exclusive update manager" ); } else { require( msg.sender == tokenOwner || _isManagerOf(msg.sender,tokenOwner), "ALOR: You are neither the owner nor a update manager" ); } } _; } // Read parcel operators; simple pass through function updateOperator(uint256 tokenId) external view returns (address) { return landContract.updateOperator(tokenId); } // Setting of parcel operators function setUpdateOperator(address newOperator, uint256 tokenId) onlyValidManager(tokenId) nonReentrant external { _setUpdateOperator(newOperator, tokenId); } function setManyUpdateOperator(address newOperator, uint256[] calldata tokenIds) onlyValidManagerMany(tokenIds) nonReentrant external { for (uint i = 0; i < tokenIds.length; i++) { require(ownerOf(tokenIds[i]) == msg.sender, "ALOR: Not owner of plots"); } _setManyUpdateOperator(newOperator, tokenIds); } /** * @dev Set an updateManager for an account * @param owner - address of the account to set the updateManager * @param manager - address of the account to modify updateManager entry of * @param approved - bool whether the address will be approved or not */ function setUpdateManager(address owner, address manager, bool approved) nonReentrant external { require(manager != msg.sender, "ALOR: The operator should be different from owner"); require( owner == msg.sender, "ALOR: Only owner may set it's Update Managers" ); updateManagers[owner][manager] = approved; emit UpdateManager( owner, manager, msg.sender, approved ); } // Exclusive Update Manager related methods function setExclusiveUpdateManager(uint256 tokenId, address manager, uint64 expiry, bytes[] memory data) nonReentrant external { _requireWithinMaxDelta(manager, expiry); require( ownerOf(tokenId) == msg.sender, "ALOR: Setting an Exclusive Update Manager requires you to be the owner" ); require( !_isUnderExclusiveManagement(tokenId), "ALOR: Plot cannot already be under Exclusive Management" ); exclusiveUpdateManagers[tokenId].managerAddress = manager; exclusiveUpdateManagers[tokenId].expiry = expiry; uint256[] memory tokenIds = new uint256[](1); tokenIds[0] = tokenId; IExclusiveUpdateManager(manager).newPortfolio(tokenIds, msg.sender, data); emit SetExclusiveUpdateManager( msg.sender, manager, tokenIds, data ); } function setManyExclusiveUpdateManager(uint256[] calldata tokenIds, address manager, uint64 expiry, bytes[] memory data) nonReentrant external { _requireWithinMaxDelta(manager, expiry); for(uint i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; require( ownerOf(tokenId) == msg.sender, "ALOR: Setting an Exclusive Update Manager requires you to be the owner" ); require( !_isUnderExclusiveManagement(tokenId), "ALOR: Plot cannot already be under Exclusive Management" ); exclusiveUpdateManagers[tokenId].managerAddress = manager; exclusiveUpdateManagers[tokenId].expiry = expiry; } IExclusiveUpdateManager(manager).newPortfolio(tokenIds, msg.sender, data); emit SetExclusiveUpdateManager( msg.sender, manager, tokenIds, data ); } function _innerRenewExclusiveUpdateManager(uint256 tokenId, address manager, uint64 expiry) internal { require( ownerOf(tokenId) == msg.sender, "ALOR: Setting an Exclusive Update Manager requires you to be the owner" ); require( _isUnderExclusiveManagement(tokenId) && exclusiveUpdateManagers[tokenId].managerAddress == manager, "ALOR: Plot must be under Exclusive Management" ); // All must have the same manager because the max delta changes per manager potentially exclusiveUpdateManagers[tokenId].expiry = expiry; } function _requireWithinMaxDelta(address manager, uint64 expiry) internal { require( expiry - uint64(block.timestamp) <= expiryTable.getMaxDelta(manager), "ALOR: Expiry cannot exceed the maximum delta from the current time" ); } function renewExclusiveUpdateManager(uint256 tokenId, uint64 expiry) external { address manager = exclusiveUpdateManagers[tokenId].managerAddress; _requireWithinMaxDelta(manager, expiry); _innerRenewExclusiveUpdateManager(tokenId, manager, expiry); uint256[] memory tokenIds = new uint256[](1); tokenIds[0] = tokenId; emit RenewExclusiveUpdateManager( msg.sender, exclusiveUpdateManagers[tokenId].managerAddress, tokenIds ); } function renewManyExclusiveUpdateManager(uint256[] calldata tokenIds, uint64 expiry) external { if(tokenIds.length == 0) return; address manager = exclusiveUpdateManagers[tokenIds[0]].managerAddress; _requireWithinMaxDelta(manager, expiry); for(uint i = 0; i < tokenIds.length; i++) { _innerRenewExclusiveUpdateManager(tokenIds[i], manager, expiry); } emit RenewExclusiveUpdateManager( msg.sender, exclusiveUpdateManagers[tokenIds[0]].managerAddress, tokenIds ); } function relinquishExclusiveManagement(uint256[] memory tokenIds) external { for(uint i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; require( exclusiveUpdateManagers[tokenId].managerAddress == msg.sender && exclusiveUpdateManagers[tokenId].expiry > block.timestamp, "ALOR : Must be active exclusive manager of all plots" ); exclusiveUpdateManagers[tokenId].expiry = uint64(block.timestamp) - 1; } emit RelinquishExclusiveManagement(tokenIds, msg.sender); } // Admin functions function setExclusiveManagerExpiryTable(address newExpiryTableAddress) onlyOwner external { expiryTable = IExclusiveManagerExpiryTable(newExpiryTableAddress); emit NewManagerExpiryTable(newExpiryTableAddress); } function _setUpdateOperator(address newOperator, uint256 tokenId) internal { estateContract.setLandUpdateOperator(estateId, tokenId, newOperator); } function _setManyUpdateOperator(address newOperator, uint256[] memory tokenIds) internal { estateContract.setManyLandUpdateOperator(estateId, tokenIds, newOperator); } function _beforeBulkTokenTransfer( address from, address to, uint256[] calldata tokenIds ) internal override { super._beforeBulkTokenTransfer ( from, to, tokenIds ); for(uint i = 0; i < tokenIds.length; i++) { require(!_isUnderExclusiveManagement(tokenIds[i]), "ALOR: Cannot transfer plot while it being exclusively managed"); } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { super._beforeTokenTransfer( from, to, tokenId ); require(!_isUnderExclusiveManagement(tokenId), "ALOR: Cannot transfer plot while it being exclusively managed"); } function _afterBulkTokenTransfer( address from, address to, uint256[] calldata tokenIds ) internal override { super._afterBulkTokenTransfer ( from, to, tokenIds ); _setManyUpdateOperator(to,tokenIds); } function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal override { super._afterTokenTransfer( from, to, tokenId ); _setUpdateOperator(to,tokenId); } function _isUnderExclusiveManagement(uint256 tokenId) internal view returns (bool) { // If the expiry is non-zero there must be an exclusive update manager // So it suffices to check the current UNIX timestamp is less than the expiry variable return ( // We are only ever under management if the expiry is greater than now exclusiveUpdateManagers[tokenId].expiry > block.timestamp && // If the maxDelta of the contract is zero then the contract is banned so it cannot be a manager expiryTable.getMaxDelta( exclusiveUpdateManagers[tokenId].managerAddress ) != 0 ); } function _isManagerOf(address accessor, address plotOwner) internal view returns (bool) { return updateManagers[plotOwner][accessor]; } function _baseURI() internal view override returns (string memory) { return "https://aetheria.io/data/alor.json?id="; } function tokenIdToInternalRep(uint256 tokenId) internal pure override returns (uint16) { require(tokenId > clearHigh, "ALOR: Impossible tokenId under DCL tokenId schema"); // TODO : Add check to see if it's within aetheria's boundry etc return ( uint16((tokenId & clearLow) >> (128 - 8)) + (uint16(tokenId & clearHigh)) - (uint16(xfloor) << 8) - yfloor ); } function internalRepToTokenId(uint16 internalId) internal pure override returns (uint256) { uint256 x = ((internalId & 0xff00) >> 8) + uint16(xfloor); uint256 y = (internalId & 0x00ff) + yfloor; return (x << 128) + y; } event NewManagerExpiryTable( address indexed expiryTableContractAddress ); event UpdateManager( address indexed owner, address indexed operator, address indexed caller, bool approved ); event SetExclusiveUpdateManager( address indexed owner, address indexed manager, uint256[] indexed tokenIds, bytes[] data ); event RenewExclusiveUpdateManager( address indexed owner, address indexed manager, uint256[] indexed tokenIds ); event RelinquishExclusiveManagement( uint256[] indexed tokenIds, address indexed exclusiveManager ); uint256[44] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.7 <0.9.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; interface IERC1412Upgradeable is IERC721Upgradeable { /// @notice Transfers the ownership of multiple NFTs from one address to another address /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenIds The NFTs to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeBatchTransferFrom( address _from, address _to, uint256[] calldata _tokenIds, bytes calldata _data ) external; /// @notice Transfers the ownership of multiple NFTs from one address to another address /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenIds The NFTs to transfer function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _tokenIds) external; } pragma solidity ^0.8.13; //SPDX-License-Identifier: AGPL interface IEstateRegistry { function mint(address to, string calldata metadata) external returns (uint256); function ownerOf(uint256 _tokenId) external returns (address _owner); // from ERC721 function setManyLandUpdateOperator(uint256 _estateId, uint256[] memory _landIds, address _operator) external; function setLandUpdateOperator(uint256 _estateId, uint256 _landId, address _operator) external; // Events event CreateEstate( address indexed _owner, uint256 indexed _estateId, string _data ); event AddLand( uint256 indexed _estateId, uint256 indexed _landId ); event RemoveLand( uint256 indexed _estateId, uint256 indexed _landId, address indexed _destinatary ); event Update( uint256 indexed _assetId, address indexed _holder, address indexed _operator, string _data ); event UpdateOperator( uint256 indexed _estateId, address indexed _operator ); event UpdateManager( address indexed _owner, address indexed _operator, address indexed _caller, bool _approved ); event SetLANDRegistry( address indexed _registry ); } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.7 <0.9.0; import "@openzeppelin/contracts/interfaces/IERC165.sol"; interface IExclusiveManagerExpiryTable is IERC165 { function getMaxDelta(address manager) view external returns (uint64); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.7 <0.9.0; import "@openzeppelin/contracts/interfaces/IERC165.sol"; interface IExclusiveUpdateManager is IERC165 { // New portfolio is called after tokens are put under the contracts exclusive management // This allows the contract to reject assignments of management if it wishes (useful for compliance) // It also allows for book-keeping allowing the contract to know all tokens it is exclusive manager for function newPortfolio(uint256[] calldata tokenIds, address owner, bytes[] calldata data) external; } // solium-disable linebreak-style pragma solidity ^0.8.13; //SPDX-License-Identifier: AGPL interface ILANDRegistry { // LAND can be assigned by the owner function assignNewParcel(int x, int y, address beneficiary) external; function assignMultipleParcels(int[] calldata x, int[] calldata y, address beneficiary) external; // After one year, LAND can be claimed from an inactive public key function ping() external; // LAND-centric getters function encodeTokenId(int x, int y) external pure returns (uint256); function decodeTokenId(uint value) external pure returns (int, int); function exists(int x, int y) external view returns (bool); function ownerOfLand(int x, int y) external view returns (address); function ownerOfLandMany(int[] calldata x, int[] calldata y) external view returns (address[] memory); function landOf(address owner) external view returns (int[] memory, int[] memory); function landData(int x, int y) external view returns (string memory); function updateOperator(uint256 tokenId) external view returns (address); // Transfer LAND function transferLand(int x, int y, address to) external; function transferManyLand(int[] calldata x, int[] calldata y, address to) external; // Update LAND function updateLandData(int x, int y, string calldata data) external; function updateManyLandData(int[] calldata x, int[] calldata y, string calldata data) external; //operators function setUpdateOperator(uint256 assetId, address operator) external; // Events event Update( uint256 indexed assetId, address indexed holder, address indexed operator, string data ); event UpdateOperator( uint256 indexed assetId, address indexed operator ); event DeployAuthorized( address indexed _caller, address indexed _deployer ); event DeployForbidden( address indexed _caller, address indexed _deployer ); } // SPDX-License-Identifier: MIT // A modified implementation of the openzeppelin ERC721 contract optimised for large scale mints // Written by Alonzo C pragma solidity >=0.8.7 <0.9.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "../interfaces/IERC1412Upgradeable.sol"; /** * @dev An ERC721 implementation designed for efficient mass-minting, includig the Metadata extension * This implementation can only handle upto 2^16 - 1 tokens */ contract MassERC721Upgradeable is Initializable, ContextUpgradeable, ReentrancyGuardUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC1412Upgradeable/*, IERC721EnumerableUpgradeable*/ { using AddressUpgradeable for address; using StringsUpgradeable for uint256; struct HolderData { uint16 holderId; // A holderId of 0 implies the address has no holderId yet uint128 balance; } //Mapping of a short-tokenId block to their holderId mapping(uint16 => uint16[16]) internal _owners; // Mapping of owner addresses to token count and holderId mapping(address => HolderData) internal _holderInfo; // Mapping of holderIds to addreses mapping(uint16 => address) internal _holderAddrs; // Mapping encoding a tree with branching factor 16 which acts as an index for finding the Nth NFT token // The tree is updated upon burn and mint // It is expected the contract importing this one implements the initial tree build //mapping(uint256 => uint16[16][]) internal _indexTree; // Mapping from token ID to approved address // This is unchanged from the original openzeppelin implementation // because approvals don't get set on the mint mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // If the freshHolder stack is empty any new account will get their holderId from this variable // and then increment it otherwise they take the id ontop of the stack uint16 internal _freshestHolderId; // This array stores the holderIds of users who no longer hold any tokens. // Allowing for them to be recycled for new holders. // This ensures that holderIds never overflow as we already assume that there are at most `2^16 - 1` tokens uint16[] internal _freshHolderIdStack; // This array stores a list of keys for which _owners is intialised. // Allowing for quick global token enumeration and a fallback per-user enumeration //uint16[] internal _activeMapPages; // This identifies the root of the index tree, _indexTree[_indexTreeRootLayer][0] is always the root node //uint256 internal _indexTreeRootLayer; // Token name string private _name; // Token symbol string private _symbol; // Token Supply uint256 private _totalSupply; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __MassERC721Upgradeable_init(string memory name_, string memory symbol_, uint256 totalSupply_) internal onlyInitializing { __MassERC721Upgradeable_init_unchained(name_, symbol_, totalSupply_); } function __MassERC721Upgradeable_init_unchained( string memory name_, string memory symbol_, uint256 totalSupply_ ) internal onlyInitializing { _freshestHolderId = 1; _name = name_; _symbol = symbol_; _totalSupply = totalSupply_; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) nonReentrant external virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) nonReentrant external virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) nonReentrant external virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function batchTransferFrom( address from, address to, uint256[] calldata tokenIds ) nonReentrant external { require( _isApprovedOrOwnerofBatch(_msgSender(), tokenIds), "ERC721: transfer caller is not owner nor approved for a token" ); _batchTransfer(from, to, tokenIds); } /// @notice Transfers the ownership of multiple NFTs from one address to another address /// @param from The current owner of the NFT /// @param to The new owner /// @param tokenIds The NFTs to transfer function safeBatchTransferFrom( address from, address to, uint256[] calldata tokenIds ) nonReentrant external virtual override { require( _isApprovedOrOwnerofBatch(_msgSender(), tokenIds), "ERC721: transfer caller is not owner nor approved for a token" ); _batchTransfer(from, to, tokenIds); // This is gas hungry but I know not of a standard for ERC721 batch recievers for(uint256 i = 0; i < tokenIds.length; i++) { require( _checkOnERC721Received(from, to, tokenIds[i], ""), "MassERC721: transfer to non ERC721Receiver implementer" ); } } /// @notice Transfers the ownership of multiple NFTs from one address to another address /// @param from The current owner of the NFT /// @param to The new owner /// @param tokenIds The NFTs to transfer /// @param data Additional data with no specified format, sent in call to `to` function safeBatchTransferFrom( address from, address to, uint256[] calldata tokenIds, bytes memory data ) nonReentrant external virtual override { require( _isApprovedOrOwnerofBatch(_msgSender(), tokenIds), "ERC721: transfer caller is not owner nor approved for a token" ); _batchTransfer(from, to, tokenIds); // This is gas hungry but I know not of a standard for ERC721 batch recievers for(uint256 i = 0; i < tokenIds.length; i++) { require( _checkOnERC721Received(from, to, tokenIds[i], data), "MassERC721: transfer to non ERC721Receiver implementer" ); } } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) nonReentrant external virtual override { address owner = _holderAddrs[_holderOf(tokenId)]; require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) nonReentrant external virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ /*function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: index must be within bounds"); uint16 holderId = _holderInfo[owner].holderId; assert((holderId != 0) && (holderId != 0xffff)); uint256 runningCount = 0; for(uint256 p = 0; p < _activeMapPages.length; p++) { uint16 tokenPageId = _activeMapPages[p]; for(uint16 i = 0; i < 16; i++) { if(_owners[tokenPageId][i] == holderId) { if(runningCount == index) { return internalRepToTokenId((tokenPageId << 4) + i); } runningCount++; } } } }*/ /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ /*function tokenByIndex(uint256 index) external view returns (uint256) { require(index < _totalSupply(), "ERC721Enumerable: index must be within bounds"); uint256 layer = _indexTreeRootLayer; uint256 offset = 0; uint256 occupancyOfPage; uint16 trailingSum = 0; uint16 tokenPageIndex = uint16(index); while(true) { uint16 runningSum = 0; uint i = 0; for(; i < 16; i++) { runningSum += _indexTree[layer][offset][i]; if(tokenPageIndex < runningSum) { tokenPageIndex -= runningSum - _indexTree[layer][offset][i]; break; } trailingSum += _indexTree[layer][offset][i]; } if(layer == 0) { occupancyOfPage = _indexTree[layer][offset][i]; offset = (offset * 16) + i; break; } offset = (offset * 16) + i; layer--; } uint16 tokenPageId = _activeMapPages[offset]; assert(index >= trailingSum); uint16 effectiveIndex = uint16(index - trailingSum); uint16 segId; if(occupancyOfPage == 16) { // when the page is full we can just directly index without search segId = effectiveIndex; } else { // Have to implement linear search as page is not fully occupied uint occupiedSlotsSeen = 0; for(uint16 i = 0; i < 16; i++) { uint16 holderId = _owners[tokenPageId][i]; bool isOccupied = !((holderId == 0x0000) || (holderId == 0xffff)); if(isOccupied) {occupiedSlotsSeen++;} if(occupiedSlotsSeen == effectiveIndex + 1) { segId = i; break; } } } assert(_exists(internalRepToTokenId((tokenPageId << 4) + segId))); return internalRepToTokenId((tokenPageId << 4) + segId); }*/ /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || interfaceId == type(IERC1412Upgradeable).interfaceId || //interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderInfo[owner].balance; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view returns (address owner) { require(_exists(tokenId), "ERC721: owner query for nonexistent token"); uint16 ownersHolderId = _holderOf(tokenId); address owner = _holderAddrs[ownersHolderId]; return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _getApproved(tokenId); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); uint16 holderId = _holderInfo[to].holderId; if(holderId == 0) { //This account doesn't have a holderId! We have to get a fresh one. holderId = _freshHolderId(to); } _holderInfo[to].balance += 1; _totalSupply += 1; uint16 reducedTokenId = tokenIdToInternalRep(tokenId); uint16 tokenPageId = reducedTokenId >> 4; uint16 segId = reducedTokenId & 0xF; _owners[tokenPageId][segId] = holderId; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = MassERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _holderInfo[owner].balance -= 1; _totalSupply -= 1; uint16 reducedTokenId = tokenIdToInternalRep(tokenId); uint16 tokenPageId = reducedTokenId >> 4; uint16 segId = reducedTokenId & 0xF; _owners[tokenPageId][segId] = 0xffff; // 0x0000 and 0xffff are both if(_holderInfo[owner].balance == 0) { // If they have no tokens we should free their holderId _freeHolderId(_holderInfo[owner].holderId); } emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); // Get the payee's holderId, and if they don't have one get them one uint16 toHolderId = _holderInfo[to].holderId; if(toHolderId == 0) { //This account doesn't have a holderId! We have to get a fresh one. toHolderId = _freshHolderId(to); } // Update balances _holderInfo[to].balance += 1; _holderInfo[from].balance -= 1; // Decode the reduced token id uint16 reducedTokenId = tokenIdToInternalRep(tokenId); uint16 tokenPageId = reducedTokenId >> 4; uint16 segId = reducedTokenId & 0xF; _owners[tokenPageId][segId] = toHolderId; if(_holderInfo[from].balance == 0) { _freeHolderId(_holderInfo[from].holderId); } emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { if(_tokenApprovals[tokenId] != to) { _tokenApprovals[tokenId] = to; emit Approval(MassERC721Upgradeable.ownerOf(tokenId), to, tokenId); } } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } function _batchTransfer( address from, address to, uint256[] calldata tokenIds ) internal virtual { require(to != address(0), "ERC721: transfer to the zero address"); require(tokenIds.length > 0, "ERC721: cannot transfer empty list of tokens"); _beforeBulkTokenTransfer(from, to, tokenIds); // Get the payee's holderId, and if they don't have one get them one uint16 toHolderId = _holderInfo[to].holderId; if(toHolderId == 0) { //This account doesn't have a holderId! We have to get a fresh one. toHolderId = _freshHolderId(to); } // Update balances _holderInfo[to].balance += uint128(tokenIds.length); _holderInfo[from].balance -= uint128(tokenIds.length); for(uint i = 0; i < tokenIds.length; i++) { // Clear approvals from the previous owner _approve(address(0), tokenIds[i]); // Decode the reduced token id uint16 reducedTokenId = tokenIdToInternalRep(tokenIds[i]); uint16 tokenPageId = reducedTokenId >> 4; uint16 segId = reducedTokenId & 0xF; _owners[tokenPageId][segId] = toHolderId; emit Transfer(from, to, tokenIds[i]); } if(_holderInfo[from].balance == 0) { _freeHolderId(_holderInfo[from].holderId); } _afterBulkTokenTransfer(from, to, tokenIds); } /** * @dev Hook that is called before any token transfer, apart from a bulk transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual { /*if (from == address(0)) { _modifyAllTokensEnumeration(tokenId,true); } if (to == address(0)) { _modifyAllTokensEnumeration(tokenId,false); }*/ } /** * @dev Hook that is called after any transfer of tokens, apart from a bulk transfer. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called before a bulk token transfer. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeBulkTokenTransfer( address from, address to, uint256[] calldata tokenIds ) internal virtual { /* if (from == address(0)) { for(uint i = 0; i < tokenIds.length; i++) { _modifyAllTokensEnumeration(tokenIds[i],true); // TODO : If the performance becomes a problem consider batching this } } if (to == address(0)) { for(uint i = 0; i < tokenIds.length; i++) { _modifyAllTokensEnumeration(tokenIds[i],false); } } */ } /** * @dev Hook that is called after bulk transfer of tokens. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterBulkTokenTransfer( address from, address to, uint256[] calldata tokenIds ) internal virtual { } /** * @dev Creates a fresh holderId for an address without one. * * Requirements: * - `newAddress` must not already have a holderId * */ function _freshHolderId(address newAddress) internal returns (uint16) { require(_holderInfo[newAddress].holderId == 0, "MassERC721: Address already has holderId"); require((_freshHolderIdStack.length > 0) || (_freshestHolderId < 65535), "MassERC721: Out of holderIds"); // due to the above require clause holderId 0xffff is impossible to reach // Therefore we can use it as a second "no owner" value allowing us to avoid using a second "active page" map // Instead we can just check if _owners[foo] is non-zero as burning sets the holderId to 0xffff uint16 newHolderId; if (_freshHolderIdStack.length == 0) { newHolderId = _freshestHolderId; _freshestHolderId++; } else { newHolderId = _freshHolderIdStack[_freshHolderIdStack.length - 1]; _freshHolderIdStack.pop(); } _holderInfo[newAddress].holderId = newHolderId; _holderAddrs[newHolderId] = newAddress; return newHolderId; } /** * @dev Frees a holderId that holds no tokens and returns the Id to the fresh holder stack. * * Requirements: * - `holderId` must be in use * - `holderId` must not hold any tokens * */ function _freeHolderId(uint16 holderId) internal { require(_holderAddrs[holderId] != address(0) , "MassERC721: HolderId not in use"); require(_holderInfo[_holderAddrs[holderId]].balance == 0, "MassERC721: HolderId still holds tokens"); _holderInfo[_holderAddrs[holderId]].holderId = 0; _holderAddrs[holderId] = address(0); _freshHolderIdStack.push(holderId); } function _holderOf(uint256 tokenId) internal view returns (uint16 holderId) { uint16 reducedTokenId = tokenIdToInternalRep(tokenId); uint16 tokenPageId = reducedTokenId >> 4; uint16 segId = reducedTokenId & 0xF; return _owners[tokenPageId][segId]; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev Implements `getApproved` but without the existence check guard */ function _getApproved(uint256 tokenId) internal view virtual returns (address) { return _tokenApprovals[tokenId]; } /* function _totalSupply() internal view returns (uint256) { return _totalSupply; /*uint256 layer = _indexTreeRootLayer; uint256 sum = 0; for(uint i = 0; i < 16; i++) { sum += _indexTree[layer][0][i]; } return sum; }*/ /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { uint16 holder = _holderOf(tokenId); return (holder != 0) && (holder != 0xffff); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = MassERC721Upgradeable.ownerOf(tokenId); return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); } /** * @dev Returns whether `spender` is allowed to manage all of `tokenIds`. * * Requirements: * * - all of `tokenIds` must exist */ function _isApprovedOrOwnerofBatch( address spender, uint256[] calldata tokenIds ) internal view virtual returns (bool) { for(uint i = 0; i < tokenIds.length; i++) { require(_exists(tokenIds[i]), "ERC721: operator query contains nonexistent token"); } for(uint i = 0; i < tokenIds.length; i++) { address owner = ownerOf(tokenIds[i]); if(!(spender == owner || isApprovedForAll(owner, spender) || _getApproved(tokenIds[i]) == spender)) { return false; } } return true; //this is only true if the spender is approved for } /** * @dev Finds the index of the `tokenPageId` within `_activeMapPages` * NOTE: This should probably be replaced by a mapping lookup but we can't afford a mapping at deploy time */ /*function _getTokenPageIndex(uint16 reducedTokenId) internal view returns (uint16 tokenPageIndex) { uint16 tokenPageId = reducedTokenId >> 4; for(tokenPageIndex = 0; tokenPageIndex < _activeMapPages.length; tokenPageIndex++) { if(_activeMapPages[tokenPageIndex] == tokenPageId) { break; } // If we have a valid token that we are burning this should be impossible assert(tokenPageIndex != _activeMapPages.length-1); } }*/ /** * @dev Returns the internal representation of a tokenId */ function tokenIdToInternalRep(uint256 tokenId) internal pure virtual returns (uint16) { require(tokenId < 65536, "Token Id out of bounds"); // We bounds check to ensure a bijection relates valid internalIds and user-facing tokenIds // If we did not bounds check there would be a many-to-one map from user-facing tokenIds to internalIds return uint16(tokenId); } function internalRepToTokenId(uint16 internalId) internal pure virtual returns (uint256) { return uint256(internalId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to) .onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /*function _modifyAllTokensEnumeration(uint256 tokenId, bool isMint) private { uint16 reducedTokenId = tokenIdToInternalRep(tokenId); uint256 pageData; if(isMint) { assembly { mstore(0,reducedTokenId) mstore(32,_owners.slot) let hash := keccak256(0,64) pageData := sload(hash) } } uint16 tokenPageIndex; // NOTE: we are gonna mutate this to save memory if((pageData == 0) && isMint) { // If the page is new we need to append it to the active page list tokenPageIndex = uint16(_activeMapPages.length); _activeMapPages.push(reducedTokenId); } else { tokenPageIndex = _getTokenPageIndex(reducedTokenId); } uint256 layer = _indexTreeRootLayer; uint256 offset = 0; while(true) { uint16 runningSum = 0; uint i = 0; for(; i < 16; i++) { runningSum += _indexTree[layer][offset][i]; if(tokenPageIndex < runningSum) { if(isMint) { _indexTree[layer][offset][i]++; } else { _indexTree[layer][offset][i]--; } tokenPageIndex -= runningSum - _indexTree[layer][offset][i]; break; } } if(layer == 0) { break; //No need to update offset here because we don't use it after the loop } offset = (offset * 16) + i; layer--; } } */ uint256[44] private __gap; } // 0:15
File 4 of 6: AdminUpgradeabilityProxy
pragma solidity ^0.4.24; // File: node_modules/zos-lib/contracts/upgradeability/Proxy.sol /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: node_modules/zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol /** * @title UpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param _implementation Address of the initial implementation. */ constructor(address _implementation) public { assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation")); _setImplementation(_implementation); } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } // File: node_modules/zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol /** * @title AdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param _implementation address of the initial implementation. */ constructor(address _implementation) UpgradeabilityProxy(_implementation) public { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin { _upgradeTo(newImplementation); require(address(this).call.value(msg.value)(data)); } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } }
File 5 of 6: EstateRegistry
pragma solidity ^0.4.24; // File: openzeppelin-zos/contracts/introspection/ERC165.sol /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // File: openzeppelin-zos/contracts/token/ERC721/ERC721Basic.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // File: openzeppelin-zos/contracts/token/ERC721/ERC721.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // File: openzeppelin-zos/contracts/token/ERC721/ERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } // File: openzeppelin-zos/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-zos/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: openzeppelin-zos/contracts/introspection/ERC165Support.sol /** * @title ERC165Support * @dev Implements ERC165 returning true for ERC165 interface identifier */ contract ERC165Support is ERC165 { bytes4 internal constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return _supportsInterface(_interfaceId); } function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { return _interfaceId == InterfaceId_ERC165; } } // File: openzeppelin-zos/contracts/token/ERC721/ERC721BasicToken.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC165Support, ERC721Basic { bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { return super._supportsInterface(_interfaceId) || _interfaceId == InterfaceId_ERC721 || _interfaceId == InterfaceId_ERC721Exists; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: zos-lib/contracts/migrations/Migratable.sol /** * @title Migratable * Helper contract to support intialization and migration schemes between * different implementations of a contract in the context of upgradeability. * To use it, replace the constructor with a function that has the * `isInitializer` modifier starting with `"0"` as `migrationId`. * When you want to apply some migration code during an upgrade, increase * the `migrationId`. Or, if the migration code must be applied only after * another migration has been already applied, use the `isMigration` modifier. * This helper supports multiple inheritance. * WARNING: It is the developer's responsibility to ensure that migrations are * applied in a correct order, or that they are run at all. * See `Initializable` for a simpler version. */ contract Migratable { /** * @dev Emitted when the contract applies a migration. * @param contractName Name of the Contract. * @param migrationId Identifier of the migration applied. */ event Migrated(string contractName, string migrationId); /** * @dev Mapping of the already applied migrations. * (contractName => (migrationId => bool)) */ mapping (string => mapping (string => bool)) internal migrated; /** * @dev Internal migration id used to specify that a contract has already been initialized. */ string constant private INITIALIZED_ID = "initialized"; /** * @dev Modifier to use in the initialization function of a contract. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. */ modifier isInitializer(string contractName, string migrationId) { validateMigrationIsPending(contractName, INITIALIZED_ID); validateMigrationIsPending(contractName, migrationId); _; emit Migrated(contractName, migrationId); migrated[contractName][migrationId] = true; migrated[contractName][INITIALIZED_ID] = true; } /** * @dev Modifier to use in the migration of a contract. * @param contractName Name of the contract. * @param requiredMigrationId Identifier of the previous migration, required * to apply new one. * @param newMigrationId Identifier of the new migration to be applied. */ modifier isMigration(string contractName, string requiredMigrationId, string newMigrationId) { require(isMigrated(contractName, requiredMigrationId), "Prerequisite migration ID has not been run yet"); validateMigrationIsPending(contractName, newMigrationId); _; emit Migrated(contractName, newMigrationId); migrated[contractName][newMigrationId] = true; } /** * @dev Returns true if the contract migration was applied. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. * @return true if the contract migration was applied, false otherwise. */ function isMigrated(string contractName, string migrationId) public view returns(bool) { return migrated[contractName][migrationId]; } /** * @dev Initializer that marks the contract as initialized. * It is important to run this if you had deployed a previous version of a Migratable contract. * For more information see https://github.com/zeppelinos/zos-lib/issues/158. */ function initialize() isInitializer("Migratable", "1.2.1") public { } /** * @dev Reverts if the requested migration was already executed. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. */ function validateMigrationIsPending(string contractName, string migrationId) private view { require(!isMigrated(contractName, migrationId), "Requested target migration ID has already been run"); } } // File: openzeppelin-zos/contracts/token/ERC721/ERC721Token.sol /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is Migratable, ERC165Support, ERC721BasicToken, ERC721 { bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ function initialize(string _name, string _symbol) public isInitializer("ERC721Token", "1.9.0") { name_ = _name; symbol_ = _symbol; } function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { return super._supportsInterface(_interfaceId) || _interfaceId == InterfaceId_ERC721Enumerable || _interfaceId == InterfaceId_ERC721Metadata; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } // File: openzeppelin-zos/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Migratable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address _sender) public isInitializer("Ownable", "1.9.0") { owner = _sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/estate/IEstateRegistry.sol contract IEstateRegistry { function mint(address to, string metadata) external returns (uint256); function ownerOf(uint256 _tokenId) public view returns (address _owner); // from ERC721 // Events event CreateEstate( address indexed _owner, uint256 indexed _estateId, string _data ); event AddLand( uint256 indexed _estateId, uint256 indexed _landId ); event RemoveLand( uint256 indexed _estateId, uint256 indexed _landId, address indexed _destinatary ); event Update( uint256 indexed _assetId, address indexed _holder, address indexed _operator, string _data ); event UpdateOperator( uint256 indexed _estateId, address indexed _operator ); event UpdateManager( address indexed _owner, address indexed _operator, address indexed _caller, bool _approved ); event SetLANDRegistry( address indexed _registry ); event SetEstateLandBalanceToken( address indexed _previousEstateLandBalance, address indexed _newEstateLandBalance ); } // File: contracts/minimeToken/IMinimeToken.sol interface IMiniMeToken { //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) external returns (bool); /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) external returns (bool); /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) external view returns (uint256 balance); event Transfer(address indexed _from, address indexed _to, uint256 _amount); } // File: contracts/estate/EstateStorage.sol contract LANDRegistry { function decodeTokenId(uint value) external pure returns (int, int); function updateLandData(int x, int y, string data) external; function setUpdateOperator(uint256 assetId, address operator) external; function setManyUpdateOperator(uint256[] landIds, address operator) external; function ping() public; function ownerOf(uint256 tokenId) public returns (address); function safeTransferFrom(address, address, uint256) public; function updateOperator(uint256 landId) public returns (address); } contract EstateStorage { bytes4 internal constant InterfaceId_GetMetadata = bytes4(keccak256("getMetadata(uint256)")); bytes4 internal constant InterfaceId_VerifyFingerprint = bytes4( keccak256("verifyFingerprint(uint256,bytes)") ); LANDRegistry public registry; // From Estate to list of owned LAND ids (LANDs) mapping(uint256 => uint256[]) public estateLandIds; // From LAND id (LAND) to its owner Estate id mapping(uint256 => uint256) public landIdEstate; // From Estate id to mapping of LAND id to index on the array above (estateLandIds) mapping(uint256 => mapping(uint256 => uint256)) public estateLandIndex; // Metadata of the Estate mapping(uint256 => string) internal estateData; // Operator of the Estate mapping (uint256 => address) public updateOperator; // From account to mapping of operator to bool whether is allowed to update content or not mapping(address => mapping(address => bool)) public updateManager; // Land balance minime token IMiniMeToken public estateLandBalance; // Registered balance accounts mapping(address => bool) public registeredBalance; } // File: contracts/estate/EstateRegistry.sol /** * @title ERC721 registry of every minted Estate and their owned LANDs * @dev Usings we are inheriting and depending on: * From ERC721Token: * - using SafeMath for uint256; * - using AddressUtils for address; */ // solium-disable-next-line max-len contract EstateRegistry is Migratable, IEstateRegistry, ERC721Token, ERC721Receiver, Ownable, EstateStorage { modifier canTransfer(uint256 estateId) { require(isApprovedOrOwner(msg.sender, estateId), "Only owner or operator can transfer"); _; } modifier onlyRegistry() { require(msg.sender == address(registry), "Only the registry can make this operation"); _; } modifier onlyUpdateAuthorized(uint256 estateId) { require(_isUpdateAuthorized(msg.sender, estateId), "Unauthorized user"); _; } modifier onlyLandUpdateAuthorized(uint256 estateId, uint256 landId) { require(_isLandUpdateAuthorized(msg.sender, estateId, landId), "unauthorized user"); _; } modifier canSetUpdateOperator(uint256 estateId) { address owner = ownerOf(estateId); require( isApprovedOrOwner(msg.sender, estateId) || updateManager[owner][msg.sender], "unauthorized user" ); _; } /** * @dev Mint a new Estate with some metadata * @param to The address that will own the minted token * @param metadata Set an initial metadata * @return An uint256 representing the new token id */ function mint(address to, string metadata) external onlyRegistry returns (uint256) { return _mintEstate(to, metadata); } /** * @notice Transfer a LAND owned by an Estate to a new owner * @param estateId Current owner of the token * @param landId LAND to be transfered * @param destinatary New owner */ function transferLand( uint256 estateId, uint256 landId, address destinatary ) external canTransfer(estateId) { return _transferLand(estateId, landId, destinatary); } /** * @notice Transfer many tokens owned by an Estate to a new owner * @param estateId Current owner of the token * @param landIds LANDs to be transfered * @param destinatary New owner */ function transferManyLands( uint256 estateId, uint256[] landIds, address destinatary ) external canTransfer(estateId) { uint length = landIds.length; for (uint i = 0; i < length; i++) { _transferLand(estateId, landIds[i], destinatary); } } /** * @notice Get the Estate id for a given LAND id * @dev This information also lives on estateLandIds, * but it being a mapping you need to know the Estate id beforehand. * @param landId LAND to search * @return The corresponding Estate id */ function getLandEstateId(uint256 landId) external view returns (uint256) { return landIdEstate[landId]; } function setLANDRegistry(address _registry) external onlyOwner { require(_registry.isContract(), "The LAND registry address should be a contract"); require(_registry != 0, "The LAND registry address should be valid"); registry = LANDRegistry(_registry); emit SetLANDRegistry(registry); } function ping() external { registry.ping(); } /** * @notice Return the amount of tokens for a given Estate * @param estateId Estate id to search * @return Tokens length */ function getEstateSize(uint256 estateId) external view returns (uint256) { return estateLandIds[estateId].length; } /** * @notice Return the amount of LANDs inside the Estates for a given address * @param _owner of the estates * @return the amount of LANDs */ function getLANDsSize(address _owner) public view returns (uint256) { // Avoid balanceOf to not compute an unnecesary require uint256 landsSize; uint256 balance = ownedTokensCount[_owner]; for (uint256 i; i < balance; i++) { uint256 estateId = ownedTokens[_owner][i]; landsSize += estateLandIds[estateId].length; } return landsSize; } /** * @notice Update the metadata of an Estate * @dev Reverts if the Estate does not exist or the user is not authorized * @param estateId Estate id to update * @param metadata string metadata */ function updateMetadata( uint256 estateId, string metadata ) external onlyUpdateAuthorized(estateId) { _updateMetadata(estateId, metadata); emit Update( estateId, ownerOf(estateId), msg.sender, metadata ); } function getMetadata(uint256 estateId) external view returns (string) { return estateData[estateId]; } function isUpdateAuthorized(address operator, uint256 estateId) external view returns (bool) { return _isUpdateAuthorized(operator, estateId); } /** * @dev Set an updateManager for an account * @param _owner - address of the account to set the updateManager * @param _operator - address of the account to be set as the updateManager * @param _approved - bool whether the address will be approved or not */ function setUpdateManager(address _owner, address _operator, bool _approved) external { require(_operator != msg.sender, "The operator should be different from owner"); require( _owner == msg.sender || operatorApprovals[_owner][msg.sender], "Unauthorized user" ); updateManager[_owner][_operator] = _approved; emit UpdateManager( _owner, _operator, msg.sender, _approved ); } /** * @notice Set Estate updateOperator * @param estateId - Estate id * @param operator - address of the account to be set as the updateOperator */ function setUpdateOperator( uint256 estateId, address operator ) public canSetUpdateOperator(estateId) { updateOperator[estateId] = operator; emit UpdateOperator(estateId, operator); } /** * @notice Set Estates updateOperator * @param _estateIds - Estate ids * @param _operator - address of the account to be set as the updateOperator */ function setManyUpdateOperator( uint256[] _estateIds, address _operator ) public { for (uint i = 0; i < _estateIds.length; i++) { setUpdateOperator(_estateIds[i], _operator); } } /** * @notice Set LAND updateOperator * @param estateId - Estate id * @param landId - LAND to set the updateOperator * @param operator - address of the account to be set as the updateOperator */ function setLandUpdateOperator( uint256 estateId, uint256 landId, address operator ) public canSetUpdateOperator(estateId) { require(landIdEstate[landId] == estateId, "The LAND is not part of the Estate"); registry.setUpdateOperator(landId, operator); } /** * @notice Set many LAND updateOperator * @param _estateId - Estate id * @param _landIds - LANDs to set the updateOperator * @param _operator - address of the account to be set as the updateOperator */ function setManyLandUpdateOperator( uint256 _estateId, uint256[] _landIds, address _operator ) public canSetUpdateOperator(_estateId) { for (uint i = 0; i < _landIds.length; i++) { require(landIdEstate[_landIds[i]] == _estateId, "The LAND is not part of the Estate"); } registry.setManyUpdateOperator(_landIds, _operator); } function initialize( string _name, string _symbol, address _registry ) public isInitializer("EstateRegistry", "0.0.2") { require(_registry != 0, "The registry should be a valid address"); ERC721Token.initialize(_name, _symbol); Ownable.initialize(msg.sender); registry = LANDRegistry(_registry); } /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public onlyRegistry returns (bytes4) { uint256 estateId = _bytesToUint(_data); _pushLandId(estateId, _tokenId); return ERC721_RECEIVED; } /** * @dev Creates a checksum of the contents of the Estate * @param estateId the estateId to be verified */ function getFingerprint(uint256 estateId) public view returns (bytes32 result) { result = keccak256(abi.encodePacked("estateId", estateId)); uint256 length = estateLandIds[estateId].length; for (uint i = 0; i < length; i++) { result ^= keccak256(abi.encodePacked(estateLandIds[estateId][i])); } return result; } /** * @dev Verifies a checksum of the contents of the Estate * @param estateId the estateid to be verified * @param fingerprint the user provided identification of the Estate contents */ function verifyFingerprint(uint256 estateId, bytes fingerprint) public view returns (bool) { return getFingerprint(estateId) == _bytesToBytes32(fingerprint); } /** * @dev Safely transfers the ownership of multiple Estate IDs to another address * @dev Delegates to safeTransferFrom for each transfer * @dev Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param estateIds uint256 array of IDs to be transferred */ function safeTransferManyFrom(address from, address to, uint256[] estateIds) public { safeTransferManyFrom( from, to, estateIds, "" ); } /** * @dev Safely transfers the ownership of multiple Estate IDs to another address * @dev Delegates to safeTransferFrom for each transfer * @dev Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param estateIds uint256 array of IDs to be transferred * @param data bytes data to send along with a safe transfer check */ function safeTransferManyFrom( address from, address to, uint256[] estateIds, bytes data ) public { for (uint i = 0; i < estateIds.length; i++) { safeTransferFrom( from, to, estateIds[i], data ); } } /** * @dev update LAND data owned by an Estate * @param estateId Estate * @param landId LAND to be updated * @param data string metadata */ function updateLandData(uint256 estateId, uint256 landId, string data) public { _updateLandData(estateId, landId, data); } /** * @dev update LANDs data owned by an Estate * @param estateId Estate id * @param landIds LANDs to be updated * @param data string metadata */ function updateManyLandData(uint256 estateId, uint256[] landIds, string data) public { uint length = landIds.length; for (uint i = 0; i < length; i++) { _updateLandData(estateId, landIds[i], data); } } function transferFrom(address _from, address _to, uint256 _tokenId) public { uint256 estateSize = estateLandIds[_tokenId].length; require(estateSize != 0, "The Estate should not be empty"); updateOperator[_tokenId] = address(0); _updateEstateLandBalance(_from, _to, estateSize); super.transferFrom(_from, _to, _tokenId); } // check the supported interfaces via ERC165 function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { // solium-disable-next-line operator-whitespace return super._supportsInterface(_interfaceId) || _interfaceId == InterfaceId_GetMetadata || _interfaceId == InterfaceId_VerifyFingerprint; } /** * @dev Internal function to mint a new Estate with some metadata * @param to The address that will own the minted token * @param metadata Set an initial metadata * @return An uint256 representing the new token id */ function _mintEstate(address to, string metadata) internal returns (uint256) { require(to != address(0), "You can not mint to an empty address"); uint256 estateId = _getNewEstateId(); _mint(to, estateId); _updateMetadata(estateId, metadata); emit CreateEstate(to, estateId, metadata); return estateId; } /** * @dev Internal function to update an Estate metadata * @dev Does not require the Estate to exist, for a public interface use `updateMetadata` * @param estateId Estate id to update * @param metadata string metadata */ function _updateMetadata(uint256 estateId, string metadata) internal { estateData[estateId] = metadata; } /** * @notice Return a new unique id * @dev It uses totalSupply to determine the next id * @return uint256 Representing the new Estate id */ function _getNewEstateId() internal view returns (uint256) { return totalSupply().add(1); } /** * @dev Appends a new LAND id to an Estate updating all related storage * @param estateId Estate where the LAND should go * @param landId Transfered LAND */ function _pushLandId(uint256 estateId, uint256 landId) internal { require(exists(estateId), "The Estate id should exist"); require(landIdEstate[landId] == 0, "The LAND is already owned by an Estate"); require(registry.ownerOf(landId) == address(this), "The EstateRegistry cannot manage the LAND"); estateLandIds[estateId].push(landId); landIdEstate[landId] = estateId; estateLandIndex[estateId][landId] = estateLandIds[estateId].length; address owner = ownerOf(estateId); _updateEstateLandBalance(address(registry), owner, 1); emit AddLand(estateId, landId); } /** * @dev Removes a LAND from an Estate and transfers it to a new owner * @param estateId Current owner of the LAND * @param landId LAND to be transfered * @param destinatary New owner */ function _transferLand( uint256 estateId, uint256 landId, address destinatary ) internal { require(destinatary != address(0), "You can not transfer LAND to an empty address"); uint256[] storage landIds = estateLandIds[estateId]; mapping(uint256 => uint256) landIndex = estateLandIndex[estateId]; /** * Using 1-based indexing to be able to make this check */ require(landIndex[landId] != 0, "The LAND is not part of the Estate"); uint lastIndexInArray = landIds.length.sub(1); /** * Get the landIndex of this token in the landIds list */ uint indexInArray = landIndex[landId].sub(1); /** * Get the landId at the end of the landIds list */ uint tempTokenId = landIds[lastIndexInArray]; /** * Store the last token in the position previously occupied by landId */ landIndex[tempTokenId] = indexInArray.add(1); landIds[indexInArray] = tempTokenId; /** * Delete the landIds[last element] */ delete landIds[lastIndexInArray]; landIds.length = lastIndexInArray; /** * Drop this landId from both the landIndex and landId list */ landIndex[landId] = 0; /** * Drop this landId Estate */ landIdEstate[landId] = 0; address owner = ownerOf(estateId); _updateEstateLandBalance(owner, address(registry), 1); registry.safeTransferFrom(this, destinatary, landId); emit RemoveLand(estateId, landId, destinatary); } function _isUpdateAuthorized(address operator, uint256 estateId) internal view returns (bool) { address owner = ownerOf(estateId); return isApprovedOrOwner(operator, estateId) || updateOperator[estateId] == operator || updateManager[owner][operator]; } function _isLandUpdateAuthorized( address operator, uint256 estateId, uint256 landId ) internal returns (bool) { return _isUpdateAuthorized(operator, estateId) || registry.updateOperator(landId) == operator; } function _bytesToUint(bytes b) internal pure returns (uint256) { return uint256(_bytesToBytes32(b)); } function _bytesToBytes32(bytes b) internal pure returns (bytes32) { bytes32 out; for (uint i = 0; i < b.length; i++) { out |= bytes32(b[i] & 0xFF) >> i.mul(8); } return out; } function _updateLandData( uint256 estateId, uint256 landId, string data ) internal onlyLandUpdateAuthorized(estateId, landId) { require(landIdEstate[landId] == estateId, "The LAND is not part of the Estate"); int x; int y; (x, y) = registry.decodeTokenId(landId); registry.updateLandData(x, y, data); } /** * @dev Set a new estate land balance minime token * @param _newEstateLandBalance address of the new estate land balance token */ function _setEstateLandBalanceToken(address _newEstateLandBalance) internal { require(_newEstateLandBalance != address(0), "New estateLandBalance should not be zero address"); emit SetEstateLandBalanceToken(estateLandBalance, _newEstateLandBalance); estateLandBalance = IMiniMeToken(_newEstateLandBalance); } /** * @dev Register an account balance * @notice Register land Balance */ function registerBalance() external { require(!registeredBalance[msg.sender], "Register Balance::The user is already registered"); // Get balance of the sender uint256 currentBalance = estateLandBalance.balanceOf(msg.sender); if (currentBalance > 0) { require( estateLandBalance.destroyTokens(msg.sender, currentBalance), "Register Balance::Could not destroy tokens" ); } // Set balance as registered registeredBalance[msg.sender] = true; // Get LAND balance uint256 newBalance = getLANDsSize(msg.sender); // Generate Tokens require( estateLandBalance.generateTokens(msg.sender, newBalance), "Register Balance::Could not generate tokens" ); } /** * @dev Unregister an account balance * @notice Unregister land Balance */ function unregisterBalance() external { require(registeredBalance[msg.sender], "Unregister Balance::The user not registered"); // Set balance as unregistered registeredBalance[msg.sender] = false; // Get balance uint256 currentBalance = estateLandBalance.balanceOf(msg.sender); // Destroy Tokens require( estateLandBalance.destroyTokens(msg.sender, currentBalance), "Unregister Balance::Could not destroy tokens" ); } /** * @dev Update account balances * @param _from account * @param _to account * @param _amount to update */ function _updateEstateLandBalance(address _from, address _to, uint256 _amount) internal { if (registeredBalance[_from]) { estateLandBalance.destroyTokens(_from, _amount); } if (registeredBalance[_to]) { estateLandBalance.generateTokens(_to, _amount); } } /** * @dev Set a estate land balance minime token hardcoded because of the * contraint of the proxy for using an owner * Mainnet: 0x8568f23f343694650370fe5e254b55bfb704a6c7 */ function setEstateLandBalanceToken() external { require(estateLandBalance == address(0), "estateLandBalance was set"); _setEstateLandBalanceToken(address(0x8568f23f343694650370fe5e254b55bfb704a6c7)); } }
File 6 of 6: LANDRegistry
pragma solidity ^0.4.24; // File: contracts/upgradable/ProxyStorage.sol contract ProxyStorage { /** * Current contract to which we are proxing */ address public currentContract; address public proxyOwner; } // File: contracts/upgradable/OwnableStorage.sol contract OwnableStorage { address public owner; constructor() internal { owner = msg.sender; } } // File: erc821/contracts/AssetRegistryStorage.sol contract AssetRegistryStorage { string internal _name; string internal _symbol; string internal _description; /** * Stores the total count of assets managed by this registry */ uint256 internal _count; /** * Stores an array of assets owned by a given account */ mapping(address => uint256[]) internal _assetsOf; /** * Stores the current holder of an asset */ mapping(uint256 => address) internal _holderOf; /** * Stores the index of an asset in the `_assetsOf` array of its holder */ mapping(uint256 => uint256) internal _indexOfAsset; /** * Stores the data associated with an asset */ mapping(uint256 => string) internal _assetData; /** * For a given account, for a given operator, store whether that operator is * allowed to transfer and modify assets on behalf of them. */ mapping(address => mapping(address => bool)) internal _operators; /** * Approval array */ mapping(uint256 => address) internal _approval; } // File: contracts/estate/IEstateRegistry.sol contract IEstateRegistry { function mint(address to, string metadata) external returns (uint256); function ownerOf(uint256 _tokenId) public view returns (address _owner); // from ERC721 // Events event CreateEstate( address indexed _owner, uint256 indexed _estateId, string _data ); event AddLand( uint256 indexed _estateId, uint256 indexed _landId ); event RemoveLand( uint256 indexed _estateId, uint256 indexed _landId, address indexed _destinatary ); event Update( uint256 indexed _assetId, address indexed _holder, address indexed _operator, string _data ); event UpdateOperator( uint256 indexed _estateId, address indexed _operator ); event UpdateManager( address indexed _owner, address indexed _operator, address indexed _caller, bool _approved ); event SetLANDRegistry( address indexed _registry ); event SetEstateLandBalanceToken( address indexed _previousEstateLandBalance, address indexed _newEstateLandBalance ); } // File: contracts/minimeToken/IMinimeToken.sol interface IMiniMeToken { //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) external returns (bool); /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) external returns (bool); /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) external view returns (uint256 balance); event Transfer(address indexed _from, address indexed _to, uint256 _amount); } // File: contracts/land/LANDStorage.sol contract LANDStorage { mapping (address => uint) public latestPing; uint256 constant clearLow = 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000; uint256 constant clearHigh = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff; uint256 constant factor = 0x100000000000000000000000000000000; mapping (address => bool) internal _deprecated_authorizedDeploy; mapping (uint256 => address) public updateOperator; IEstateRegistry public estateRegistry; mapping (address => bool) public authorizedDeploy; mapping(address => mapping(address => bool)) public updateManager; // Land balance minime token IMiniMeToken public landBalance; // Registered balance accounts mapping(address => bool) public registeredBalance; } // File: contracts/Storage.sol contract Storage is ProxyStorage, OwnableStorage, AssetRegistryStorage, LANDStorage { } // File: contracts/upgradable/Ownable.sol contract Ownable is Storage { event OwnerUpdate(address _prevOwner, address _newOwner); modifier onlyOwner { assert(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != owner, "Cannot transfer to yourself"); owner = _newOwner; } } // File: contracts/upgradable/IApplication.sol contract IApplication { function initialize(bytes data) public; } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: erc821/contracts/IERC721Base.sol interface IERC721Base { function totalSupply() external view returns (uint256); // function exists(uint256 assetId) external view returns (bool); function ownerOf(uint256 assetId) external view returns (address); function balanceOf(address holder) external view returns (uint256); function safeTransferFrom(address from, address to, uint256 assetId) external; function safeTransferFrom(address from, address to, uint256 assetId, bytes userData) external; function transferFrom(address from, address to, uint256 assetId) external; function approve(address operator, uint256 assetId) external; function setApprovalForAll(address operator, bool authorized) external; function getApprovedAddress(uint256 assetId) external view returns (address); function isApprovedForAll(address assetHolder, address operator) external view returns (bool); function isAuthorized(address operator, uint256 assetId) external view returns (bool); /** * @dev Deprecated transfer event. Now we use the standard with three parameters * It is only used in the ABI to get old transfer events. Do not remove */ event Transfer( address indexed from, address indexed to, uint256 indexed assetId, address operator, bytes userData, bytes operatorData ); /** * @dev Deprecated transfer event. Now we use the standard with three parameters * It is only used in the ABI to get old transfer events. Do not remove */ event Transfer( address indexed from, address indexed to, uint256 indexed assetId, address operator, bytes userData ); event Transfer( address indexed from, address indexed to, uint256 indexed assetId ); event ApprovalForAll( address indexed holder, address indexed operator, bool authorized ); event Approval( address indexed owner, address indexed operator, uint256 indexed assetId ); } // File: erc821/contracts/IERC721Receiver.sol interface IERC721Receiver { function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _userData ) external returns (bytes4); } // File: erc821/contracts/ERC165.sol interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } // File: erc821/contracts/ERC721Base.sol contract ERC721Base is AssetRegistryStorage, IERC721Base, ERC165 { using SafeMath for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; bytes4 private constant InterfaceId_ERC165 = 0x01ffc9a7; /* * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ bytes4 private constant Old_InterfaceId_ERC721 = 0x7c0633c6; bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ // // Global Getters // /** * @dev Gets the total amount of assets stored by the contract * @return uint256 representing the total amount of assets */ function totalSupply() external view returns (uint256) { return _totalSupply(); } function _totalSupply() internal view returns (uint256) { return _count; } // // Asset-centric getter functions // /** * @dev Queries what address owns an asset. This method does not throw. * In order to check if the asset exists, use the `exists` function or check if the * return value of this call is `0`. * @return uint256 the assetId */ function ownerOf(uint256 assetId) external view returns (address) { return _ownerOf(assetId); } function _ownerOf(uint256 assetId) internal view returns (address) { return _holderOf[assetId]; } // // Holder-centric getter functions // /** * @dev Gets the balance of the specified address * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) external view returns (uint256) { return _balanceOf(owner); } function _balanceOf(address owner) internal view returns (uint256) { return _assetsOf[owner].length; } // // Authorization getters // /** * @dev Query whether an address has been authorized to move any assets on behalf of someone else * @param operator the address that might be authorized * @param assetHolder the address that provided the authorization * @return bool true if the operator has been authorized to move any assets */ function isApprovedForAll(address assetHolder, address operator) external view returns (bool) { return _isApprovedForAll(assetHolder, operator); } function _isApprovedForAll(address assetHolder, address operator) internal view returns (bool) { return _operators[assetHolder][operator]; } /** * @dev Query what address has been particularly authorized to move an asset * @param assetId the asset to be queried for * @return bool true if the asset has been approved by the holder */ function getApproved(uint256 assetId) external view returns (address) { return _getApprovedAddress(assetId); } function getApprovedAddress(uint256 assetId) external view returns (address) { return _getApprovedAddress(assetId); } function _getApprovedAddress(uint256 assetId) internal view returns (address) { return _approval[assetId]; } /** * @dev Query if an operator can move an asset. * @param operator the address that might be authorized * @param assetId the asset that has been `approved` for transfer * @return bool true if the asset has been approved by the holder */ function isAuthorized(address operator, uint256 assetId) external view returns (bool) { return _isAuthorized(operator, assetId); } function _isAuthorized(address operator, uint256 assetId) internal view returns (bool) { require(operator != 0); address owner = _ownerOf(assetId); if (operator == owner) { return true; } return _isApprovedForAll(owner, operator) || _getApprovedAddress(assetId) == operator; } // // Authorization // /** * @dev Authorize a third party operator to manage (send) msg.sender's asset * @param operator address to be approved * @param authorized bool set to true to authorize, false to withdraw authorization */ function setApprovalForAll(address operator, bool authorized) external { return _setApprovalForAll(operator, authorized); } function _setApprovalForAll(address operator, bool authorized) internal { if (authorized) { require(!_isApprovedForAll(msg.sender, operator)); _addAuthorization(operator, msg.sender); } else { require(_isApprovedForAll(msg.sender, operator)); _clearAuthorization(operator, msg.sender); } emit ApprovalForAll(msg.sender, operator, authorized); } /** * @dev Authorize a third party operator to manage one particular asset * @param operator address to be approved * @param assetId asset to approve */ function approve(address operator, uint256 assetId) external { address holder = _ownerOf(assetId); require(msg.sender == holder || _isApprovedForAll(holder, msg.sender)); require(operator != holder); if (_getApprovedAddress(assetId) != operator) { _approval[assetId] = operator; emit Approval(holder, operator, assetId); } } function _addAuthorization(address operator, address holder) private { _operators[holder][operator] = true; } function _clearAuthorization(address operator, address holder) private { _operators[holder][operator] = false; } // // Internal Operations // function _addAssetTo(address to, uint256 assetId) internal { _holderOf[assetId] = to; uint256 length = _balanceOf(to); _assetsOf[to].push(assetId); _indexOfAsset[assetId] = length; _count = _count.add(1); } function _removeAssetFrom(address from, uint256 assetId) internal { uint256 assetIndex = _indexOfAsset[assetId]; uint256 lastAssetIndex = _balanceOf(from).sub(1); uint256 lastAssetId = _assetsOf[from][lastAssetIndex]; _holderOf[assetId] = 0; // Insert the last asset into the position previously occupied by the asset to be removed _assetsOf[from][assetIndex] = lastAssetId; // Resize the array _assetsOf[from][lastAssetIndex] = 0; _assetsOf[from].length--; // Remove the array if no more assets are owned to prevent pollution if (_assetsOf[from].length == 0) { delete _assetsOf[from]; } // Update the index of positions for the asset _indexOfAsset[assetId] = 0; _indexOfAsset[lastAssetId] = assetIndex; _count = _count.sub(1); } function _clearApproval(address holder, uint256 assetId) internal { if (_ownerOf(assetId) == holder && _approval[assetId] != 0) { _approval[assetId] = 0; emit Approval(holder, 0, assetId); } } // // Supply-altering functions // function _generate(uint256 assetId, address beneficiary) internal { require(_holderOf[assetId] == 0); _addAssetTo(beneficiary, assetId); emit Transfer(0, beneficiary, assetId); } function _destroy(uint256 assetId) internal { address holder = _holderOf[assetId]; require(holder != 0); _removeAssetFrom(holder, assetId); emit Transfer(holder, 0, assetId); } // // Transaction related operations // modifier onlyHolder(uint256 assetId) { require(_ownerOf(assetId) == msg.sender); _; } modifier onlyAuthorized(uint256 assetId) { require(_isAuthorized(msg.sender, assetId)); _; } modifier isCurrentOwner(address from, uint256 assetId) { require(_ownerOf(assetId) == from); _; } modifier isDestinataryDefined(address destinatary) { require(destinatary != 0); _; } modifier destinataryIsNotHolder(uint256 assetId, address to) { require(_ownerOf(assetId) != to); _; } /** * @dev Alias of `safeTransferFrom(from, to, assetId, '')` * * @param from address that currently owns an asset * @param to address to receive the ownership of the asset * @param assetId uint256 ID of the asset to be transferred */ function safeTransferFrom(address from, address to, uint256 assetId) external { return _doTransferFrom(from, to, assetId, '', true); } /** * @dev Securely transfers the ownership of a given asset from one address to * another address, calling the method `onNFTReceived` on the target address if * there's code associated with it * * @param from address that currently owns an asset * @param to address to receive the ownership of the asset * @param assetId uint256 ID of the asset to be transferred * @param userData bytes arbitrary user information to attach to this transfer */ function safeTransferFrom(address from, address to, uint256 assetId, bytes userData) external { return _doTransferFrom(from, to, assetId, userData, true); } /** * @dev Transfers the ownership of a given asset from one address to another address * Warning! This function does not attempt to verify that the target address can send * tokens. * * @param from address sending the asset * @param to address to receive the ownership of the asset * @param assetId uint256 ID of the asset to be transferred */ function transferFrom(address from, address to, uint256 assetId) external { return _doTransferFrom(from, to, assetId, '', false); } function _doTransferFrom( address from, address to, uint256 assetId, bytes userData, bool doCheck ) onlyAuthorized(assetId) internal { _moveToken(from, to, assetId, userData, doCheck); } function _moveToken( address from, address to, uint256 assetId, bytes userData, bool doCheck ) isDestinataryDefined(to) destinataryIsNotHolder(assetId, to) isCurrentOwner(from, assetId) private { address holder = _holderOf[assetId]; _clearApproval(holder, assetId); _removeAssetFrom(holder, assetId); _addAssetTo(to, assetId); emit Transfer(holder, to, assetId); if (doCheck && _isContract(to)) { // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) require( IERC721Receiver(to).onERC721Received( msg.sender, holder, assetId, userData ) == ERC721_RECEIVED ); } } /** * Internal function that moves an asset from one holder to another */ /** * @dev Returns `true` if the contract implements `interfaceID` and `interfaceID` is not 0xffffffff, `false` otherwise * @param _interfaceID The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { if (_interfaceID == 0xffffffff) { return false; } return _interfaceID == InterfaceId_ERC165 || _interfaceID == Old_InterfaceId_ERC721 || _interfaceID == InterfaceId_ERC721; } // // Utilities // function _isContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } // File: erc821/contracts/IERC721Enumerable.sol contract IERC721Enumerable { /** * @notice Enumerate active tokens * @dev Throws if `index` >= `totalSupply()`, otherwise SHALL NOT throw. * @param index A counter less than `totalSupply()` * @return The identifier for the `index`th asset, (sort order not * specified) */ // TODO (eordano): Not implemented // function tokenByIndex(uint256 index) public view returns (uint256 _assetId); /** * @notice Count of owners which own at least one asset * Must not throw. * @return A count of the number of owners which own asset */ // TODO (eordano): Not implemented // function countOfOwners() public view returns (uint256 _count); /** * @notice Enumerate owners * @dev Throws if `index` >= `countOfOwners()`, otherwise must not throw. * @param index A counter less than `countOfOwners()` * @return The address of the `index`th owner (sort order not specified) */ // TODO (eordano): Not implemented // function ownerByIndex(uint256 index) public view returns (address owner); /** * @notice Get all tokens of a given address * @dev This is not intended to be used on-chain * @param owner address of the owner to query * @return a list of all assetIds of a user */ function tokensOf(address owner) external view returns (uint256[]); /** * @notice Enumerate tokens assigned to an owner * @dev Throws if `index` >= `balanceOf(owner)` or if * `owner` is the zero address, representing invalid assets. * Otherwise this must not throw. * @param owner An address where we are interested in assets owned by them * @param index A counter less than `balanceOf(owner)` * @return The identifier for the `index`th asset assigned to `owner`, * (sort order not specified) */ function tokenOfOwnerByIndex( address owner, uint256 index ) external view returns (uint256 tokenId); } // File: erc821/contracts/ERC721Enumerable.sol contract ERC721Enumerable is AssetRegistryStorage, IERC721Enumerable { /** * @notice Get all tokens of a given address * @dev This is not intended to be used on-chain * @param owner address of the owner to query * @return a list of all assetIds of a user */ function tokensOf(address owner) external view returns (uint256[]) { return _assetsOf[owner]; } /** * @notice Enumerate tokens assigned to an owner * @dev Throws if `index` >= `balanceOf(owner)` or if * `owner` is the zero address, representing invalid assets. * Otherwise this must not throw. * @param owner An address where we are interested in assets owned by them * @param index A counter less than `balanceOf(owner)` * @return The identifier for the `index`th asset assigned to `owner`, * (sort order not specified) */ function tokenOfOwnerByIndex( address owner, uint256 index ) external view returns (uint256 assetId) { require(index < _assetsOf[owner].length); require(index < (1<<127)); return _assetsOf[owner][index]; } } // File: erc821/contracts/IERC721Metadata.sol contract IERC721Metadata { /** * @notice A descriptive name for a collection of NFTs in this contract */ function name() external view returns (string); /** * @notice An abbreviated name for NFTs in this contract */ function symbol() external view returns (string); /** * @notice A description of what this DAR is used for */ function description() external view returns (string); /** * Stores arbitrary info about a token */ function tokenMetadata(uint256 assetId) external view returns (string); } // File: erc821/contracts/ERC721Metadata.sol contract ERC721Metadata is AssetRegistryStorage, IERC721Metadata { function name() external view returns (string) { return _name; } function symbol() external view returns (string) { return _symbol; } function description() external view returns (string) { return _description; } function tokenMetadata(uint256 assetId) external view returns (string) { return _assetData[assetId]; } function _update(uint256 assetId, string data) internal { _assetData[assetId] = data; } } // File: erc821/contracts/FullAssetRegistry.sol contract FullAssetRegistry is ERC721Base, ERC721Enumerable, ERC721Metadata { constructor() public { } /** * @dev Method to check if an asset identified by the given id exists under this DAR. * @return uint256 the assetId */ function exists(uint256 assetId) external view returns (bool) { return _exists(assetId); } function _exists(uint256 assetId) internal view returns (bool) { return _holderOf[assetId] != 0; } function decimals() external pure returns (uint256) { return 0; } } // File: contracts/land/ILANDRegistry.sol interface ILANDRegistry { // LAND can be assigned by the owner function assignNewParcel(int x, int y, address beneficiary) external; function assignMultipleParcels(int[] x, int[] y, address beneficiary) external; // After one year, LAND can be claimed from an inactive public key function ping() external; // LAND-centric getters function encodeTokenId(int x, int y) external pure returns (uint256); function decodeTokenId(uint value) external pure returns (int, int); function exists(int x, int y) external view returns (bool); function ownerOfLand(int x, int y) external view returns (address); function ownerOfLandMany(int[] x, int[] y) external view returns (address[]); function landOf(address owner) external view returns (int[], int[]); function landData(int x, int y) external view returns (string); // Transfer LAND function transferLand(int x, int y, address to) external; function transferManyLand(int[] x, int[] y, address to) external; // Update LAND function updateLandData(int x, int y, string data) external; function updateManyLandData(int[] x, int[] y, string data) external; // Authorize an updateManager to manage parcel data function setUpdateManager(address _owner, address _operator, bool _approved) external; // Events event Update( uint256 indexed assetId, address indexed holder, address indexed operator, string data ); event UpdateOperator( uint256 indexed assetId, address indexed operator ); event UpdateManager( address indexed _owner, address indexed _operator, address indexed _caller, bool _approved ); event DeployAuthorized( address indexed _caller, address indexed _deployer ); event DeployForbidden( address indexed _caller, address indexed _deployer ); event SetLandBalanceToken( address indexed _previousLandBalance, address indexed _newLandBalance ); } // File: contracts/metadata/IMetadataHolder.sol contract IMetadataHolder is ERC165 { function getMetadata(uint256 /* assetId */) external view returns (string); } // File: contracts/land/LANDRegistry.sol /* solium-disable function-order */ contract LANDRegistry is Storage, Ownable, FullAssetRegistry, ILANDRegistry { bytes4 constant public GET_METADATA = bytes4(keccak256("getMetadata(uint256)")); function initialize(bytes) external { _name = "Decentraland LAND"; _symbol = "LAND"; _description = "Contract that stores the Decentraland LAND registry"; } modifier onlyProxyOwner() { require(msg.sender == proxyOwner, "This function can only be called by the proxy owner"); _; } modifier onlyDeployer() { require( msg.sender == proxyOwner || authorizedDeploy[msg.sender], "This function can only be called by an authorized deployer" ); _; } modifier onlyOwnerOf(uint256 assetId) { require( msg.sender == _ownerOf(assetId), "This function can only be called by the owner of the asset" ); _; } modifier onlyUpdateAuthorized(uint256 tokenId) { require( msg.sender == _ownerOf(tokenId) || _isAuthorized(msg.sender, tokenId) || _isUpdateAuthorized(msg.sender, tokenId), "msg.sender is not authorized to update" ); _; } modifier canSetUpdateOperator(uint256 tokenId) { address owner = _ownerOf(tokenId); require( _isAuthorized(msg.sender, tokenId) || updateManager[owner][msg.sender], "unauthorized user" ); _; } // // Authorization // function isUpdateAuthorized(address operator, uint256 assetId) external view returns (bool) { return _isUpdateAuthorized(operator, assetId); } function _isUpdateAuthorized(address operator, uint256 assetId) internal view returns (bool) { address owner = _ownerOf(assetId); return owner == operator || updateOperator[assetId] == operator || updateManager[owner][operator]; } function authorizeDeploy(address beneficiary) external onlyProxyOwner { require(beneficiary != address(0), "invalid address"); require(authorizedDeploy[beneficiary] == false, "address is already authorized"); authorizedDeploy[beneficiary] = true; emit DeployAuthorized(msg.sender, beneficiary); } function forbidDeploy(address beneficiary) external onlyProxyOwner { require(beneficiary != address(0), "invalid address"); require(authorizedDeploy[beneficiary], "address is already forbidden"); authorizedDeploy[beneficiary] = false; emit DeployForbidden(msg.sender, beneficiary); } // // LAND Create // function assignNewParcel(int x, int y, address beneficiary) external onlyDeployer { _generate(_encodeTokenId(x, y), beneficiary); _updateLandBalance(address(0), beneficiary); } function assignMultipleParcels(int[] x, int[] y, address beneficiary) external onlyDeployer { for (uint i = 0; i < x.length; i++) { _generate(_encodeTokenId(x[i], y[i]), beneficiary); _updateLandBalance(address(0), beneficiary); } } // // Inactive keys after 1 year lose ownership // function ping() external { // solium-disable-next-line security/no-block-members latestPing[msg.sender] = block.timestamp; } function setLatestToNow(address user) external { require(msg.sender == proxyOwner || _isApprovedForAll(user, msg.sender), "Unauthorized user"); // solium-disable-next-line security/no-block-members latestPing[user] = block.timestamp; } // // LAND Getters // function encodeTokenId(int x, int y) external pure returns (uint) { return _encodeTokenId(x, y); } function _encodeTokenId(int x, int y) internal pure returns (uint result) { require( -1000000 < x && x < 1000000 && -1000000 < y && y < 1000000, "The coordinates should be inside bounds" ); return _unsafeEncodeTokenId(x, y); } function _unsafeEncodeTokenId(int x, int y) internal pure returns (uint) { return ((uint(x) * factor) & clearLow) | (uint(y) & clearHigh); } function decodeTokenId(uint value) external pure returns (int, int) { return _decodeTokenId(value); } function _unsafeDecodeTokenId(uint value) internal pure returns (int x, int y) { x = expandNegative128BitCast((value & clearLow) >> 128); y = expandNegative128BitCast(value & clearHigh); } function _decodeTokenId(uint value) internal pure returns (int x, int y) { (x, y) = _unsafeDecodeTokenId(value); require( -1000000 < x && x < 1000000 && -1000000 < y && y < 1000000, "The coordinates should be inside bounds" ); } function expandNegative128BitCast(uint value) internal pure returns (int) { if (value & (1<<127) != 0) { return int(value | clearLow); } return int(value); } function exists(int x, int y) external view returns (bool) { return _exists(x, y); } function _exists(int x, int y) internal view returns (bool) { return _exists(_encodeTokenId(x, y)); } function ownerOfLand(int x, int y) external view returns (address) { return _ownerOfLand(x, y); } function _ownerOfLand(int x, int y) internal view returns (address) { return _ownerOf(_encodeTokenId(x, y)); } function ownerOfLandMany(int[] x, int[] y) external view returns (address[]) { require(x.length > 0, "You should supply at least one coordinate"); require(x.length == y.length, "The coordinates should have the same length"); address[] memory addrs = new address[](x.length); for (uint i = 0; i < x.length; i++) { addrs[i] = _ownerOfLand(x[i], y[i]); } return addrs; } function landOf(address owner) external view returns (int[], int[]) { uint256 len = _assetsOf[owner].length; int[] memory x = new int[](len); int[] memory y = new int[](len); int assetX; int assetY; for (uint i = 0; i < len; i++) { (assetX, assetY) = _decodeTokenId(_assetsOf[owner][i]); x[i] = assetX; y[i] = assetY; } return (x, y); } function tokenMetadata(uint256 assetId) external view returns (string) { return _tokenMetadata(assetId); } function _tokenMetadata(uint256 assetId) internal view returns (string) { address _owner = _ownerOf(assetId); if (_isContract(_owner) && _owner != address(estateRegistry)) { if ((ERC165(_owner)).supportsInterface(GET_METADATA)) { return IMetadataHolder(_owner).getMetadata(assetId); } } return _assetData[assetId]; } function landData(int x, int y) external view returns (string) { return _tokenMetadata(_encodeTokenId(x, y)); } // // LAND Transfer // function transferFrom(address from, address to, uint256 assetId) external { require(to != address(estateRegistry), "EstateRegistry unsafe transfers are not allowed"); return _doTransferFrom( from, to, assetId, "", false ); } function transferLand(int x, int y, address to) external { uint256 tokenId = _encodeTokenId(x, y); _doTransferFrom( _ownerOf(tokenId), to, tokenId, "", true ); } function transferManyLand(int[] x, int[] y, address to) external { require(x.length > 0, "You should supply at least one coordinate"); require(x.length == y.length, "The coordinates should have the same length"); for (uint i = 0; i < x.length; i++) { uint256 tokenId = _encodeTokenId(x[i], y[i]); _doTransferFrom( _ownerOf(tokenId), to, tokenId, "", true ); } } function transferLandToEstate(int x, int y, uint256 estateId) external { require( estateRegistry.ownerOf(estateId) == msg.sender, "You must own the Estate you want to transfer to" ); uint256 tokenId = _encodeTokenId(x, y); _doTransferFrom( _ownerOf(tokenId), address(estateRegistry), tokenId, toBytes(estateId), true ); } function transferManyLandToEstate(int[] x, int[] y, uint256 estateId) external { require(x.length > 0, "You should supply at least one coordinate"); require(x.length == y.length, "The coordinates should have the same length"); require( estateRegistry.ownerOf(estateId) == msg.sender, "You must own the Estate you want to transfer to" ); for (uint i = 0; i < x.length; i++) { uint256 tokenId = _encodeTokenId(x[i], y[i]); _doTransferFrom( _ownerOf(tokenId), address(estateRegistry), tokenId, toBytes(estateId), true ); } } /** * @notice Set LAND updateOperator * @param assetId - LAND id * @param operator - address of the account to be set as the updateOperator */ function setUpdateOperator( uint256 assetId, address operator ) public canSetUpdateOperator(assetId) { updateOperator[assetId] = operator; emit UpdateOperator(assetId, operator); } /** * @notice Set many LAND updateOperator * @param _assetIds - LAND ids * @param _operator - address of the account to be set as the updateOperator */ function setManyUpdateOperator( uint256[] _assetIds, address _operator ) public { for (uint i = 0; i < _assetIds.length; i++) { setUpdateOperator(_assetIds[i], _operator); } } /** * @dev Set an updateManager for an account * @param _owner - address of the account to set the updateManager * @param _operator - address of the account to be set as the updateManager * @param _approved - bool whether the address will be approved or not */ function setUpdateManager(address _owner, address _operator, bool _approved) external { require(_operator != msg.sender, "The operator should be different from owner"); require( _owner == msg.sender || _isApprovedForAll(_owner, msg.sender), "Unauthorized user" ); updateManager[_owner][_operator] = _approved; emit UpdateManager( _owner, _operator, msg.sender, _approved ); } // // Estate generation // event EstateRegistrySet(address indexed registry); function setEstateRegistry(address registry) external onlyProxyOwner { estateRegistry = IEstateRegistry(registry); emit EstateRegistrySet(registry); } function createEstate(int[] x, int[] y, address beneficiary) external returns (uint256) { // solium-disable-next-line arg-overflow return _createEstate(x, y, beneficiary, ""); } function createEstateWithMetadata( int[] x, int[] y, address beneficiary, string metadata ) external returns (uint256) { // solium-disable-next-line arg-overflow return _createEstate(x, y, beneficiary, metadata); } function _createEstate( int[] x, int[] y, address beneficiary, string metadata ) internal returns (uint256) { require(x.length > 0, "You should supply at least one coordinate"); require(x.length == y.length, "The coordinates should have the same length"); require(address(estateRegistry) != 0, "The Estate registry should be set"); uint256 estateTokenId = estateRegistry.mint(beneficiary, metadata); bytes memory estateTokenIdBytes = toBytes(estateTokenId); for (uint i = 0; i < x.length; i++) { uint256 tokenId = _encodeTokenId(x[i], y[i]); _doTransferFrom( _ownerOf(tokenId), address(estateRegistry), tokenId, estateTokenIdBytes, true ); } return estateTokenId; } function toBytes(uint256 x) internal pure returns (bytes b) { b = new bytes(32); // solium-disable-next-line security/no-inline-assembly assembly { mstore(add(b, 32), x) } } // // LAND Update // function updateLandData( int x, int y, string data ) external { return _updateLandData(x, y, data); } function _updateLandData( int x, int y, string data ) internal onlyUpdateAuthorized(_encodeTokenId(x, y)) { uint256 assetId = _encodeTokenId(x, y); address owner = _holderOf[assetId]; _update(assetId, data); emit Update( assetId, owner, msg.sender, data ); } function updateManyLandData(int[] x, int[] y, string data) external { require(x.length > 0, "You should supply at least one coordinate"); require(x.length == y.length, "The coordinates should have the same length"); for (uint i = 0; i < x.length; i++) { _updateLandData(x[i], y[i], data); } } /** * @dev Set a new land balance minime token * @notice Set new land balance token: `_newLandBalance` * @param _newLandBalance address of the new land balance token */ function setLandBalanceToken(address _newLandBalance) onlyProxyOwner external { require(_newLandBalance != address(0), "New landBalance should not be zero address"); emit SetLandBalanceToken(landBalance, _newLandBalance); landBalance = IMiniMeToken(_newLandBalance); } /** * @dev Register an account balance * @notice Register land Balance */ function registerBalance() external { require(!registeredBalance[msg.sender], "Register Balance::The user is already registered"); // Get balance of the sender uint256 currentBalance = landBalance.balanceOf(msg.sender); if (currentBalance > 0) { require( landBalance.destroyTokens(msg.sender, currentBalance), "Register Balance::Could not destroy tokens" ); } // Set balance as registered registeredBalance[msg.sender] = true; // Get LAND balance uint256 newBalance = _balanceOf(msg.sender); // Generate Tokens require( landBalance.generateTokens(msg.sender, newBalance), "Register Balance::Could not generate tokens" ); } /** * @dev Unregister an account balance * @notice Unregister land Balance */ function unregisterBalance() external { require(registeredBalance[msg.sender], "Unregister Balance::The user not registered"); // Set balance as unregistered registeredBalance[msg.sender] = false; // Get balance uint256 currentBalance = landBalance.balanceOf(msg.sender); // Destroy Tokens require( landBalance.destroyTokens(msg.sender, currentBalance), "Unregister Balance::Could not destroy tokens" ); } function _doTransferFrom( address from, address to, uint256 assetId, bytes userData, bool doCheck ) internal { updateOperator[assetId] = address(0); _updateLandBalance(from, to); super._doTransferFrom( from, to, assetId, userData, doCheck ); } function _isContract(address addr) internal view returns (bool) { uint size; // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } /** * @dev Update account balances * @param _from account * @param _to account */ function _updateLandBalance(address _from, address _to) internal { if (registeredBalance[_from]) { landBalance.destroyTokens(_from, 1); } if (registeredBalance[_to]) { landBalance.generateTokens(_to, 1); } } }