Overview
ETH Balance
0 ETH
Eth Value
$0.00More Info
Private Name Tags
ContractCreator
TokenTracker
| Transaction Hash |
Method
|
Block
|
From
|
|
To
|
||||
|---|---|---|---|---|---|---|---|---|---|
Latest 1 internal transaction
Advanced mode:
| Parent Transaction Hash | Method | Block |
From
|
|
To
|
||
|---|---|---|---|---|---|---|---|
| 0x3d602d80 | 23683034 | 124 days ago | Contract Creation | 0 ETH |
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions
Loading...
Loading
Minimal Proxy Contract for 0x7a9e3150b1d046e6957a5cc4c9ce9373a09d3e99
Contract Name:
TTTrackerTokenV2
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 200 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: AGPL v3
pragma solidity ^0.8.20;
import {ITTTrackerTokenV2} from "../interfaces/ITTTrackerTokenV2.sol";
import {TokenTableUnlockerV2} from "./TokenTableUnlockerV2.sol";
import {ITTFutureTokenV2} from "../interfaces/ITTFutureTokenV2.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/**
* @title TTTrackerTokenV2
* @author Jack Xu @ EthSign
* @dev An ERC20 token that represents the number of currently claimable
* unlocked tokens. This token can be added into the investor's wallet,
* making it easy for them to check on this information without having to
* go through TokenTable's website.
*/
// solhint-disable ordering
// solhint-disable no-unused-vars
contract TTTrackerTokenV2 is ITTTrackerTokenV2, IERC20Metadata, Initializable {
TokenTableUnlockerV2 public ttuInstance;
constructor() {
if (block.chainid != 33133 && block.chainid != 300 && block.chainid != 324) {
_disableInitializers();
}
}
function initialize(address ttuInstance_) external override initializer {
ttuInstance = TokenTableUnlockerV2(ttuInstance_);
}
function name() external view returns (string memory) {
return string.concat("Tracker ", IERC20Metadata(ttuInstance.getProjectToken()).name());
}
function symbol() external view returns (string memory) {
return string.concat("T-", IERC20Metadata(ttuInstance.getProjectToken()).symbol());
}
function decimals() external view returns (uint8) {
return IERC20Metadata(ttuInstance.getProjectToken()).decimals();
}
/**
* @dev Total number of tokens deposited into the unlocker awaiting claim.
*/
function totalSupply() external view returns (uint256) {
return IERC20Metadata(ttuInstance.getProjectToken()).balanceOf(address(ttuInstance));
}
/**
* @dev Number of currently claimable tokens of the given address.
*/
function balanceOf(address account) external view returns (uint256) {
uint256 amountClaimable;
ITTFutureTokenV2 nftInstance = ttuInstance.futureToken();
uint256[] memory tokenIdsOfOwner = nftInstance.tokensOfOwner(account);
for (uint256 i = 0; i < tokenIdsOfOwner.length; i++) {
(uint256 deltaAmountClaimable,) = ttuInstance.calculateAmountClaimable(tokenIdsOfOwner[i]);
amountClaimable += deltaAmountClaimable;
// include pending amount claimable for cancelled actuals
amountClaimable += ttuInstance.pendingAmountClaimableForCancelledActuals(tokenIdsOfOwner[i]);
}
return amountClaimable;
}
/**
* @dev This operation is not allowed/implemented on purpose.
*/
function transfer(address, uint256) external pure returns (bool) {
return false;
}
/**
* @dev This operation is not allowed/implemented on purpose.
*/
function allowance(address, address) external pure returns (uint256) {
return 0;
}
/**
* @dev This operation is not allowed/implemented on purpose.
*/
function approve(address, uint256) external pure returns (bool) {
return false;
}
/**
* @dev This operation is not allowed/implemented on purpose.
*/
function transferFrom(address, address, uint256) external pure returns (bool) {
return false;
}
function version() external pure returns (string memory) {
return "2.5.0";
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../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.
*
* The initial owner is set to the address provided by the deployer. 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 {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling 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 {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../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;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}// SPDX-License-Identifier: AGPL v3
pragma solidity ^0.8.28;
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {Actual, Preset} from "../interfaces/TokenTableUnlockerV2DataModels.sol";
import {ITokenTableUnlockerV2, IOwnable} from "../interfaces/ITokenTableUnlockerV2.sol";
import {ITTHook} from "../interfaces/ITTHook.sol";
import {ITTFutureTokenV2} from "./TTFutureTokenV2.sol";
import {TTUProjectTokenStorage} from "./TTUProjectTokenStorage.sol";
import {ITTUDeployer} from "../interfaces/ITTUDeployer.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IDelegateRegistry} from "../libraries/IDelegateRegistry.sol";
// solhint-disable var-name-mixedcase
// solhint-disable no-inline-assembly
// solhint-disable const-name-snakecase
// solhint-disable private-vars-leading-underscore
contract TokenTableUnlockerV2 is
OwnableUpgradeable,
TTUProjectTokenStorage,
ITokenTableUnlockerV2,
ReentrancyGuardUpgradeable
{
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
/// @custom:storage-location erc7201:ethsign.tokentable.TokenTableUnlockerV2
struct TokenTableUnlockerV2Storage {
ITTUDeployer deployer;
ITTFutureTokenV2 futureToken;
ITTHook hook;
bool isCreateable;
bool isCancelable;
bool isHookable;
bool isWithdrawable;
bool currentChainSupportsExternalDelegateRegistry;
mapping(bytes32 => Preset) _presets;
mapping(uint256 => Actual) actuals;
mapping(uint256 => uint256) pendingAmountClaimableForCancelledActuals;
EnumerableSet.AddressSet claimingDelegates;
}
// keccak256(abi.encode(uint256(keccak256("ethsign.tokentable.TokenTableUnlockerV2")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant TokenTableUnlockerV2StorageLocation =
0xf4418c544e5a1a0f1b27d83456fa5dee959057d761996477014154ff58940400;
uint256 public constant BIPS_PRECISION = 10 ** 4; // down to 0.01%
uint256 public constant TOKEN_PRECISION = 10 ** 5;
uint256 public constant DURATION_PRECISION = 10 ** 5;
IDelegateRegistry public constant externalDelegateRegistry =
IDelegateRegistry(0x00000000000000447e69651d841bD8D104Bed493);
function _getTokenTableUnlockerV2Storage() internal pure returns (TokenTableUnlockerV2Storage storage $) {
assembly {
$.slot := TokenTableUnlockerV2StorageLocation
}
}
// solhint-disable-next-line ordering
constructor() {
if (block.chainid != 33133 && block.chainid != 300 && block.chainid != 324) {
_disableInitializers();
}
}
function initialize(
address projectToken,
address futureToken_,
address deployer_,
bool isCancelable_,
bool isHookable_,
bool isWithdrawable_
) external override initializer {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
__Ownable_init_unchained(_msgSender());
_initializeSE(projectToken);
$.futureToken = ITTFutureTokenV2(futureToken_);
$.deployer = ITTUDeployer(deployer_);
__ReentrancyGuard_init_unchained();
$.isCreateable = true;
$.isCancelable = isCancelable_;
$.isHookable = isHookable_;
$.isWithdrawable = isWithdrawable_;
}
// solhint-disable-next-line ordering
function createPresets(bytes32[] calldata presetIds, Preset[] calldata presets, uint256 batchId, bytes calldata)
external
virtual
override
onlyOwner
{
for (uint256 i = 0; i < presetIds.length; i++) {
_createPreset(presetIds[i], presets[i], batchId);
}
_callHook(_msgData());
}
function createActuals(
address[] calldata recipients,
Actual[] calldata actuals_,
uint256[] calldata recipientIds,
uint256 batchId,
bytes calldata
) external virtual override onlyOwner {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
if (!$.isCreateable) revert NotPermissioned();
for (uint256 i = 0; i < recipients.length; i++) {
_createActual(recipients[i], actuals_[i], recipientIds[i], batchId);
}
_callHook(_msgData());
}
function withdrawDeposit(uint256 amount, bytes calldata) external virtual override onlyOwner {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
if (!$.isWithdrawable && !$.deployer.consumeEmergencyWithdrawRequest()) {
revert NotPermissioned();
}
IERC20(getProjectToken()).safeTransfer(_msgSender(), amount);
emit TokensWithdrawn(_msgSender(), amount);
_callHook(_msgData());
}
function claim(uint256[] calldata actualIds, address[] calldata claimTos, uint256 batchId, bytes calldata)
external
virtual
override
nonReentrant
{
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
for (uint256 i = 0; i < actualIds.length; i++) {
if ($.futureToken.ownerOf(actualIds[i]) != _msgSender()) {
revert NotPermissioned();
}
_claim(actualIds[i], claimTos[i], batchId);
}
_callHook(_msgData());
}
function delegateClaim(uint256[] calldata actualIds, uint256 batchId, bytes calldata)
external
virtual
override
nonReentrant
{
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
bool callerIsClaimingDelegate = $.claimingDelegates.contains(_msgSender());
for (uint256 i = 0; i < actualIds.length; i++) {
if (
!callerIsClaimingDelegate
&& !(
$.currentChainSupportsExternalDelegateRegistry
&& externalDelegateRegistry.checkDelegateForContract(
_msgSender(), $.futureToken.ownerOf(actualIds[i]), address(this), this.delegateClaim.selector
)
)
) {
revert NotPermissioned();
}
_claim(actualIds[i], address(0), batchId);
}
_callHook(_msgData());
}
function cancel(
uint256[] calldata actualIds,
bool[] calldata shouldWipeClaimableBalance,
uint256 batchId,
bytes calldata
) external virtual override onlyOwner returns (uint256[] memory pendingAmountClaimables) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
if (!$.isCancelable) revert NotPermissioned();
pendingAmountClaimables = new uint256[](actualIds.length);
for (uint256 i = 0; i < actualIds.length; i++) {
uint256 actualId = actualIds[i];
(uint256 deltaAmountClaimable,) = calculateAmountClaimable(actualId);
if (!shouldWipeClaimableBalance[i]) {
$.pendingAmountClaimableForCancelledActuals[actualId] += deltaAmountClaimable;
}
pendingAmountClaimables[i] = deltaAmountClaimable;
emit ActualCancelled(actualId, deltaAmountClaimable, shouldWipeClaimableBalance[i], batchId);
delete $.actuals[actualId];
}
_callHook(_msgData());
}
function setHook(ITTHook hook_) external virtual override onlyOwner {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
if (!$.isHookable) revert NotPermissioned();
$.hook = hook_;
_callHook(_msgData());
}
function setClaimingDelegate(address delegate, bool status) external virtual override onlyOwner {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
if (status) {
$.claimingDelegates.add(delegate);
} else {
$.claimingDelegates.remove(delegate);
}
emit ClaimingDelegateSet(delegate, status);
}
function setCurrentChainSupportsExternalDelegateRegistry(bool status) external override onlyOwner {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
$.currentChainSupportsExternalDelegateRegistry = status;
}
function disableCreate() external virtual override onlyOwner {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
$.isCreateable = false;
emit CreateDisabled();
_callHook(_msgData());
}
function disableCancel() external virtual override onlyOwner {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
$.isCancelable = false;
emit CancelDisabled();
_callHook(_msgData());
}
function disableHook() external virtual override onlyOwner {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
$.isHookable = false;
emit HookDisabled();
$.hook = ITTHook(address(0));
}
function disableWithdraw() external virtual override onlyOwner {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
$.isWithdrawable = false;
emit WithdrawDisabled();
_callHook(_msgData());
}
function setEmergencyWithdrawRequestStatus(bool status) external virtual override onlyOwner {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
require(!$.isWithdrawable, AlreadyWithdrawable());
$.deployer.setEmergencyWithdrawRequestStatus(status);
}
function transferOwnership(address newOwner) public override(IOwnable, OwnableUpgradeable) {
OwnableUpgradeable.transferOwnership(newOwner);
}
function renounceOwnership() public override(IOwnable, OwnableUpgradeable) {
OwnableUpgradeable.renounceOwnership();
}
function owner() public view override(IOwnable, OwnableUpgradeable) returns (address) {
return OwnableUpgradeable.owner();
}
function _createPreset(bytes32 presetId, Preset memory preset, uint256 batchId) internal virtual {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
if (!_presetIsEmpty($._presets[presetId])) revert PresetExists();
if (!_presetHasValidFormat(preset) || presetId == 0) {
revert InvalidPresetFormat();
}
$._presets[presetId] = preset;
emit PresetCreated(presetId, batchId);
}
function _createActual(address recipient, Actual memory actual, uint256 recipientId, uint256 batchId)
internal
virtual
{
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
uint256 actualId = $.futureToken.safeMint(recipient);
Preset storage preset = $._presets[actual.presetId];
if (_presetIsEmpty(preset)) revert PresetDoesNotExist();
if (actual.amountClaimed >= actual.totalAmount) {
revert InvalidSkipAmount();
}
$.actuals[actualId] = actual;
emit ActualCreated(actual.presetId, actualId, recipient, recipientId, batchId);
}
function _claim(uint256 actualId, address overrideRecipient, uint256 batchId) internal virtual {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
uint256 deltaAmountClaimable;
address recipient;
if (overrideRecipient == address(0)) {
recipient = $.futureToken.ownerOf(actualId);
} else {
recipient = overrideRecipient;
}
deltaAmountClaimable = $.pendingAmountClaimableForCancelledActuals[actualId];
if (deltaAmountClaimable != 0) {
$.pendingAmountClaimableForCancelledActuals[actualId] = 0;
IERC20(getProjectToken()).safeTransfer(recipient, deltaAmountClaimable);
} else {
deltaAmountClaimable = _updateActualAndSend(actualId, recipient);
}
uint256 feesCharged = _chargeFees(deltaAmountClaimable);
emit TokensClaimed(actualId, _msgSender(), recipient, deltaAmountClaimable, feesCharged, batchId);
}
function _callHook(bytes calldata context) internal virtual {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
if (address($.hook) == address(0)) return;
$.hook.didCall(context, _msgSender());
}
function deployer() external view virtual override returns (ITTUDeployer) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
return $.deployer;
}
function futureToken() external view virtual override returns (ITTFutureTokenV2) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
return $.futureToken;
}
function hook() external view virtual override returns (ITTHook) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
return $.hook;
}
function claimingDelegates() external view virtual override returns (address[] memory) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
return $.claimingDelegates.values();
}
function isCreateable() external view virtual override returns (bool) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
return $.isCreateable;
}
function isCancelable() external view virtual override returns (bool) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
return $.isCancelable;
}
function isHookable() external view virtual override returns (bool) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
return $.isHookable;
}
function isWithdrawable() external view virtual override returns (bool) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
return $.isWithdrawable;
}
function pendingAmountClaimableForCancelledActuals(uint256 actualId)
external
view
virtual
override
returns (uint256)
{
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
return $.pendingAmountClaimableForCancelledActuals[actualId];
}
function getEncodedPreset(bytes32 presetId) external view virtual override returns (bytes memory) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
Preset memory preset = $._presets[presetId];
return abi.encode(
preset.linearStartTimestampsRelative,
preset.linearEndTimestampRelative,
preset.linearBips,
preset.numOfUnlocksForEachLinear,
preset.stream
);
}
function actuals(uint256 actualId) external view virtual override returns (Actual memory) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
return $.actuals[actualId];
}
function currentChainSupportsExternalDelegateRegistry() public view override returns (bool) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
return $.currentChainSupportsExternalDelegateRegistry;
}
function calculateAmountClaimable(uint256 actualId)
public
view
virtual
override
returns (uint256 deltaAmountClaimable, uint256 updatedAmountClaimed)
{
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
Actual memory actual = $.actuals[actualId];
// check if actual is cancelled
if (actual.presetId != 0) {
(deltaAmountClaimable, updatedAmountClaimed) = simulateAmountClaimable(actualId, block.timestamp);
}
}
function simulateAmountClaimable(uint256 actualId, uint256 claimTimestampAbsolute)
public
view
virtual
override
returns (uint256 deltaAmountClaimable, uint256 updatedAmountClaimed)
{
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
Actual memory actual = $.actuals[actualId];
if (actual.presetId == 0) revert ActualDoesNotExist();
Preset memory preset = $._presets[actual.presetId];
uint256 i;
uint256 latestIncompleteLinearIndex;
if (claimTimestampAbsolute < actual.startTimestampAbsolute + preset.linearStartTimestampsRelative[0]) {
return (0, actual.amountClaimed);
}
uint256 claimTimestampRelative = claimTimestampAbsolute - actual.startTimestampAbsolute;
for (i = 0; i < preset.linearStartTimestampsRelative.length; i++) {
if (preset.linearStartTimestampsRelative[i] <= claimTimestampRelative) {
latestIncompleteLinearIndex = i;
} else {
break;
}
}
// 1. calculate completed linear index claimables in bips
for (i = 0; i < latestIncompleteLinearIndex; i++) {
updatedAmountClaimed += preset.linearBips[i] * TOKEN_PRECISION;
}
// 2. calculate incomplete linear index claimable in bips
uint256 latestIncompleteLinearDuration;
if (latestIncompleteLinearIndex == preset.linearStartTimestampsRelative.length - 1) {
latestIncompleteLinearDuration = preset.linearEndTimestampRelative
- preset.linearStartTimestampsRelative[preset.linearStartTimestampsRelative.length - 1];
} else {
latestIncompleteLinearDuration = preset.linearStartTimestampsRelative[latestIncompleteLinearIndex + 1]
- preset.linearStartTimestampsRelative[latestIncompleteLinearIndex];
}
if (latestIncompleteLinearDuration == 0) {
latestIncompleteLinearDuration = 1;
}
uint256 numOfUnlocksForIncompleteLinear = preset.stream
? latestIncompleteLinearDuration
: preset.numOfUnlocksForEachLinear[latestIncompleteLinearIndex];
uint256 latestIncompleteLinearIntervalForEachUnlock =
(latestIncompleteLinearDuration * DURATION_PRECISION) / numOfUnlocksForIncompleteLinear;
uint256 latestIncompleteLinearClaimableTimestampRelative =
claimTimestampRelative - preset.linearStartTimestampsRelative[latestIncompleteLinearIndex];
uint256 numOfClaimableUnlocksInIncompleteLinear = (
latestIncompleteLinearClaimableTimestampRelative * DURATION_PRECISION
) / latestIncompleteLinearIntervalForEachUnlock;
updatedAmountClaimed += (
preset.linearBips[latestIncompleteLinearIndex] * TOKEN_PRECISION * numOfClaimableUnlocksInIncompleteLinear
) / numOfUnlocksForIncompleteLinear;
updatedAmountClaimed = (updatedAmountClaimed * actual.totalAmount) / (BIPS_PRECISION * TOKEN_PRECISION);
if (updatedAmountClaimed > actual.totalAmount) {
updatedAmountClaimed = actual.totalAmount;
}
if (actual.amountClaimed > updatedAmountClaimed) {
deltaAmountClaimable = 0;
updatedAmountClaimed = actual.amountClaimed;
} else {
deltaAmountClaimable = updatedAmountClaimed - actual.amountClaimed;
}
}
function version() public pure virtual override returns (string memory) {
return "2.7.0";
}
function _updateActualAndSend(uint256 actualId, address recipient)
internal
virtual
returns (uint256 deltaAmountClaimable_)
{
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
(uint256 deltaAmountClaimable, uint256 updatedAmountClaimed) = calculateAmountClaimable(actualId);
Actual storage actual = $.actuals[actualId];
actual.amountClaimed = updatedAmountClaimed;
IERC20(getProjectToken()).safeTransfer(recipient, deltaAmountClaimable);
deltaAmountClaimable_ = deltaAmountClaimable;
}
function _chargeFees(uint256 amount) internal virtual returns (uint256 feesCollected) {
TokenTableUnlockerV2Storage storage $ = _getTokenTableUnlockerV2Storage();
if (address($.deployer) != address(0) && address($.deployer.feeCollector()) != address(0)) {
feesCollected = $.deployer.feeCollector().getFee(address(this), amount);
if (feesCollected > 0) {
IERC20(getProjectToken()).safeTransfer($.deployer.feeCollector().owner(), feesCollected);
}
}
}
function _presetIsEmpty(Preset storage preset) internal view returns (bool) {
return preset.linearBips.length * preset.linearStartTimestampsRelative.length
* preset.numOfUnlocksForEachLinear.length * preset.linearEndTimestampRelative == 0;
}
function _presetHasValidFormat(Preset memory preset) internal pure returns (bool) {
uint256 total;
uint256 i;
for (i = 0; i < preset.linearBips.length; i++) {
total += preset.linearBips[i];
}
if (
!(
(total == BIPS_PRECISION) && (preset.linearBips.length == preset.linearStartTimestampsRelative.length)
&& (
preset.linearStartTimestampsRelative[preset.linearStartTimestampsRelative.length - 1]
< preset.linearEndTimestampRelative
) && (preset.numOfUnlocksForEachLinear.length == preset.linearStartTimestampsRelative.length)
)
) {
return false;
}
i = 1;
while (true) {
uint256 startTimestampForSegment;
uint256 endTimestampForSegment;
if (i == preset.linearStartTimestampsRelative.length) {
endTimestampForSegment = preset.linearEndTimestampRelative;
} else {
endTimestampForSegment = preset.linearStartTimestampsRelative[i];
}
startTimestampForSegment = preset.linearStartTimestampsRelative[i - 1];
if ((endTimestampForSegment - startTimestampForSegment) / preset.numOfUnlocksForEachLinear[i - 1] == 0) {
return false;
}
if (i == preset.linearStartTimestampsRelative.length) break;
i += 1;
}
return true;
}
}// SPDX-License-Identifier: AGPL v3
pragma solidity ^0.8.20;
import {ITTFutureTokenV2} from "../interfaces/ITTFutureTokenV2.sol";
import {IERC721AUpgradeable} from "erc721a-upgradeable/contracts/interfaces/IERC721AQueryableUpgradeable.sol";
import {
ERC721AQueryableUpgradeable,
ERC721AUpgradeable
} from "erc721a-upgradeable/contracts/extensions/ERC721AQueryableUpgradeable.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ITokenTableUnlockerV2} from "../interfaces/ITokenTableUnlockerV2.sol";
/**
* @title TTFutureTokenV2
* @author Jack Xu @ EthSign
* @dev This is a redemption NFT minted to the stakeholder whenever an actual
* unlocking schedule is created by a founder. The holder of a future token
* can use it to claim unlocked tokens. A single instance of future token
* corresponds to a single instance of unlocker. This token is transferrable.
* The ID of this NFT is the ID of the actual unlocking schedule. The current
* claimable amount can be determined by calling
* TokenTableUnlockerV2.calculateAmountClaimable(uint256 actualId)
*/
// solhint-disable var-name-mixedcase
// solhint-disable no-inline-assembly
// solhint-disable const-name-snakecase
// solhint-disable private-vars-leading-underscore
contract TTFutureTokenV2 is ITTFutureTokenV2, ERC721AQueryableUpgradeable {
/// @custom:storage-location erc7201:ethsign.tokentable.TTFutureTokenV2
struct TTFutureTokenV2Storage {
address authorizedMinter;
bool isTransferable;
string baseUri;
}
// keccak256(abi.encode(uint256(keccak256("ethsign.tokentable.TTFutureTokenV2")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant TTFutureTokenV2StorageLocation =
0xb50f0509372e72ec7790b055b09e294ca3549f94c48d078a7ee9a7b36fac3600;
function _getTTFutureTokenV2Storage() internal pure returns (TTFutureTokenV2Storage storage $) {
assembly {
$.slot := TTFutureTokenV2StorageLocation
}
}
// solhint-disable-next-line ordering
constructor() {
if (block.chainid != 33133 && block.chainid != 300 && block.chainid != 324) {
_dummyInitialize();
}
}
function _dummyInitialize() internal initializerERC721A {}
// solhint-disable-next-line ordering
function initialize(address projectToken, bool isTransferable_) external override initializerERC721A {
TTFutureTokenV2Storage storage $ = _getTTFutureTokenV2Storage();
__ERC721A_init_unchained(
string.concat("Future ", IERC20Metadata(projectToken).name()),
string.concat("FT-", IERC20Metadata(projectToken).symbol())
);
$.isTransferable = isTransferable_;
}
/**
* @notice Sets who is authorized to mint future tokens.
* @dev This function can only be called once. It is called automatically
* when deployed using TTUDeployer. The authorized minter is usually the
* unlocker contract.
*/
// solhint-disable-next-line ordering
function setAuthorizedMinterSingleUse(address authorizedMinter_) external override {
TTFutureTokenV2Storage storage $ = _getTTFutureTokenV2Storage();
if ($.authorizedMinter != address(0)) revert NotPermissioned();
$.authorizedMinter = authorizedMinter_;
}
/**
* @notice Mints a future token to an address.
* @dev This function can only be called by the authorized minter. A future
* token with tokenId == actualId is minted.
*/
function safeMint(address to) external override returns (uint256 tokenId) {
TTFutureTokenV2Storage storage $ = _getTTFutureTokenV2Storage();
if (_msgSenderERC721A() != $.authorizedMinter) revert NotPermissioned();
tokenId = _nextTokenId();
_safeMint(to, 1);
}
/**
* @dev Add a transfer lock
*/
function transferFrom(address from, address to, uint256 tokenId)
public
payable
virtual
override(ERC721AUpgradeable, IERC721AUpgradeable)
{
TTFutureTokenV2Storage storage $ = _getTTFutureTokenV2Storage();
if (!$.isTransferable) revert NotPermissioned();
super.transferFrom(from, to, tokenId);
}
/**
* @dev Add a transfer lock
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data)
public
payable
virtual
override(ERC721AUpgradeable, IERC721AUpgradeable)
{
TTFutureTokenV2Storage storage $ = _getTTFutureTokenV2Storage();
if (!$.isTransferable) revert NotPermissioned();
super.safeTransferFrom(from, to, tokenId, _data);
}
function setURI(string calldata uri) external {
TTFutureTokenV2Storage storage $ = _getTTFutureTokenV2Storage();
if (_msgSenderERC721A() != ITokenTableUnlockerV2($.authorizedMinter).owner()) revert NotPermissioned();
$.baseUri = uri;
emit DidSetBaseURI(uri);
}
/**
* @notice Returns the Unlocker address.
* @dev We assume the authorized minter is an instance of TTUV2.
*/
function getUnlocker() external view override returns (address) {
return _getTTFutureTokenV2Storage().authorizedMinter;
}
function version() public pure virtual override returns (string memory) {
return "2.6.0";
}
function _baseURI() internal view virtual override returns (string memory) {
TTFutureTokenV2Storage storage $ = _getTTFutureTokenV2Storage();
return $.baseUri;
}
}// SPDX-License-Identifier: AGPL v3
pragma solidity ^0.8.20;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
// solhint-disable var-name-mixedcase
// solhint-disable no-inline-assembly
// solhint-disable const-name-snakecase
// solhint-disable private-vars-leading-underscore
contract TTUProjectTokenStorage is Initializable {
/// @custom:storage-location erc7201:ethsign.tokentable.TTUProjectTokenStorage
struct TTUProjectTokenStorageStorage {
address _projectToken;
}
// keccak256(abi.encode(uint256(keccak256("ethsign.tokentable.TTUProjectTokenStorage")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant TTUProjectTokenStorageStorageLocation =
0xc6cedc2110f0271ccdfaf617b7233d3ed38f0d70138cb74c2dc2c8d098506000;
error TokenSet();
function _getTTUProjectTokenStorageStorage() internal pure returns (TTUProjectTokenStorageStorage storage $) {
assembly {
$.slot := TTUProjectTokenStorageStorageLocation
}
}
// solhint-disable-next-line ordering
function initializeProjectToken(address projectToken) public {
TTUProjectTokenStorageStorage storage $ = _getTTUProjectTokenStorageStorage();
if ($._projectToken != address(0)) revert TokenSet();
$._projectToken = projectToken;
}
function getProjectToken() public view returns (address) {
TTUProjectTokenStorageStorage storage $ = _getTTUProjectTokenStorageStorage();
return $._projectToken;
}
function _initializeSE(address projectToken) internal onlyInitializing {
TTUProjectTokenStorageStorage storage $ = _getTTUProjectTokenStorageStorage();
$._projectToken = projectToken;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IOwnable {
function renounceOwnership() external;
function transferOwnership(address newOwner) external;
function owner() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IOwnable} from "./IOwnable.sol";
import {IVersionable} from "./IVersionable.sol";
import {Preset, Actual} from "./TokenTableUnlockerV2DataModels.sol";
import {ITTHook} from "./ITTHook.sol";
import {ITTUDeployer} from "./ITTUDeployer.sol";
import {ITTFutureTokenV2} from "./ITTFutureTokenV2.sol";
/**
* @title ITokenTableUnlockerV2
* @author Jack Xu @ EthSign
* @dev The lightweight interface for TokenTableUnlockerV2(.5.x), which handles token unlocking and distribution for TokenTable.
*/
abstract contract ITokenTableUnlockerV2 is IOwnable, IVersionable {
event PresetCreated(bytes32 presetId, uint256 batchId);
event ActualCreated(bytes32 presetId, uint256 actualId, address recipient, uint256 recipientId, uint256 batchId);
event ActualCancelled(
uint256 actualId, uint256 pendingAmountClaimable, bool didWipeClaimableBalance, uint256 batchId
);
event TokensClaimed(
uint256 actualId, address caller, address to, uint256 amount, uint256 feesCharged, uint256 batchId
);
event TokensWithdrawn(address by, uint256 amount);
event ClaimingDelegateSet(address delegate, bool status);
event CreateDisabled();
event CancelDisabled();
event HookDisabled();
event WithdrawDisabled();
/**
* @dev 0x0ef8e8dc
*/
error InvalidPresetFormat();
/**
* @dev 0x7cbb15b4
*/
error PresetExists();
/**
* @dev 0xbd88ff7b
*/
error PresetDoesNotExist();
/**
* @dev 0x06aed316
*/
error ActualDoesNotExist();
/**
* @dev 0x78c0fc43
*/
error InvalidSkipAmount();
/**
* @dev 0x7f63bd0f
*/
error NotPermissioned();
/**
* @dev 0x2fac9032
*/
error AlreadyWithdrawable();
/**
* @dev This contract should be deployed with `TTUDeployerLite`, which calls this function with the correct parameters.
* @param projectToken The address of the token that the founder intends to unlock and distribute.
* @param futureToken_ The address of the associated FutureToken.
* @param deployer_ The address of the deployer. It helps call the fee collector during claim.
* @param isCancelable_ If the founder is allowed to cancel schedules. Can be disabled later, but cannot be enabled again.
* @param isHookable_ If the founder is allowed to attach external hooks to function calls. Can be disabled later, but cannot be enabled again.
* @param isWithdrawable_ If the founder is allowed to withdraw deposited tokens. Can be disabled later, but cannot be enabled again.
*/
function initialize(
address projectToken,
address futureToken_,
address deployer_,
bool isCancelable_,
bool isHookable_,
bool isWithdrawable_
) external virtual;
/**
* @notice Creates an unlocking schedule preset template.
* @dev Emits `PresetCreated`. Only callable by the owner.
* @param presetIds These IDs can be the hashes of a plaintext preset names but really there is no restriction. Will revert if they already exist.
* @param presets An array of `Preset` structs.
* @param batchId Emitted as an event reserved for EthSign frontend use. This parameter has no effect on contract execution.
* @param extraData An ERC-5750 parameter that's passed to the hook directly.
*/
function createPresets(
bytes32[] calldata presetIds,
Preset[] calldata presets,
uint256 batchId,
bytes calldata extraData
) external virtual;
/**
* @notice Creates an actual unlocking schedule based on a preset.
* @dev Emits `ActualCreated`. A FutureToken is minted in the process with `tokenId == actualId`.
* @param recipients An array of token recipients for the schedules. Note that claiming eligibility can be modified by transfering the corresponding FutureToken.
* @param actuals An array of `Actual` structs.
* @param recipientIds Emitted as an event reserved for EthSign frontend use. This parameter has no effect on contract execution.
* @param batchId Emitted as an event reserved for EthSign frontend use. This parameter has no effect on contract execution.
* @param extraData An ERC-5750 parameter that's passed to the hook directly.
*/
function createActuals(
address[] calldata recipients,
Actual[] calldata actuals,
uint256[] calldata recipientIds,
uint256 batchId,
bytes calldata extraData
) external virtual;
/**
* @notice Withdraws existing deposit from the contract.
* @dev Emits `TokensWithdrawn`. Only callable by the owner.
* @param amount Amount of deposited funds the founder wishes to withdraw.
* @param extraData An ERC-5750 parameter that's passed to the hook directly.
*/
function withdrawDeposit(uint256 amount, bytes calldata extraData) external virtual;
/**
* @notice Claims claimable tokens for the specified schedules to the specified addresses respectively.
* @dev Emits `TokensClaimed`. Only callable by the FutureToken owner.
* @param actualIds The IDs of the unlocking schedules that we are trying to claim from.
* @param claimTos If we want to send the claimed tokens to an address other than the caller. To send the claimed tokens to the caller (default behavior), pass in `ethers.constants.AddressZero`.
* @param batchId Emitted as an event reserved for EthSign frontend use. This parameter has no effect on contract execution.
* @param extraData An ERC-5750 parameter that's passed to the hook directly.
*/
function claim(uint256[] calldata actualIds, address[] calldata claimTos, uint256 batchId, bytes calldata extraData)
external
virtual;
/**
* @notice Claims claimable tokens for the specified schedules on behalf of recipients. Claimed tokens are sent to the schedule recipients.
* @dev Emits `TokensClaimed`. Only callable by the claiming delegate.
* @param actualIds The IDs of the unlocking schedules that we are trying to claim from on behalf of the recipients.
* @param batchId Emitted as an event reserved for EthSign frontend use. This parameter has no effect on contract execution.
* @param extraData An ERC-5750 parameter that's passed to the hook directly.
*/
function delegateClaim(uint256[] calldata actualIds, uint256 batchId, bytes calldata extraData) external virtual;
/**
* @notice Cancels an array of unlocking schedules effective immediately. Tokens not yet claimed but are already unlocked will be tallied.
* @dev Emits `ActualCancelled`. Only callable by the owner.
* @param actualIds The ID of the actual unlocking schedule that we want to cancel.
* @param shouldWipeClaimableBalance If the unlocked and claimable balance of the canceled schedule should be wiped. This is usually used to delete an erroneously created schedule that has already started unlocking.
* @param batchId Emitted as an event reserved for EthSign frontend use. This parameter has no effect on contract execution.
* @param extraData An ERC-5750 parameter that's passed to the hook directly.
* @return pendingAmountClaimables Number of tokens eligible to be claimed by the affected stakeholders at the moment of cancellation.
*/
function cancel(
uint256[] calldata actualIds,
bool[] calldata shouldWipeClaimableBalance,
uint256 batchId,
bytes calldata extraData
) external virtual returns (uint256[] memory pendingAmountClaimables);
/**
* @notice Sets the hook contract.
* @dev Only callable by the owner.
* @param hook The address of the `ITTHook` hook contract.
*/
function setHook(ITTHook hook) external virtual;
/**
* @notice Sets the claiming delegate who can trigger claims on behalf of recipients.
* @param delegate The claiming delegate we wish to set.
* @param status Whether the delegate is added(true) or revoked(false).
* @dev Only callable by the owner.
*/
function setClaimingDelegate(address delegate, bool status) external virtual;
/**
* @notice Sets if the current chain is supported by delegate.xyz
*/
function setCurrentChainSupportsExternalDelegateRegistry(bool status) external virtual;
/**
* @notice Permanently disables the `createActuals()` function.
* @dev Only callable by the owner.
*/
function disableCreate() external virtual;
/**
* @notice Permanently disables the `cancel()` function.
* @dev Only callable by the owner.
*/
function disableCancel() external virtual;
/**
* @notice Permanently disables the hook.
* @dev Only callable by the owner.
*/
function disableHook() external virtual;
/**
* @notice Permanently prevents the founder from withdrawing deposits.
* @dev Only callable by the owner.
*/
function disableWithdraw() external virtual;
/**
* @notice When withdraw is disabled, this allows the owner to request an emergency withdraw of deposited tokens. This must be approved by the deployer.
* @dev Only callable by the owner.
*/
function setEmergencyWithdrawRequestStatus(bool status) external virtual;
/**
* @return The deployer instance associated with this Unlocker.
*/
function deployer() external view virtual returns (ITTUDeployer);
/**
* @return The FutureToken instance associated with this Unlocker.
*/
function futureToken() external view virtual returns (ITTFutureTokenV2);
/**
* @return The external hook associated with this Unlocker.
*/
function hook() external view virtual returns (ITTHook);
/**
* @return Returns the array of claiming delegates who can trigger claims on behalf of schedule recipients.
*/
function claimingDelegates() external view virtual returns (address[] memory);
/**
* @return If the founder is allowed to create new schedules.
*/
function isCreateable() external view virtual returns (bool);
/**
* @return If the founder is allowed to cancel schedules.
*/
function isCancelable() external view virtual returns (bool);
/**
* @return If the founder can attach external hooks to function calls.
*/
function isHookable() external view virtual returns (bool);
/**
* @return If the founder can withdraw deposited but unclaimed tokens.
*/
function isWithdrawable() external view virtual returns (bool);
/**
* @param actualId The canceled schedule ID.
* @return The amount of tokens from canceled schedules that have been unlocked but unclaimed by the stakeholder.
*/
function pendingAmountClaimableForCancelledActuals(uint256 actualId) external view virtual returns (uint256);
/**
* @notice To decode in JS, use:
* ```js
* ethers.utils.defaultAbiCoder.decode(
* ['uint256[]', 'uint256', 'uint256[]', 'uint256[]', 'bool'],
* encodedPreset
* )
* ```
* @param presetId The ID of the preset we are trying to read.
* @return An ABI-encoded `Preset`, as nested objects cannot be returned directly in Solidity.
*/
function getEncodedPreset(bytes32 presetId) external view virtual returns (bytes memory);
/**
* @notice Returns the Actual struct based on the input ID.
*/
function actuals(uint256 actualId) external view virtual returns (Actual memory);
/**
* @return The basis point precision of this Unlocker.
*/
// function BIPS_PRECISION() external pure virtual returns (uint256); // Commenting this out, as this doesn't work with Hardhat upgrades plugin
/**
* @notice Returns if the current chain is supported by delegate.xyz
*/
function currentChainSupportsExternalDelegateRegistry() public view virtual returns (bool);
/**
* @notice Calculates the amount of unlocked tokens that have yet to be claimed in an actual unlocking schedule.
* @dev This is the most complex part of the smart contract. Quite a bit of calculations are performed here.
* @param actualId The ID of the actual unlocking schedule that we are working with.
* @return deltaAmountClaimable Amount of tokens claimable right now.
* @return updatedAmountClaimed New total amount of tokens claimed. This is the sum of all previously claimed tokens and `deltaAmountClaimable`.
*/
function calculateAmountClaimable(uint256 actualId)
public
view
virtual
returns (uint256 deltaAmountClaimable, uint256 updatedAmountClaimed);
/**
* @notice Simulates the amount of unlocked tokens that have yet to be claimed at a specific time in an actual unlocking schedule.
* @dev This is the most complex part of the smart contract. Quite a bit of calculations are performed here.
* @param actualId The ID of the actual unlocking schedule that we are working with.
* @param claimTimestampAbsolute The simulated time of claim.
* @return deltaAmountClaimable Amount of tokens claimable right now.
* @return updatedAmountClaimed New total amount of tokens claimed. This is the sum of all previously claimed tokens and `deltaAmountClaimable`.
*/
function simulateAmountClaimable(uint256 actualId, uint256 claimTimestampAbsolute)
public
view
virtual
returns (uint256 deltaAmountClaimable, uint256 updatedAmountClaimed);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {IERC721AQueryableUpgradeable} from "erc721a-upgradeable/contracts/interfaces/IERC721AQueryableUpgradeable.sol";
import {IVersionable} from "./IVersionable.sol";
/**
* @title ITTFutureTokenV2
* @author Jack Xu @ EthSign
* @dev The lightweight interface for TTFutureTokenV2(.5.x), which handles unlocking schedule ownership for TokenTable.
*/
interface ITTFutureTokenV2 is IERC721AQueryableUpgradeable, IVersionable {
event DidSetBaseURI(string newURI);
/**
* @dev 0x7f63bd0f
*/
error NotPermissioned();
/**
* @dev This contract should be deployed with `TTUDeployerLite`, which calls this function with the correct parameters.
* @param projectToken The address of the token that the founder intends to unlock and distribute.
* @param isTransferable If the FutureTokens (aka schedules) can be transfered once minted.
*/
function initialize(address projectToken, bool isTransferable) external;
/**
* @notice This contract should be deployed with `TTUDeployerLite`, which calls this function with the correct parameters.
* @dev This function can only be called once.
* @param authorizedMinter_ The address which is authorized to mint new FutureTokens. This is set to the corresponding Unlocker in the deployer.
*/
function setAuthorizedMinterSingleUse(address authorizedMinter_) external;
/**
* @notice Safely mints a new FutureToken to the specified address.
* @dev This function can only be called by the authorized minter.
* @param to The recipient of the new FutureToken.
* @return tokenId The minted token ID (aka actual ID or schedule ID).
*/
function safeMint(address to) external returns (uint256 tokenId);
/**
* @notice Updates the base URI.
* @dev This function can only be called by the owner of the authorized minter, which is usually the founder.
* @param uri The new base URI.
*/
function setURI(string calldata uri) external;
/**
* @notice Gets the Unlocker address.
*/
function getUnlocker() external view returns (address);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title ITTHook
* @author Jack Xu @ EthSign
*/
interface ITTHook {
/**
* @notice Forwards the call context from the hooked contract.
* @dev Reverts within hooks will revert the hooked contract as well.
* @param originalMsgData Forwarded calldata from the called function.
* @param originalMsgSender Forwarded sender from the called function.
*/
function didCall(bytes calldata originalMsgData, address originalMsgSender) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {IVersionable} from "./IVersionable.sol";
interface ITTTrackerTokenV2 is IVersionable {
/**
* @dev This contract should be deployed with `TTUDeployerLite`, which calls this function with the correct parameters.
* @param ttuInstance_ The address of the corresponding Unlocker.
*/
function initialize(address ttuInstance_) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {ITokenTableUnlockerV2} from "./ITokenTableUnlockerV2.sol";
import {ITTFutureTokenV2} from "./ITTFutureTokenV2.sol";
import {ITTUFeeCollector} from "./ITTUFeeCollector.sol";
/**
* @title TTUDeployer
* @author Jack Xu @ EthSign
* @dev This is the deployer for all TokenTable core and proxy contracts. All initial setup and configuration is automatically done here.
* To save gas and enable easy upgradeability, all deployed contracts are `Clone` or `BeaconProxy` instances.
* You should avoid deploying TokenTable contracts individually unless you know what you're doing.
*/
interface ITTUDeployer {
event TTUDeployerInitialized(
address unlockerImpl,
address futureTokenImpl,
address trackerTokenImpl,
address beaconManagerImpl,
address feeCollector
);
event TokenTableSuiteDeployed(
address by, string projectId, address unlocker, address futureToken, address trackerToken
);
event FeeCollectorChanged(address feeCollector);
/**
* @dev 0xa6ef0ba1
*/
error AlreadyDeployed();
/**
* @dev 0x82b42900
*/
error Unauthorized();
/**
* @dev 0xad78f5dc
*/
error MissingRequest();
/**
* @notice Exposes the fee collector variable.
* @return An instance of the fee collector.
*/
function feeCollector() external returns (ITTUFeeCollector);
/**
* @notice This function is called when an unlocker wants to initiate or cancel an emergency withdraw request.
* @dev Only callable by a deployed unlocker.
*/
function setEmergencyWithdrawRequestStatus(bool status) external;
/**
* @notice This function resets the approval to false while returning the current status.
* @dev Only callable by a deployed unlocker.
* @return approved If the withdraw request was approved.
*/
function consumeEmergencyWithdrawRequest() external returns (bool approved);
/**
* @notice Deploys and configures a new set of TokenTable products that uses an existing NFT as FutureToken.
* @dev Emits `TokenTableSuiteDeployed`. Throws: `AlreadyDeployed`.
* @param projectToken The project token address.
* @param projectId A unique projectId, otherwise it will revert.
* @param isUpgradeable When set to false, a `Clone` instead of a `BeaconProxy` is created to prevent future upgradeability.
* @param isTransferable Allow FutureToken to be transferable. Ignored if an existing FutureToken is supplied.
* @param isCancelable Allow unlocking schedules to be cancelled in the Unlocker.
* @param isHookable Allow Unlocker to call an external hook.
* @param isWithdrawable Allow the founder to withdraw deposited funds.
*/
function deployTTSuite(
address projectToken,
address existingFutureToken,
string memory projectId,
bool isUpgradeable,
bool isTransferable,
bool isCancelable,
bool isHookable,
bool isWithdrawable
) external returns (ITokenTableUnlockerV2, ITTFutureTokenV2);
/**
* @notice Allows external parties to query if an emergency withdraw request is approved.
* @return If the withdraw request is approved.
*/
function emergencyWithdrawApprovals(address unlocker) external view returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {IOwnable} from "./IOwnable.sol";
import {IVersionable} from "./IVersionable.sol";
/**
* @title ITTUFeeCollector
* @author Jack Xu @ EthSign
* @dev This contract handles TokenTable service fee calculation.
*/
interface ITTUFeeCollector is IOwnable, IVersionable {
event DefaultFeeSetBips(uint256 bips);
event DefaultFeeSet(uint256 fee);
event CustomFeeSetBips(address unlockerAddress, uint256 bips);
event CustomFeeSetFixed(address unlockerAddress, uint256 fixedFee);
/**
* @dev 0xc9034e18
*/
error FeesTooHigh();
/**
* @notice Returns the amount of fees to collect. A fixed fee will always override a dynamic fee.
* @param unlockerAddress The address of the Unlocker (or any contract that uses the fee collector). Used to fetch pricing.
* @param tokenTransferred The number of tokens transferred.
* @return tokensCollected The number of tokens to collect as fees.
*/
function getFee(address unlockerAddress, uint256 tokenTransferred)
external
view
returns (uint256 tokensCollected);
/**
* @notice Returns the fee token address.
* @param unlockerAddress The address of the Unlocker (or any contract that uses the fee collector). Used to fetch pricing.
*/
function getFeeToken(address unlockerAddress) external view returns (address tokenAddress);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title IVersionable
* @author Jack Xu @ EthSign
* @dev This interface is implemented by all major TokenTable contracts to keep track of their versioning for upgrade compatibility checks.
*/
interface IVersionable {
function version() external pure returns (string memory);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title TokenTableUnlockerV2DataModels.Preset
* @author Jack Xu @ EthSign
* @notice A `Preset` is an unlocking schedule template that contains information that's shared across all stakeholders within a single round.
*
* In this system, cliff unlocks are considered linear as well. This enables us to mix and match cliffs and linears at will, providing full customizability. Cliff waiting periods have a linear bip of 0 and cliff unlocking moments have a duration of 1 second.
*
* Note that all relative timestamps are relative to the absolute start timestamp. Absolute timestamps are standard UNIX epoch timestamps in seconds.
*
* `linearStartTimestampsRelative`: An array of start timestamps for each linear segment.
* `linearEndTimestampRelative`: The timestamp that marks the end of the final linear segment.
* `linearBips`: The basis point that is unlocked for each linear segment. Must add up to `TokenTableUnlockerV2.BIPS_PRECISION()`.
* `numOfUnlocksForEachLinear`: The number of unlocks within each respective linear segment.
* `stream`: If the tokens should unlock as a stream instead of a cliff at the end of linear segment subdivision.
*/
struct Preset {
uint256[] linearStartTimestampsRelative;
uint256 linearEndTimestampRelative;
uint256[] linearBips;
uint256[] numOfUnlocksForEachLinear;
bool stream;
}
/**
* @title TokenTableUnlockerV2DataModels.Actual
* @author Jack Xu @ EthSign
* @notice An `Actual` is an actual unlocking schedule for a single stakeholder and builds on top of an existing preset. An actual contains information that is different from one stakeholder to the next.
*
* `presetId`: The ID of the `Preset` that this `Actual` references.
* `startTimestampAbsolute`: The timestamp of when this unlocking schedule actually starts.
* `amountClaimed`: The amount of tokens that have already been claimed by the recipient.
* `totalAmount`: The maximum amount of tokens that the recipient can claim throughout the entire schedule.
*/
struct Actual {
bytes32 presetId;
uint256 startTimestampAbsolute;
uint256 amountClaimed;
uint256 totalAmount;
}// SPDX-License-Identifier: CC0-1.0
pragma solidity >=0.8.13;
/**
* @title IDelegateRegistry
* @custom:version 2.0
* @custom:author foobar (0xfoobar)
* @notice A standalone immutable registry storing delegated permissions from one address to another
*/
interface IDelegateRegistry {
/// @notice Delegation type, NONE is used when a delegation does not exist or is revoked
enum DelegationType {
NONE,
ALL,
CONTRACT,
ERC721,
ERC20,
ERC1155
}
/// @notice Struct for returning delegations
struct Delegation {
DelegationType type_;
address to;
address from;
bytes32 rights;
address contract_;
uint256 tokenId;
uint256 amount;
}
/// @notice Emitted when an address delegates or revokes rights for their entire wallet
event DelegateAll(address indexed from, address indexed to, bytes32 rights, bool enable);
/// @notice Emitted when an address delegates or revokes rights for a contract address
event DelegateContract(
address indexed from, address indexed to, address indexed contract_, bytes32 rights, bool enable
);
/// @notice Emitted when an address delegates or revokes rights for an ERC721 tokenId
event DelegateERC721(
address indexed from,
address indexed to,
address indexed contract_,
uint256 tokenId,
bytes32 rights,
bool enable
);
/// @notice Emitted when an address delegates or revokes rights for an amount of ERC20 tokens
event DelegateERC20(
address indexed from, address indexed to, address indexed contract_, bytes32 rights, uint256 amount
);
/// @notice Emitted when an address delegates or revokes rights for an amount of an ERC1155 tokenId
event DelegateERC1155(
address indexed from,
address indexed to,
address indexed contract_,
uint256 tokenId,
bytes32 rights,
uint256 amount
);
/// @notice Thrown if multicall calldata is malformed
error MulticallFailed();
/**
* ----------- WRITE -----------
*/
/**
* @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
* @param data The encoded function data for each of the calls to make to this contract
* @return results The results from each of the calls passed in via data
*/
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
/**
* @notice Allow the delegate to act on behalf of `msg.sender` for all contracts
* @param to The address to act as delegate
* @param rights Specific subdelegation rights granted to the delegate, pass an empty bytestring to encompass all rights
* @param enable Whether to enable or disable this delegation, true delegates and false revokes
* @return delegationHash The unique identifier of the delegation
*/
function delegateAll(address to, bytes32 rights, bool enable) external payable returns (bytes32 delegationHash);
/**
* @notice Allow the delegate to act on behalf of `msg.sender` for a specific contract
* @param to The address to act as delegate
* @param contract_ The contract whose rights are being delegated
* @param rights Specific subdelegation rights granted to the delegate, pass an empty bytestring to encompass all rights
* @param enable Whether to enable or disable this delegation, true delegates and false revokes
* @return delegationHash The unique identifier of the delegation
*/
function delegateContract(address to, address contract_, bytes32 rights, bool enable)
external
payable
returns (bytes32 delegationHash);
/**
* @notice Allow the delegate to act on behalf of `msg.sender` for a specific ERC721 token
* @param to The address to act as delegate
* @param contract_ The contract whose rights are being delegated
* @param tokenId The token id to delegate
* @param rights Specific subdelegation rights granted to the delegate, pass an empty bytestring to encompass all rights
* @param enable Whether to enable or disable this delegation, true delegates and false revokes
* @return delegationHash The unique identifier of the delegation
*/
function delegateERC721(address to, address contract_, uint256 tokenId, bytes32 rights, bool enable)
external
payable
returns (bytes32 delegationHash);
/**
* @notice Allow the delegate to act on behalf of `msg.sender` for a specific amount of ERC20 tokens
* @dev The actual amount is not encoded in the hash, just the existence of a amount (since it is an upper bound)
* @param to The address to act as delegate
* @param contract_ The address for the fungible token contract
* @param rights Specific subdelegation rights granted to the delegate, pass an empty bytestring to encompass all rights
* @param amount The amount to delegate, > 0 delegates and 0 revokes
* @return delegationHash The unique identifier of the delegation
*/
function delegateERC20(address to, address contract_, bytes32 rights, uint256 amount)
external
payable
returns (bytes32 delegationHash);
/**
* @notice Allow the delegate to act on behalf of `msg.sender` for a specific amount of ERC1155 tokens
* @dev The actual amount is not encoded in the hash, just the existence of a amount (since it is an upper bound)
* @param to The address to act as delegate
* @param contract_ The address of the contract that holds the token
* @param tokenId The token id to delegate
* @param rights Specific subdelegation rights granted to the delegate, pass an empty bytestring to encompass all rights
* @param amount The amount of that token id to delegate, > 0 delegates and 0 revokes
* @return delegationHash The unique identifier of the delegation
*/
function delegateERC1155(address to, address contract_, uint256 tokenId, bytes32 rights, uint256 amount)
external
payable
returns (bytes32 delegationHash);
/**
* ----------- CHECKS -----------
*/
/**
* @notice Check if `to` is a delegate of `from` for the entire wallet
* @param to The potential delegate address
* @param from The potential address who delegated rights
* @param rights Specific rights to check for, pass the zero value to ignore subdelegations and check full delegations only
* @return valid Whether delegate is granted to act on the from's behalf
*/
function checkDelegateForAll(address to, address from, bytes32 rights) external view returns (bool);
/**
* @notice Check if `to` is a delegate of `from` for the specified `contract_` or the entire wallet
* @param to The delegated address to check
* @param contract_ The specific contract address being checked
* @param from The cold wallet who issued the delegation
* @param rights Specific rights to check for, pass the zero value to ignore subdelegations and check full delegations only
* @return valid Whether delegate is granted to act on from's behalf for entire wallet or that specific contract
*/
function checkDelegateForContract(address to, address from, address contract_, bytes32 rights)
external
view
returns (bool);
/**
* @notice Check if `to` is a delegate of `from` for the specific `contract` and `tokenId`, the entire `contract_`, or the entire wallet
* @param to The delegated address to check
* @param contract_ The specific contract address being checked
* @param tokenId The token id for the token to delegating
* @param from The wallet that issued the delegation
* @param rights Specific rights to check for, pass the zero value to ignore subdelegations and check full delegations only
* @return valid Whether delegate is granted to act on from's behalf for entire wallet, that contract, or that specific tokenId
*/
function checkDelegateForERC721(address to, address from, address contract_, uint256 tokenId, bytes32 rights)
external
view
returns (bool);
/**
* @notice Returns the amount of ERC20 tokens the delegate is granted rights to act on the behalf of
* @param to The delegated address to check
* @param contract_ The address of the token contract
* @param from The cold wallet who issued the delegation
* @param rights Specific rights to check for, pass the zero value to ignore subdelegations and check full delegations only
* @return balance The delegated balance, which will be 0 if the delegation does not exist
*/
function checkDelegateForERC20(address to, address from, address contract_, bytes32 rights)
external
view
returns (uint256);
/**
* @notice Returns the amount of a ERC1155 tokens the delegate is granted rights to act on the behalf of
* @param to The delegated address to check
* @param contract_ The address of the token contract
* @param tokenId The token id to check the delegated amount of
* @param from The cold wallet who issued the delegation
* @param rights Specific rights to check for, pass the zero value to ignore subdelegations and check full delegations only
* @return balance The delegated balance, which will be 0 if the delegation does not exist
*/
function checkDelegateForERC1155(address to, address from, address contract_, uint256 tokenId, bytes32 rights)
external
view
returns (uint256);
/**
* ----------- ENUMERATIONS -----------
*/
/**
* @notice Returns all enabled delegations a given delegate has received
* @param to The address to retrieve delegations for
* @return delegations Array of Delegation structs
*/
function getIncomingDelegations(address to) external view returns (Delegation[] memory delegations);
/**
* @notice Returns all enabled delegations an address has given out
* @param from The address to retrieve delegations for
* @return delegations Array of Delegation structs
*/
function getOutgoingDelegations(address from) external view returns (Delegation[] memory delegations);
/**
* @notice Returns all hashes associated with enabled delegations an address has received
* @param to The address to retrieve incoming delegation hashes for
* @return delegationHashes Array of delegation hashes
*/
function getIncomingDelegationHashes(address to) external view returns (bytes32[] memory delegationHashes);
/**
* @notice Returns all hashes associated with enabled delegations an address has given out
* @param from The address to retrieve outgoing delegation hashes for
* @return delegationHashes Array of delegation hashes
*/
function getOutgoingDelegationHashes(address from) external view returns (bytes32[] memory delegationHashes);
/**
* @notice Returns the delegations for a given array of delegation hashes
* @param delegationHashes is an array of hashes that correspond to delegations
* @return delegations Array of Delegation structs, return empty structs for nonexistent or revoked delegations
*/
function getDelegationsFromHashes(bytes32[] calldata delegationHashes)
external
view
returns (Delegation[] memory delegations);
/**
* ----------- STORAGE ACCESS -----------
*/
/**
* @notice Allows external contracts to read arbitrary storage slots
*/
function readSlot(bytes32 location) external view returns (bytes32);
/**
* @notice Allows external contracts to read an arbitrary array of storage slots
*/
function readSlots(bytes32[] calldata locations) external view returns (bytes32[] memory);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable diamond facet 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.
*/
import {ERC721A__InitializableStorage} from './ERC721A__InitializableStorage.sol';
abstract contract ERC721A__Initializable {
using ERC721A__InitializableStorage for ERC721A__InitializableStorage.Layout;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializerERC721A() {
// 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(
ERC721A__InitializableStorage.layout()._initializing
? _isConstructor()
: !ERC721A__InitializableStorage.layout()._initialized,
'ERC721A__Initializable: contract is already initialized'
);
bool isTopLevelCall = !ERC721A__InitializableStorage.layout()._initializing;
if (isTopLevelCall) {
ERC721A__InitializableStorage.layout()._initializing = true;
ERC721A__InitializableStorage.layout()._initialized = true;
}
_;
if (isTopLevelCall) {
ERC721A__InitializableStorage.layout()._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 onlyInitializingERC721A() {
require(
ERC721A__InitializableStorage.layout()._initializing,
'ERC721A__Initializable: contract is not initializing'
);
_;
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base storage for the initialization function for upgradeable diamond facet contracts
**/
library ERC721A__InitializableStorage {
struct Layout {
/*
* Indicates that the contract has been initialized.
*/
bool _initialized;
/*
* Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.initializable.facet');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library ERC721AStorage {
// Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
struct TokenApprovalRef {
address value;
}
struct Layout {
// =============================================================
// STORAGE
// =============================================================
// The next token ID to be minted.
uint256 _currentIndex;
// The number of tokens burned.
uint256 _burnCounter;
// Token name
string _name;
// Token symbol
string _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned.
// See {_packedOwnershipOf} implementation for details.
//
// Bits Layout:
// - [0..159] `addr`
// - [160..223] `startTimestamp`
// - [224] `burned`
// - [225] `nextInitialized`
// - [232..255] `extraData`
mapping(uint256 => uint256) _packedOwnerships;
// Mapping owner address to address data.
//
// Bits Layout:
// - [0..63] `balance`
// - [64..127] `numberMinted`
// - [128..191] `numberBurned`
// - [192..255] `aux`
mapping(address => uint256) _packedAddressData;
// Mapping from token ID to approved address.
mapping(uint256 => ERC721AStorage.TokenApprovalRef) _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) _operatorApprovals;
}
bytes32 internal constant STORAGE_SLOT = keccak256('ERC721A.contracts.storage.ERC721A');
function layout() internal pure returns (Layout storage l) {
bytes32 slot = STORAGE_SLOT;
assembly {
l.slot := slot
}
}
}// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.3
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import './IERC721AUpgradeable.sol';
import {ERC721AStorage} from './ERC721AStorage.sol';
import './ERC721A__Initializable.sol';
/**
* @dev Interface of ERC721 token receiver.
*/
interface ERC721A__IERC721ReceiverUpgradeable {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC721A
*
* @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
* Non-Fungible Token Standard, including the Metadata extension.
* Optimized for lower gas during batch mints.
*
* Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
* starting from `_startTokenId()`.
*
* Assumptions:
*
* - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
* - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721AUpgradeable is ERC721A__Initializable, IERC721AUpgradeable {
using ERC721AStorage for ERC721AStorage.Layout;
// =============================================================
// CONSTANTS
// =============================================================
// Mask of an entry in packed address data.
uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
// The bit position of `numberMinted` in packed address data.
uint256 private constant _BITPOS_NUMBER_MINTED = 64;
// The bit position of `numberBurned` in packed address data.
uint256 private constant _BITPOS_NUMBER_BURNED = 128;
// The bit position of `aux` in packed address data.
uint256 private constant _BITPOS_AUX = 192;
// Mask of all 256 bits in packed address data except the 64 bits for `aux`.
uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
// The bit position of `startTimestamp` in packed ownership.
uint256 private constant _BITPOS_START_TIMESTAMP = 160;
// The bit mask of the `burned` bit in packed ownership.
uint256 private constant _BITMASK_BURNED = 1 << 224;
// The bit position of the `nextInitialized` bit in packed ownership.
uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;
// The bit mask of the `nextInitialized` bit in packed ownership.
uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;
// The bit position of `extraData` in packed ownership.
uint256 private constant _BITPOS_EXTRA_DATA = 232;
// Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
// The mask of the lower 160 bits for addresses.
uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;
// The maximum `quantity` that can be minted with {_mintERC2309}.
// This limit is to prevent overflows on the address data entries.
// For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}
// is required to cause an overflow, which is unrealistic.
uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
// The `Transfer` event signature is given by:
// `keccak256(bytes("Transfer(address,address,uint256)"))`.
bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
// =============================================================
// CONSTRUCTOR
// =============================================================
function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializingERC721A {
__ERC721A_init_unchained(name_, symbol_);
}
function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializingERC721A {
ERC721AStorage.layout()._name = name_;
ERC721AStorage.layout()._symbol = symbol_;
ERC721AStorage.layout()._currentIndex = _startTokenId();
}
// =============================================================
// TOKEN COUNTING OPERATIONS
// =============================================================
/**
* @dev Returns the starting token ID.
* To change the starting token ID, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Returns the next token ID to be minted.
*/
function _nextTokenId() internal view virtual returns (uint256) {
return ERC721AStorage.layout()._currentIndex;
}
/**
* @dev Returns the total number of tokens in existence.
* Burned tokens will reduce the count.
* To get the total number of tokens minted, please see {_totalMinted}.
*/
function totalSupply() public view virtual override returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than `_currentIndex - _startTokenId()` times.
unchecked {
return ERC721AStorage.layout()._currentIndex - ERC721AStorage.layout()._burnCounter - _startTokenId();
}
}
/**
* @dev Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view virtual returns (uint256) {
// Counter underflow is impossible as `_currentIndex` does not decrement,
// and it is initialized to `_startTokenId()`.
unchecked {
return ERC721AStorage.layout()._currentIndex - _startTokenId();
}
}
/**
* @dev Returns the total number of tokens burned.
*/
function _totalBurned() internal view virtual returns (uint256) {
return ERC721AStorage.layout()._burnCounter;
}
// =============================================================
// ADDRESS DATA OPERATIONS
// =============================================================
/**
* @dev Returns the number of tokens in `owner`'s account.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return ERC721AStorage.layout()._packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return
(ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return
(ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return uint64(ERC721AStorage.layout()._packedAddressData[owner] >> _BITPOS_AUX);
}
/**
* Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal virtual {
uint256 packed = ERC721AStorage.layout()._packedAddressData[owner];
uint256 auxCasted;
// Cast `aux` with assembly to avoid redundant masking.
assembly {
auxCasted := aux
}
packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
ERC721AStorage.layout()._packedAddressData[owner] = packed;
}
// =============================================================
// IERC165
// =============================================================
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* to learn more about how these ids are created.
*
* This function call must use less than 30000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
// The interface IDs are constants representing the first 4 bytes
// of the XOR of all function selectors in the interface.
// See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
// (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
return
interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165.
interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721.
interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
}
// =============================================================
// IERC721Metadata
// =============================================================
/**
* @dev Returns the token collection name.
*/
function name() public view virtual override returns (string memory) {
return ERC721AStorage.layout()._name;
}
/**
* @dev Returns the token collection symbol.
*/
function symbol() public view virtual override returns (string memory) {
return ERC721AStorage.layout()._symbol;
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
}
/**
* @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, it can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
// =============================================================
// OWNERSHIPS OPERATIONS
// =============================================================
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return address(uint160(_packedOwnershipOf(tokenId)));
}
/**
* @dev Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around over time.
*/
function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnershipOf(tokenId));
}
/**
* @dev Returns the unpacked `TokenOwnership` struct at `index`.
*/
function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
return _unpackedOwnership(ERC721AStorage.layout()._packedOwnerships[index]);
}
/**
* @dev Initializes the ownership slot minted at `index` for efficiency purposes.
*/
function _initializeOwnershipAt(uint256 index) internal virtual {
if (ERC721AStorage.layout()._packedOwnerships[index] == 0) {
ERC721AStorage.layout()._packedOwnerships[index] = _packedOwnershipOf(index);
}
}
/**
* Returns the packed ownership data of `tokenId`.
*/
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
if (_startTokenId() <= tokenId) {
packed = ERC721AStorage.layout()._packedOwnerships[tokenId];
// If not burned.
if (packed & _BITMASK_BURNED == 0) {
// If the data at the starting slot does not exist, start the scan.
if (packed == 0) {
if (tokenId >= ERC721AStorage.layout()._currentIndex) revert OwnerQueryForNonexistentToken();
// Invariant:
// There will always be an initialized ownership slot
// (i.e. `ownership.addr != address(0) && ownership.burned == false`)
// before an unintialized ownership slot
// (i.e. `ownership.addr == address(0) && ownership.burned == false`)
// Hence, `tokenId` will not underflow.
//
// We can directly compare the packed value.
// If the address is zero, packed will be zero.
for (;;) {
unchecked {
packed = ERC721AStorage.layout()._packedOwnerships[--tokenId];
}
if (packed == 0) continue;
return packed;
}
}
// Otherwise, the data exists and is not burned. We can skip the scan.
// This is possible because we have already achieved the target condition.
// This saves 2143 gas on transfers of initialized tokens.
return packed;
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev Returns the unpacked `TokenOwnership` struct from `packed`.
*/
function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
ownership.addr = address(uint160(packed));
ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
ownership.burned = packed & _BITMASK_BURNED != 0;
ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
}
/**
* @dev Packs ownership data into a single uint256.
*/
function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
assembly {
// Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
owner := and(owner, _BITMASK_ADDRESS)
// `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
}
}
/**
* @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
*/
function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
// For branchless setting of the `nextInitialized` flag.
assembly {
// `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
// =============================================================
// APPROVAL OPERATIONS
// =============================================================
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
*/
function approve(address to, uint256 tokenId) public payable virtual override {
_approve(to, tokenId, true);
}
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return ERC721AStorage.layout()._tokenApprovals[tokenId].value;
}
/**
* @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) public virtual override {
ERC721AStorage.layout()._operatorApprovals[_msgSenderERC721A()][operator] = approved;
emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
}
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return ERC721AStorage.layout()._operatorApprovals[owner][operator];
}
/**
* @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. See {_mint}.
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return
_startTokenId() <= tokenId &&
tokenId < ERC721AStorage.layout()._currentIndex && // If within bounds,
ERC721AStorage.layout()._packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned.
}
/**
* @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
*/
function _isSenderApprovedOrOwner(
address approvedAddress,
address owner,
address msgSender
) private pure returns (bool result) {
assembly {
// Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
owner := and(owner, _BITMASK_ADDRESS)
// Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
msgSender := and(msgSender, _BITMASK_ADDRESS)
// `msgSender == owner || msgSender == approvedAddress`.
result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
}
}
/**
* @dev Returns the storage slot and value for the approved address of `tokenId`.
*/
function _getApprovedSlotAndAddress(uint256 tokenId)
private
view
returns (uint256 approvedAddressSlot, address approvedAddress)
{
ERC721AStorage.TokenApprovalRef storage tokenApproval = ERC721AStorage.layout()._tokenApprovals[tokenId];
// The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
assembly {
approvedAddressSlot := tokenApproval.slot
approvedAddress := sload(approvedAddressSlot)
}
}
// =============================================================
// TRANSFER OPERATIONS
// =============================================================
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) public payable virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner();
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
// The nested ifs save around 20+ gas over a compound boolean condition.
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner.
assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.
sstore(approvedAddressSlot, 0)
}
}
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
unchecked {
// We can directly increment and decrement the balances.
--ERC721AStorage.layout()._packedAddressData[from]; // Updates: `balance -= 1`.
++ERC721AStorage.layout()._packedAddressData[to]; // Updates: `balance += 1`.
// Updates:
// - `address` to the next owner.
// - `startTimestamp` to the timestamp of transfering.
// - `burned` to `false`.
// - `nextInitialized` to `true`.
ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
// If the next slot's address is zero and not burned (i.e. packed value is zero).
if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
// If the next slot is within bounds.
if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @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 memory _data
) public payable virtual override {
transferFrom(from, to, tokenId);
if (to.code.length != 0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Hook that is called before a set of serially-ordered token IDs
* are about to be transferred. This includes minting.
* And also called before burning one token.
*
* `startTokenId` - the first token ID to be transferred.
* `quantity` - the amount to be transferred.
*
* 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, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token IDs
* have been transferred. This includes minting.
* And also called after one token has been burned.
*
* `startTokenId` - the first token ID to be transferred.
* `quantity` - the amount to be transferred.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* `from` - Previous owner of the given token ID.
* `to` - Target address that will receive the token.
* `tokenId` - Token ID to be transferred.
* `_data` - Optional data to send along with the call.
*
* Returns whether the call correctly returned the expected magic value.
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try
ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == ERC721A__IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
// =============================================================
// MINT OPERATIONS
// =============================================================
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event for each mint.
*/
function _mint(address to, uint256 quantity) internal virtual {
uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// `balance` and `numberMinted` have a maximum limit of 2**64.
// `tokenId` has a maximum limit of 2**256.
unchecked {
// Updates:
// - `balance += quantity`.
// - `numberMinted += quantity`.
//
// We can directly add to the `balance` and `numberMinted`.
ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
// Updates:
// - `address` to the owner.
// - `startTimestamp` to the timestamp of minting.
// - `burned` to `false`.
// - `nextInitialized` to `quantity == 1`.
ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
uint256 toMasked;
uint256 end = startTokenId + quantity;
// Use assembly to loop and emit the `Transfer` event for gas savings.
// The duplicated `log4` removes an extra check and reduces stack juggling.
// The assembly, together with the surrounding Solidity code, have been
// delicately arranged to nudge the compiler into producing optimized opcodes.
assembly {
// Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
toMasked := and(to, _BITMASK_ADDRESS)
// Emit the `Transfer` event.
log4(
0, // Start of data (0, since no data).
0, // End of data (0, since no data).
_TRANSFER_EVENT_SIGNATURE, // Signature.
0, // `address(0)`.
toMasked, // `to`.
startTokenId // `tokenId`.
)
// The `iszero(eq(,))` check ensures that large values of `quantity`
// that overflows uint256 will make the loop run out of gas.
// The compiler will optimize the `iszero` away for performance.
for {
let tokenId := add(startTokenId, 1)
} iszero(eq(tokenId, end)) {
tokenId := add(tokenId, 1)
} {
// Emit the `Transfer` event. Similar to above.
log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId)
}
}
if (toMasked == 0) revert MintToZeroAddress();
ERC721AStorage.layout()._currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* This function is intended for efficient minting only during contract creation.
*
* It emits only one {ConsecutiveTransfer} as defined in
* [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
* instead of a sequence of {Transfer} event(s).
*
* Calling this function outside of contract creation WILL make your contract
* non-compliant with the ERC721 standard.
* For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
* {ConsecutiveTransfer} event is only permissible during contract creation.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {ConsecutiveTransfer} event.
*/
function _mintERC2309(address to, uint256 quantity) internal virtual {
uint256 startTokenId = ERC721AStorage.layout()._currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are unrealistic due to the above check for `quantity` to be below the limit.
unchecked {
// Updates:
// - `balance += quantity`.
// - `numberMinted += quantity`.
//
// We can directly add to the `balance` and `numberMinted`.
ERC721AStorage.layout()._packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
// Updates:
// - `address` to the owner.
// - `startTimestamp` to the timestamp of minting.
// - `burned` to `false`.
// - `nextInitialized` to `quantity == 1`.
ERC721AStorage.layout()._packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
ERC721AStorage.layout()._currentIndex = startTokenId + quantity;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement
* {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* See {_mint}.
*
* Emits a {Transfer} event for each mint.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = ERC721AStorage.layout()._currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (index < end);
// Reentrancy protection.
if (ERC721AStorage.layout()._currentIndex != end) revert();
}
}
}
/**
* @dev Equivalent to `_safeMint(to, quantity, '')`.
*/
function _safeMint(address to, uint256 quantity) internal virtual {
_safeMint(to, quantity, '');
}
// =============================================================
// APPROVAL OPERATIONS
// =============================================================
/**
* @dev Equivalent to `_approve(to, tokenId, false)`.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_approve(to, tokenId, false);
}
/**
* @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:
*
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
bool approvalCheck
) internal virtual {
address owner = ownerOf(tokenId);
if (approvalCheck)
if (_msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
revert ApprovalCallerNotOwnerNorApproved();
}
ERC721AStorage.layout()._tokenApprovals[tokenId].value = to;
emit Approval(owner, to, tokenId);
}
// =============================================================
// BURN OPERATIONS
// =============================================================
/**
* @dev Equivalent to `_burn(tokenId, false)`.
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
// The nested ifs save around 20+ gas over a compound boolean condition.
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner.
assembly {
if approvedAddress {
// This is equivalent to `delete _tokenApprovals[tokenId]`.
sstore(approvedAddressSlot, 0)
}
}
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
unchecked {
// Updates:
// - `balance -= 1`.
// - `numberBurned += 1`.
//
// We can directly decrement the balance, and increment the number burned.
// This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
ERC721AStorage.layout()._packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
// Updates:
// - `address` to the last owner.
// - `startTimestamp` to the timestamp of burning.
// - `burned` to `true`.
// - `nextInitialized` to `true`.
ERC721AStorage.layout()._packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
// If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
// If the next slot's address is zero and not burned (i.e. packed value is zero).
if (ERC721AStorage.layout()._packedOwnerships[nextTokenId] == 0) {
// If the next slot is within bounds.
if (nextTokenId != ERC721AStorage.layout()._currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
ERC721AStorage.layout()._packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
ERC721AStorage.layout()._burnCounter++;
}
}
// =============================================================
// EXTRA DATA OPERATIONS
// =============================================================
/**
* @dev Directly sets the extra data for the ownership data `index`.
*/
function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
uint256 packed = ERC721AStorage.layout()._packedOwnerships[index];
if (packed == 0) revert OwnershipNotInitializedForExtraData();
uint256 extraDataCasted;
// Cast `extraData` with assembly to avoid redundant masking.
assembly {
extraDataCasted := extraData
}
packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
ERC721AStorage.layout()._packedOwnerships[index] = packed;
}
/**
* @dev Called during each token transfer to set the 24bit `extraData` field.
* Intended to be overridden by the cosumer contract.
*
* `previousExtraData` - the value of `extraData` before 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, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _extraData(
address from,
address to,
uint24 previousExtraData
) internal view virtual returns (uint24) {}
/**
* @dev Returns the next extra data for the packed ownership data.
* The returned result is shifted into position.
*/
function _nextExtraData(
address from,
address to,
uint256 prevOwnershipPacked
) private view returns (uint256) {
uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
}
// =============================================================
// OTHER OPERATIONS
// =============================================================
/**
* @dev Returns the message sender (defaults to `msg.sender`).
*
* If you are writing GSN compatible contracts, you need to override this function.
*/
function _msgSenderERC721A() internal view virtual returns (address) {
return msg.sender;
}
/**
* @dev Converts a uint256 to its ASCII string decimal representation.
*/
function _toString(uint256 value) internal pure virtual returns (string memory str) {
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
let m := add(mload(0x40), 0xa0)
// Update the free memory pointer to allocate.
mstore(0x40, m)
// Assign the `str` to the end.
str := sub(m, 0x20)
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
// prettier-ignore
for { let temp := value } 1 {} {
str := sub(str, 1)
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing `temp` until zero.
temp := div(temp, 10)
// prettier-ignore
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
}
}// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.3
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import './IERC721AQueryableUpgradeable.sol';
import '../ERC721AUpgradeable.sol';
import '../ERC721A__Initializable.sol';
/**
* @title ERC721AQueryable.
*
* @dev ERC721A subclass with convenience query functions.
*/
abstract contract ERC721AQueryableUpgradeable is
ERC721A__Initializable,
ERC721AUpgradeable,
IERC721AQueryableUpgradeable
{
function __ERC721AQueryable_init() internal onlyInitializingERC721A {
__ERC721AQueryable_init_unchained();
}
function __ERC721AQueryable_init_unchained() internal onlyInitializingERC721A {}
/**
* @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
*
* If the `tokenId` is out of bounds:
*
* - `addr = address(0)`
* - `startTimestamp = 0`
* - `burned = false`
* - `extraData = 0`
*
* If the `tokenId` is burned:
*
* - `addr = <Address of owner before token was burned>`
* - `startTimestamp = <Timestamp when token was burned>`
* - `burned = true`
* - `extraData = <Extra data when token was burned>`
*
* Otherwise:
*
* - `addr = <Address of owner>`
* - `startTimestamp = <Timestamp of start of ownership>`
* - `burned = false`
* - `extraData = <Extra data at start of ownership>`
*/
function explicitOwnershipOf(uint256 tokenId) public view virtual override returns (TokenOwnership memory) {
TokenOwnership memory ownership;
if (tokenId < _startTokenId() || tokenId >= _nextTokenId()) {
return ownership;
}
ownership = _ownershipAt(tokenId);
if (ownership.burned) {
return ownership;
}
return _ownershipOf(tokenId);
}
/**
* @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
* See {ERC721AQueryable-explicitOwnershipOf}
*/
function explicitOwnershipsOf(uint256[] calldata tokenIds)
external
view
virtual
override
returns (TokenOwnership[] memory)
{
unchecked {
uint256 tokenIdsLength = tokenIds.length;
TokenOwnership[] memory ownerships = new TokenOwnership[](tokenIdsLength);
for (uint256 i; i != tokenIdsLength; ++i) {
ownerships[i] = explicitOwnershipOf(tokenIds[i]);
}
return ownerships;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`,
* in the range [`start`, `stop`)
* (i.e. `start <= tokenId < stop`).
*
* This function allows for tokens to be queried if the collection
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
*
* Requirements:
*
* - `start < stop`
*/
function tokensOfOwnerIn(
address owner,
uint256 start,
uint256 stop
) external view virtual override returns (uint256[] memory) {
unchecked {
if (start >= stop) revert InvalidQueryRange();
uint256 tokenIdsIdx;
uint256 stopLimit = _nextTokenId();
// Set `start = max(start, _startTokenId())`.
if (start < _startTokenId()) {
start = _startTokenId();
}
// Set `stop = min(stop, stopLimit)`.
if (stop > stopLimit) {
stop = stopLimit;
}
uint256 tokenIdsMaxLength = balanceOf(owner);
// Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`,
// to cater for cases where `balanceOf(owner)` is too big.
if (start < stop) {
uint256 rangeLength = stop - start;
if (rangeLength < tokenIdsMaxLength) {
tokenIdsMaxLength = rangeLength;
}
} else {
tokenIdsMaxLength = 0;
}
uint256[] memory tokenIds = new uint256[](tokenIdsMaxLength);
if (tokenIdsMaxLength == 0) {
return tokenIds;
}
// We need to call `explicitOwnershipOf(start)`,
// because the slot at `start` may not be initialized.
TokenOwnership memory ownership = explicitOwnershipOf(start);
address currOwnershipAddr;
// If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`.
// `ownership.address` will not be zero, as `start` is clamped to the valid token ID range.
if (!ownership.burned) {
currOwnershipAddr = ownership.addr;
}
for (uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
// Downsize the array to fit.
assembly {
mstore(tokenIds, tokenIdsIdx)
}
return tokenIds;
}
}
/**
* @dev Returns an array of token IDs owned by `owner`.
*
* This function scans the ownership mapping and is O(`totalSupply`) in complexity.
* It is meant to be called off-chain.
*
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
* multiple smaller scans if the collection is large enough to cause
* an out-of-gas error (10K collections should be fine).
*/
function tokensOfOwner(address owner) external view virtual override returns (uint256[] memory) {
unchecked {
uint256 tokenIdsIdx;
address currOwnershipAddr;
uint256 tokenIdsLength = balanceOf(owner);
uint256[] memory tokenIds = new uint256[](tokenIdsLength);
TokenOwnership memory ownership;
for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
return tokenIds;
}
}
}// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.3
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import '../IERC721AUpgradeable.sol';
/**
* @dev Interface of ERC721AQueryable.
*/
interface IERC721AQueryableUpgradeable is IERC721AUpgradeable {
/**
* Invalid query range (`start` >= `stop`).
*/
error InvalidQueryRange();
/**
* @dev Returns the `TokenOwnership` struct at `tokenId` without reverting.
*
* If the `tokenId` is out of bounds:
*
* - `addr = address(0)`
* - `startTimestamp = 0`
* - `burned = false`
* - `extraData = 0`
*
* If the `tokenId` is burned:
*
* - `addr = <Address of owner before token was burned>`
* - `startTimestamp = <Timestamp when token was burned>`
* - `burned = true`
* - `extraData = <Extra data when token was burned>`
*
* Otherwise:
*
* - `addr = <Address of owner>`
* - `startTimestamp = <Timestamp of start of ownership>`
* - `burned = false`
* - `extraData = <Extra data at start of ownership>`
*/
function explicitOwnershipOf(uint256 tokenId) external view returns (TokenOwnership memory);
/**
* @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order.
* See {ERC721AQueryable-explicitOwnershipOf}
*/
function explicitOwnershipsOf(uint256[] memory tokenIds) external view returns (TokenOwnership[] memory);
/**
* @dev Returns an array of token IDs owned by `owner`,
* in the range [`start`, `stop`)
* (i.e. `start <= tokenId < stop`).
*
* This function allows for tokens to be queried if the collection
* grows too big for a single call of {ERC721AQueryable-tokensOfOwner}.
*
* Requirements:
*
* - `start < stop`
*/
function tokensOfOwnerIn(
address owner,
uint256 start,
uint256 stop
) external view returns (uint256[] memory);
/**
* @dev Returns an array of token IDs owned by `owner`.
*
* This function scans the ownership mapping and is O(`totalSupply`) in complexity.
* It is meant to be called off-chain.
*
* See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into
* multiple smaller scans if the collection is large enough to cause
* an out-of-gas error (10K collections should be fine).
*/
function tokensOfOwner(address owner) external view returns (uint256[] memory);
}// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.3
// Creator: Chiru Labs
pragma solidity ^0.8.4;
/**
* @dev Interface of ERC721A.
*/
interface IERC721AUpgradeable {
/**
* The caller must own the token or be an approved operator.
*/
error ApprovalCallerNotOwnerNorApproved();
/**
* The token does not exist.
*/
error ApprovalQueryForNonexistentToken();
/**
* Cannot query the balance for the zero address.
*/
error BalanceQueryForZeroAddress();
/**
* Cannot mint to the zero address.
*/
error MintToZeroAddress();
/**
* The quantity of tokens minted must be more than zero.
*/
error MintZeroQuantity();
/**
* The token does not exist.
*/
error OwnerQueryForNonexistentToken();
/**
* The caller must own the token or be an approved operator.
*/
error TransferCallerNotOwnerNorApproved();
/**
* The token must be owned by `from`.
*/
error TransferFromIncorrectOwner();
/**
* Cannot safely transfer to a contract that does not implement the
* ERC721Receiver interface.
*/
error TransferToNonERC721ReceiverImplementer();
/**
* Cannot transfer to the zero address.
*/
error TransferToZeroAddress();
/**
* The token does not exist.
*/
error URIQueryForNonexistentToken();
/**
* The `quantity` minted with ERC2309 exceeds the safety limit.
*/
error MintERC2309QuantityExceedsLimit();
/**
* The `extraData` cannot be set on an unintialized ownership slot.
*/
error OwnershipNotInitializedForExtraData();
// =============================================================
// STRUCTS
// =============================================================
struct TokenOwnership {
// The address of the owner.
address addr;
// Stores the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
// Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
uint24 extraData;
}
// =============================================================
// TOKEN COUNTERS
// =============================================================
/**
* @dev Returns the total number of tokens in existence.
* Burned tokens will reduce the count.
* To get the total number of tokens minted, please see {_totalMinted}.
*/
function totalSupply() external view returns (uint256);
// =============================================================
// IERC165
// =============================================================
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
* to learn more about how these ids are created.
*
* This function call must use less than 30000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
// =============================================================
// IERC721
// =============================================================
/**
* @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,
bytes calldata data
) external payable;
/**
* @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external payable;
/**
* @dev Transfers `tokenId` 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 payable;
/**
* @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 payable;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom}
* for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
// =============================================================
// IERC721Metadata
// =============================================================
/**
* @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);
// =============================================================
// IERC2309
// =============================================================
/**
* @dev Emitted when tokens in `fromTokenId` to `toTokenId`
* (inclusive) is transferred from `from` to `to`, as defined in the
* [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
*
* See {_mintERC2309} for more details.
*/
event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
}// SPDX-License-Identifier: MIT // ERC721A Contracts v4.2.3 // Creator: Chiru Labs pragma solidity ^0.8.4; import '../extensions/IERC721AQueryableUpgradeable.sol';
{
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"bytecodeHash": "none",
"useLiteralContent": true
},
"evmVersion": "paris",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}Contract ABI
API[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"ttuInstance_","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"ttuInstance","outputs":[{"internalType":"contract TokenTableUnlockerV2","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"}]Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 33 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.