Verified contractExactCC-BY-NC-ND-2.5
Factory
Address0x9692e68aec88bf16846ef51ca5bd8b9ae3625609
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.16
- Same code
Only this contract
Details
- Compiler
- solc 0.8.16+commit.07a7930e
- Language
- solidity
- Optimization
- Yes, 999,999 runs
- EVM version
- london
- License
- CC-BY-NC-ND-2.5
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 18,497,746
- Creation transaction
- 0xcfa86335f3…e22b05e705
42 files
- contracts/Factory.solmain18.11 KB
- @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol3.15 KB
- @openzeppelin/contracts-upgradeable/interfaces/IERC1967Upgradeable.sol678 B
- @openzeppelin/contracts-upgradeable/interfaces/draft-IERC1822Upgradeable.sol890 B
- @openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol4.04 KB
- @openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol6.78 KB
- @openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol461 B
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.64 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol4.89 KB
- @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol3.66 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol2.75 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol2.27 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol7.1 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol9.38 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.35 KB
- @openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol4.12 KB
- @openzeppelin/contracts/access/AccessControl.sol8.23 KB
- @openzeppelin/contracts/access/IAccessControl.sol2.92 KB
- @openzeppelin/contracts/access/Ownable.sol2.62 KB
- @openzeppelin/contracts/proxy/Clones.sol4.03 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.74 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol2.26 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol6.94 KB
- @openzeppelin/contracts/utils/Address.sol9.36 KB
- @openzeppelin/contracts/utils/Context.sol844 B
- @openzeppelin/contracts/utils/Strings.sol2.78 KB
- @openzeppelin/contracts/utils/cryptography/MerkleProof.sol9.62 KB
- @openzeppelin/contracts/utils/introspection/ERC165.sol987 B
- @openzeppelin/contracts/utils/introspection/IERC165.sol853 B
- @openzeppelin/contracts/utils/math/Math.sol12.79 KB
- @openzeppelin/contracts/utils/math/SignedMath.sol1.26 KB
- contracts/ERC20FixedPriceAllocator.sol26.6 KB
- contracts/ERC20ManualAllocator.sol15.26 KB
- contracts/ERC20OptionsAllocator.sol18.96 KB
- contracts/NftAllocator.sol14.72 KB
- contracts/Types.sol3.04 KB
- contracts/Venture.sol10.66 KB
- contracts/interfaces/IJubiERC20.sol1.8 KB
- contracts/utils/SignatureValidation.sol4.04 KB
- erc721a/contracts/ERC721A.sol41.35 KB
- erc721a/contracts/IERC721A.sol8.71 KB
contracts/Factory.sol
//SPDX-License-Identifier: CC-BY-NC-ND-2.5
pragma solidity 0.8.16;
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ClonesUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {Venture} from "./Venture.sol";
import {Types} from "./Types.sol";
import {NftAllocator} from "./NftAllocator.sol";
import {ERC20FixedPriceAllocator} from "./ERC20FixedPriceAllocator.sol";
import {IJubiERC20} from "./interfaces/IJubiERC20.sol";
import {ERC20ManualAllocator} from "./ERC20ManualAllocator.sol";
import {ERC20OptionsAllocator} from "./ERC20OptionsAllocator.sol";
/**
* @title Contract factory to manage ventures
* @notice You can use this Contract to create new Ventures and Allocators
*/
contract Factory is OwnableUpgradeable, UUPSUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice Is the address where Jubi fees will be sent
address public jubiFundsAddress;
/// @notice Is the % fee jubi will be charging IE: 1% num: 1, den: 100
Types.Fraction public jubiFeePercent;
/// @notice A list of all ventures created by this factory
Venture[] public ventures;
/// @notice A list of ventures managed by this factory
mapping(address => bool) public managedVentures;
/// @notice The address to use when creating a new Venture
address public ventureImpl;
/// @notice The address to use when creating a new NftAllocator
address public nftAllocatorImpl;
/// @notice The address to use when creating a new SignatureStore
address public signatureStoreNftAllocatorImpl;
/// @notice The address to use when creating a new FixedPrice ERC20 allocator
address public ERC20FixedPriceAllocatorImpl;
/// @notice The address to use when creating a new SignatureStore
address public ERC20FixedPriceAllocatorSignatureStoreImpl;
/// @notice The address to use when creating a new FixedPrice ERC20 allocator
address public ERC20ManualAllocatorImpl;
/// @notice The address to use when creating a new ERC20 Options allocator
address public ERC20OptionsAllocatorImpl;
/**
* @notice This event is emitted when a Venture(`venture`) is created, by `owner` with `config` at a specific `version`
* @param owner The venture owner.
* @param venture The venture that was created.
* @param config The config that was used to create the Venture.
* @param impl The ventureImpl that was used.
*/
event VentureCreated(address indexed owner, Venture indexed venture, Types.VentureConfig config, address impl);
/**
* @notice This event is emitted when an NFT Allocator(`allocator`) is created, of type `allocatorType` with `config`
* at a specific `version` it will be attached to a Venture(`venture`)
* @param venture The venture that manages this allocator.
* @param allocator The allocator that was created.
* @param config The config that was used to create the Allocator.
* @param impl The allocatorImpl that was used.
*/
event NFTAllocatorCreated(address indexed venture, address indexed allocator, Types.AllocatorType allocatorType, Types.NftAllocatorConfig config, address impl);
/**
* @notice This event is emitted when an ERC20 Allocator(`allocator`) is created, of type `allocatorType` with `config`
* at a specific `version` it will be attached to a Venture(`venture`)
* @param venture The venture that manages this allocator.
* @param allocator The allocator that was created.
* @param config The config that was used to create the Allocator.
* @param impl The allocatorImpl that was used.
*/
event ERC20FixedPriceAllocatorCreated(address indexed venture, address indexed allocator, Types.AllocatorType allocatorType, Types.ERC20FixedPriceAllocatorConfig config, address impl);
/**
* @notice This event is emitted when an ERC20 Allocator(`allocator`) is created, of type `allocatorType` with `config`
* at a specific `version` it will be attached to a Venture(`venture`)
* @param venture The venture that manages this allocator.
* @param allocator The allocator that was created.
* @param config The config that was used to create the Allocator.
* @param impl The allocatorImpl that was used.
*/
event ERC20ManualAllocatorCreated(address indexed venture, address indexed allocator, Types.AllocatorType allocatorType, Types.AllocatorConfig config, address impl);
/**
* @notice This event is emitted when an ERC20 Allocator(`allocator`) is created, of type `allocatorType` with `config`
* at a specific `version` it will be attached to a Venture(`venture`)
* @param venture The venture that manages this allocator.
* @param allocator The allocator that was created.
* @param config The config that was used to create the Allocator.
* @param impl The allocatorImpl that was used.
*/
event ERC20OptionsAllocatorCreated(address indexed venture, address indexed allocator, Types.AllocatorType allocatorType, Types.AllocatorConfig config, address impl);
/**
* @notice This event is emitted when an Allocator is updated to a new impl `newImpl`
* @param newImpl The address of the new implementation to be used
* @param allocatorType The type of allocator that was updated
*/
event AllocatorImplUpdated(address newImpl, Types.AllocatorType allocatorType);
/**
* @notice This event is emitted when the ventureImpl is updated
* @param newImpl The address of the new implementation to be used
*/
event VentureImplUpdated(address newImpl);
/**
* @notice This event is emitted when the signatureStoreImpl is updated
* @param newImpl The address of the new implementation to be used
*/
event SignatureStoreNftAllocatorImplUpdated(address newImpl);
/**
* @notice This event is emitted when the ERC20 signatureStoreImpl is updated
* @param newImpl The address of the new implementation to be used
*/
event ERC20FixedPriceSignatureStoreImplUpdated(address newImpl);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @param _ventureImpl The initial address to use for Venture Clones.
* @param _nftAllocatorImpl The initial address to use for nftAllocator Clones.
* @param _ERC20FixedPriceAllocatorImpl The initial address to use for ERC20FixedPriceAllocator Clones.
*/
function initialize(
address _ventureImpl,
address _nftAllocatorImpl,
address _ERC20FixedPriceAllocatorImpl,
address _jubiFundsAddress,
uint128 jubiFeePercentNumerator,
uint128 jubiFeePercentDenominator
) initializer public {
__Ownable_init();
__UUPSUpgradeable_init();
ventureImpl = _ventureImpl;
nftAllocatorImpl = _nftAllocatorImpl;
ERC20FixedPriceAllocatorImpl = _ERC20FixedPriceAllocatorImpl;
jubiFundsAddress = _jubiFundsAddress;
jubiFeePercent.num = jubiFeePercentNumerator;
jubiFeePercent.den = jubiFeePercentDenominator;
}
/**
* @notice This function is used to set/initialize new variables upon each upgrade of the contract
* @param _fixedPriceERC20AllocatorImpl The address of the Fixed Price ERC20 Allocator implementation.
*/
function initializeAtUpgrade(address _fixedPriceERC20AllocatorImpl) reinitializer(2) external onlyOwner {
/* TODO: Possibly replace calling with upgradeAndCall ?? */
require(_fixedPriceERC20AllocatorImpl != address(0), "Factory: fixedPriceERC20AllocatorImpl cannot be 0" );
_updateAllocatorImpl(_fixedPriceERC20AllocatorImpl, Types.AllocatorType.ERC20_FIXED_PRICE);
}
/**
* @notice Sets the Jubi fee percentage.
* @dev Only the contract owner can call this function.
* @param _fee The new Jubi fee percentage as a fraction.
*/
function setJubiFeePercent(Types.Fraction calldata _fee) external onlyOwner {
jubiFeePercent.num = _fee.num;
jubiFeePercent.den = _fee.den;
}
/**
* @notice Creates a Venture with `config` as params
* @param config The configuration to create the Venture
*
* Emits a {VentureCreated} event.
*/
function createVenture(Types.VentureConfig memory config) external {
require(config.fundsAddress != address(0), "Factory: invalid funds address");
require(address(config.treasuryToken) != address(0), "Factory: Treasury token cannot be 0 address");
bytes32 salt = keccak256(abi.encodePacked(msg.sender, config.fundsAddress));
Venture venture = Venture(ClonesUpgradeable.cloneDeterministic(ventureImpl, salt));
venture.initialize(config, msg.sender);
ventures.push(venture);
managedVentures[address(venture)] = true;
emit VentureCreated(msg.sender, venture, config, ventureImpl);
}
/**
* @notice Creates a NftAllocator with `config` as params
* @param config The configuration to create the NftAllocator
*
* Emits a {AllocatorCreated} event.
*/
function createNftAllocator(Types.NftAllocatorConfig memory config) external {
Venture venture = config.venture;
require(managedVentures[address(venture)], "Factory: invalid venture address");
require(venture.isAdminOrAllocatorManager(msg.sender), "Factory: only venture manager can add allocator");
NftAllocator allocator = NftAllocator(ClonesUpgradeable.clone(nftAllocatorImpl));
allocator.initialize(jubiFundsAddress, jubiFeePercent, config, msg.sender);
venture.addAllocator(address(allocator), uint256(Types.AllocatorType.NFT), config.tokensForAllocation);
emit NFTAllocatorCreated(address(venture), address(allocator), Types.AllocatorType.NFT, config, nftAllocatorImpl);
}
/**
* @notice Creates a NftAllocator with `config` as params
* @param config The configuration to create the NftAllocator
*
* Emits a {AllocatorCreated} event.
*/
function createERC20FixedPriceAllocator(Types.ERC20FixedPriceAllocatorConfig memory config) external {
Venture venture = config.venture;
require(managedVentures[address(venture)], "Factory: invalid venture address");
require(venture.isAdminOrAllocatorManager(msg.sender), "Factory: only venture manager can add allocator");
ERC20FixedPriceAllocator allocator = ERC20FixedPriceAllocator(ClonesUpgradeable.clone(ERC20FixedPriceAllocatorImpl));
if (address(config.allocationToken) != address(0)) {
IERC20Upgradeable allocationToken = IERC20Upgradeable(address(config.allocationToken));
allocationToken.safeTransferFrom(
msg.sender,
address(this),
config.tokensForAllocation
);
allocationToken.safeApprove(address(allocator), config.tokensForAllocation);
}
allocator.initialize(msg.sender, config);
venture.addAllocator(address(allocator), uint256(Types.AllocatorType.ERC20_FIXED_PRICE), config.tokensForAllocation);
emit ERC20FixedPriceAllocatorCreated(address(venture), address(allocator), Types.AllocatorType.ERC20_FIXED_PRICE, config, ERC20FixedPriceAllocatorImpl);
}
/**
* @notice Creates a ERC20ManualAllocator with `config` as params
* @param config The configuration to create the Allocator
*
* Emits a {AllocatorCreated} event.
*/
function createERC20ManualAllocator(Types.AllocatorConfig memory config) external {
Venture venture = config.venture;
require(managedVentures[address(venture)], "Factory: invalid venture address");
require(venture.isAdminOrAllocatorManager(msg.sender), "Factory: only venture manager can add allocator");
ERC20ManualAllocator allocator = ERC20ManualAllocator(ClonesUpgradeable.clone(ERC20ManualAllocatorImpl));
if (address(config.allocationToken) != address(0)) {
IERC20Upgradeable allocationToken = IERC20Upgradeable(address(config.allocationToken));
allocationToken.safeTransferFrom(
msg.sender,
address(this),
config.tokensForAllocation
);
allocationToken.safeApprove(address(allocator), config.tokensForAllocation);
}
allocator.initialize(config);
venture.addAllocator(address(allocator), uint256(Types.AllocatorType.ERC20_MANUAL), config.tokensForAllocation);
emit ERC20ManualAllocatorCreated(address(venture), address(allocator), Types.AllocatorType.ERC20_MANUAL, config, ERC20ManualAllocatorImpl);
}
/**
* @notice Creates a ERC20ManualAllocator with `config` as params
* @param config The configuration to create the Allocator
*
* Emits a {AllocatorCreated} event.
*/
function createERC20OptionsAllocator(Types.AllocatorConfig memory config) external {
Venture venture = config.venture;
require(managedVentures[address(venture)], "Factory: invalid venture address");
require(venture.isAdminOrAllocatorManager(msg.sender), "Factory: only venture manager can add allocator");
ERC20OptionsAllocator allocator = ERC20OptionsAllocator(ClonesUpgradeable.clone(ERC20OptionsAllocatorImpl));
if (address(config.allocationToken) != address(0)) {
IERC20Upgradeable allocationToken = IERC20Upgradeable(address(config.allocationToken));
allocationToken.safeTransferFrom(
msg.sender,
address(this),
config.tokensForAllocation
);
allocationToken.safeApprove(address(allocator), config.tokensForAllocation);
}
allocator.initialize(config);
venture.addAllocator(address(allocator), uint256(Types.AllocatorType.ERC20_OPTIONS_ALLOCATOR), config.tokensForAllocation);
emit ERC20OptionsAllocatorCreated(address(venture), address(allocator), Types.AllocatorType.ERC20_OPTIONS_ALLOCATOR, config, ERC20OptionsAllocatorImpl);
}
/**
* @notice Mints multiple tokens to the specified recipients.
* @param tokenAddress The address of the token contract to mint tokens from.
* @param recipients An array of addresses to receive the minted tokens.
* @param amounts An array of amounts to mint for each recipient.
*/
function bulkMintTokens(address tokenAddress, address[] memory recipients, uint256[] memory amounts) public {
require(recipients.length == amounts.length, "Each recipient must have an amount");
IJubiERC20 token = IJubiERC20(tokenAddress);
require(token.minters(msg.sender) || token.owner() == msg.sender, "Only minters can bulk mint tokens");
for (uint256 i; i < recipients.length; ++i) {
token.mint(recipients[i], amounts[i]);
}
}
/// @notice Helper to get all ventures
function getVentures() external view returns (Venture[] memory) {
return ventures;
}
/**
* @notice Updates the address of an allocator, so new Clones use it.
* @param newImpl The new address for allocator `_type`.
* @param _type Which allocator are we updating.
*/
function updateAllocatorImpl(address newImpl, Types.AllocatorType _type) external onlyOwner {
_updateAllocatorImpl(newImpl,_type);
}
/**
* @notice Updates the address of ventureImpl, so new Clones use it.
* @param newImpl The new address for allocator `_type`.
*/
function updateVentureImpl(address newImpl) external onlyOwner {
require(newImpl != address(0), "Factory: invalid address for new Impl");
require(newImpl != ventureImpl, "Factory: cannot update to same version");
ventureImpl = newImpl;
emit VentureImplUpdated(newImpl);
}
/**
* @notice Updates the address of an allocator, so new Clones use it.
* @param newImpl The new address for allocator `_type`.
* @param _type Which allocator are we updating.
*/
function _updateAllocatorImpl(address newImpl, Types.AllocatorType _type) internal {
require(newImpl != address(0), "Factory: invalid address for new Impl");
if (_type == Types.AllocatorType.NFT) {
require(newImpl != nftAllocatorImpl, "Factory: cannot update to same version");
nftAllocatorImpl = newImpl;
}
if (_type == Types.AllocatorType.ERC20_FIXED_PRICE) {
require(newImpl != ERC20FixedPriceAllocatorImpl, "Factory: cannot update to same version");
ERC20FixedPriceAllocatorImpl = newImpl;
}
if (_type == Types.AllocatorType.ERC20_MANUAL) {
require(newImpl != ERC20ManualAllocatorImpl, "Factory: cannot update to same version");
ERC20ManualAllocatorImpl = newImpl;
}
if (_type == Types.AllocatorType.ERC20_OPTIONS_ALLOCATOR) {
require(newImpl != ERC20OptionsAllocatorImpl, "Factory: cannot update to same version");
ERC20OptionsAllocatorImpl = newImpl;
}
emit AllocatorImplUpdated(newImpl, _type);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation)
internal
onlyOwner
override
{}
}
@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. 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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/interfaces/IERC1967Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*
* _Available since v4.8.3._
*/
interface IERC1967Upgradeable {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
@openzeppelin/contracts-upgradeable/interfaces/draft-IERC1822Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/Clones.sol)
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library ClonesUpgradeable {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create(0, 0x09, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create2(0, 0x09, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(add(ptr, 0x38), deployer)
mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
mstore(add(ptr, 0x14), implementation)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
mstore(add(ptr, 0x58), salt)
mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
predicted := keccak256(add(ptr, 0x43), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
}
@openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/IERC1967Upgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
AddressUpgradeable.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeTo(address newImplementation) public virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @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) {
return _status == _ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @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.
*/
interface IERC20PermitUpgradeable {
/**
* @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].
*/
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);
}
@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
/**
* @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(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, 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(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @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(IERC20Upgradeable token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @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(IERC20Upgradeable 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, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @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(IERC20Upgradeable 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))) && AddressUpgradeable.isContract(address(token));
}
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
@openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(account),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
@openzeppelin/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. 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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/proxy/Clones.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/Clones.sol)
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create(0, 0x09, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create2(0, 0x09, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(add(ptr, 0x38), deployer)
mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
mstore(add(ptr, 0x14), implementation)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
mstore(add(ptr, 0x58), salt)
mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
predicted := keccak256(add(ptr, 0x43), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @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.
*/
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].
*/
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);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../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 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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @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.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @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, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @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.isContract(address(token));
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
@openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.2) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates merkle trees that are safe
* against this attack out of the box.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Calldata version of {verify}
*
* _Available since v4.7._
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Calldata version of {processProof}
*
* _Available since v4.7._
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
*
* _Available since v4.7._
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Calldata version of {multiProofVerify}
*
* CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
*
* _Available since v4.7._
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* _Available since v4.7._
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
require(proofPos == proofLen, "MerkleProof: invalid multiproof");
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Calldata version of {processMultiProof}.
*
* CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
*
* _Available since v4.7._
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
require(proofPos == proofLen, "MerkleProof: invalid multiproof");
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
@openzeppelin/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
@openzeppelin/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
@openzeppelin/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
contracts/ERC20FixedPriceAllocator.sol
//SPDX-License-Identifier: CC-BY-NC-ND-2.5
pragma solidity 0.8.16;
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { Types } from "./Types.sol";
import { Venture } from "./Venture.sol";
import { SignatureUtil } from "./utils/SignatureValidation.sol";
/**
* @title ERC20FixedPriceAllocator
* @author Jubi
* @notice This contract allows a Venture to create a sale of Venture tokens,
* and will allocate the purchased tokens to the relevant purchase accounts according to a distribution schedule
*/
contract ERC20FixedPriceAllocator is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
/// @notice The name used to identify this Allocator in dApps
string public name;
/// @notice A description about this Allocator for dApps
string public description;
/// @notice Is the allocator open/active
bool public isOpen;
/// @notice Escrow is active/is the hurdle amount yet to be reached
bool public escrowActive;
/// @notice Has the escrow amount been claimed
bool public isEscrowClaimed;
/// @notice Token price
uint256 public tokenPrice;
/// @notice Total amount of Venture tokens that can be purchased via this allocator
uint256 public totalTokensForAllocation;
/// @notice The minimum amount of tokens that need to be purchased for the sale to be successful
uint256 public hurdle;
/// @notice The portion of a purchase that remains after fees
uint256 public ventureFunds;
/// @notice The timestamp at which the distribution schedule to release tokens for claiming, starts.
/// Typically happens after the Venture Token is minted and can be set using setVentureToken
uint256 public releaseScheduleStartTimeStamp;
/// @notice The number of seconds after starting the distribution schedule, that tokens will be locked from claiming
uint256 public tokenLockDuration;
/// @notice The duration over which tokens are released for claiming after the tokenLockDuration
uint256 public releaseDuration;
/// @notice The token accepted for purchasing the Venture Token
IERC20 public purchaseToken;
/// @notice The Venture Token that allocated for sale
IERC20 public allocationToken;
/// @notice merkle root that captures all valid invite codes
bytes32 public inviteCodesMerkleRoot;
/// @notice maps invitesCodes => wallets
mapping(bytes32 => address) public claimedInvites;
/// @notice the Venture that manages this contract
Venture public venture;
/// @notice Hashed domain separator as per EIP712
bytes32 public DOMAIN_SEPARATOR;
/// @notice Data hash of the signed terms of this allocator
bytes32 public termsHash;
/// @notice the URL where the terms of this allocator can be found
string public termsUrl;
/// @notice The signature of the token allocations terms by the venture's representative
/// signature is for ALL invite codes and the entire token allocation, and counts as counter signature for each purchase
bytes public ventureSignature;
/// @notice Tokens that have been purchased by a specific address
mapping(address => uint256) public allocation;
/// @notice Total tokens allocated/purchased from this allocator
uint256 public totalAllocationTokenAllocated;
/// @notice Amount of tokens remaining that an account is allowed to purchase given their invite codes
/// sum of allowance from cumulative invite codes - purchased tokens
mapping(address => uint256) public remainingAccountAllocationTokenAllowance;
/// @notice purchaseToken spent to purchase allocationToken by a specific address
mapping(address => uint256) public paidAmounts;
/// @notice Total purchaseToken collected by this allocator
uint256 public totalPaidAmount;
/// @notice Number of allocationToken claimed by a specific address
mapping(address => uint256) public accountClaimed;
/// @notice Total allocationToken claimed from this allocator
uint256 public totalClaimed;
/// @notice Has the hurdle been reached
bool public isHurdleReached;
/**
* @notice This event is emitted when a purchase is made
* @param account The account that purchased tokens
* @param purchaseAmount The amount of purchaseToken that was paid
* @param allocatedAmount The amount of allocationToken that will be allocated to the account
* @param purchaseSignature The signature of the terms by the purchaser
* @param ventureSignature The signature of the terms by the venture representative
*/
event Purchase(
address account,
uint256 purchaseAmount,
uint256 allocatedAmount,
bytes purchaseSignature,
bytes ventureSignature
);
/**
* @notice This event is emitted a Claim is made
* @param account The account that claimed allocationToken
* @param amount The amount that was claimed
*/
event Claimed(address account, uint256 amount);
/**
* @notice This event is emitted when an `admin` migrates the venture that manages this allocator
* from `oldVenture` to `newVenture`
* @param oldVenture The venture that is been deprecated
* @param newVenture The venture that is assigned as the new manager
* @param admin The admin account that perform the migration
*/
event VentureMigrated(
address indexed oldVenture,
address indexed newVenture,
address admin
);
/**
* @dev Emitted when an amount of tokens is claimed from the escrow by an account.
* @param amount The amount of tokens claimed.
* @param account The account that claimed the tokens.
*/
event EscrowClaimed(uint256 amount, address account);
/**
* @dev Emitted when the allocator is closed and no more allocations can be made.
* @param account The account that closed the allocator.
*/
event AllocatorClosed(address account);
/**
* @dev Emitted when the venture token address is set.
* @param ventureToken The address of the venture token.
*/
event AllocationTokenSet(address indexed ventureToken);
/**
* @dev Emitted when the hurdle is reached.
*/
event HurdleReached();
/**
* @notice This function is used to initialize the contract
* @dev PLEASE NOTE, this contract supports prices with the decimals specific to the purchase token, i.e. $USDC 1 as 1000000
* Allocation token is only supported with 18 decimals
* @param _founder The address of the founder
* @param _config The configuration for this allocator
*/
function initialize(
address _founder,
Types.ERC20FixedPriceAllocatorConfig memory _config
) external initializer {
__Ownable_init();
__ReentrancyGuard_init();
_transferOwnership(_config.venture.owner());
name = _config.name;
description = _config.description;
venture = _config.venture;
tokenPrice = _config.signatureStoreConfig.tokenPrice;
allocationToken = _config.allocationToken;
totalTokensForAllocation = _config.tokensForAllocation;
hurdle = _config.signatureStoreConfig.hurdle;
releaseScheduleStartTimeStamp = _config
.signatureStoreConfig
.releaseScheduleStartTimeStamp;
tokenLockDuration = _config.signatureStoreConfig.tokenLockDuration;
releaseDuration = _config.signatureStoreConfig.releaseDuration;
inviteCodesMerkleRoot = _config.inviteCodesMerkleRoot;
purchaseToken = _config.venture.treasuryToken();
termsHash = _config.signatureStoreConfig.termsHash;
termsUrl = _config.signatureStoreConfig.termsUrl;
bytes32 founderDomain = SignatureUtil.hashDomain( SignatureUtil.EIP712Domain({
name : name,
version : '1',
chainId : block.chainid,
verifyingContract : _founder
}));
SignatureUtil.SignatureData memory signatureData = SignatureUtil.SignatureData({
signer: _founder,
termsUrl: _config.signatureStoreConfig.termsUrl,
termsHash: _config.signatureStoreConfig.termsHash,
numTokens: _config.tokensForAllocation,
tokenPrice: _config.signatureStoreConfig.tokenPrice,
hurdle: _config.signatureStoreConfig.hurdle,
releaseScheduleStartTimeStamp: _config.signatureStoreConfig.releaseScheduleStartTimeStamp,
tokenLockDuration: _config.signatureStoreConfig.tokenLockDuration,
releaseDuration: _config.signatureStoreConfig.releaseDuration,
inviteCode: _config.signatureStoreConfig.config.inviteCode
});
bool isSignatureValid = SignatureUtil.verifySignature(founderDomain, signatureData, _config.signatureStoreConfig.config.signature);
require(isSignatureValid, "FixedPriceAllocator: Invalid signature");
ventureSignature = _config.signatureStoreConfig.config.signature;
DOMAIN_SEPARATOR = SignatureUtil.hashDomain( SignatureUtil.EIP712Domain({
name : name,
version : '1',
chainId : block.chainid,
verifyingContract : address(this)
}));
if (address(allocationToken) != address(0)) {
allocationToken.safeTransferFrom(
msg.sender,
address(this),
totalTokensForAllocation
);
}
isOpen = true;
escrowActive = true;
}
/**
* @notice This function is used to purchase allocationToken, `ventureTokenPurchaseAmount` specifying the number of tokens being purchased as long as:
* 1. The sale is open
* 2. The invite code is valid
* 3. The signature is valid
* 4. The venture token purchase amount is above the min bounds specified by their invite codes for the first purchase
* 5. The venture token purchase amount is below or equal to the remaining `remainingAccountAllocationTokenAllowance`
* 6. There is sufficient unsold allocationToken to fulfill the purchase
*
* @param ventureTokenPurchaseAmount amount of allocationToken to purchase
* @param minVentureTokenPurchase min amount of allocationToken that can be purchased specified by the invite code
* @param maxVentureTokenPurchase max amount of allocationToken that can be purchased specified by the invite code
*/
function purchase(
uint256 ventureTokenPurchaseAmount,
uint256 minVentureTokenPurchase,
uint256 maxVentureTokenPurchase,
bytes32 inviteCode,
bytes32[] calldata merkleProof,
bytes memory signature
) external nonReentrant {
/* TODO: just use msg.sender directly */
address account = msg.sender;
require(
MerkleProof.verify(
merkleProof,
inviteCodesMerkleRoot,
keccak256(
abi.encode(
inviteCode,
minVentureTokenPurchase,
maxVentureTokenPurchase
)
)
),
"FixedPriceAllocator: Invalid invite code"
);
require(
ventureTokenPurchaseAmount >= minVentureTokenPurchase ||
allocation[account] != 0,
"FixedPriceAllocator: Can not purchase less than minimum amount"
);
if (claimedInvites[inviteCode] != address(0)) {
if (claimedInvites[inviteCode] != account) {
revert(
"FixedPriceAllocator: You can only purchase with one wallet per invite code"
);
}
if (
ventureTokenPurchaseAmount >
remainingAccountAllocationTokenAllowance[account]
) {
revert(
"FixedPriceAllocator: Maximum purchase amount for invite codes exceeded"
);
}
} else {
if (
ventureTokenPurchaseAmount >
(remainingAccountAllocationTokenAllowance[account] +
maxVentureTokenPurchase)
) {
revert(
"FixedPriceAllocator: Maximum purchase amount for invite codes exceeded"
);
}
}
require(isOpen, "FixedPriceAllocator: Sale Closed");
SignatureUtil.SignatureData memory signatureData = SignatureUtil.SignatureData({
signer: msg.sender,
termsUrl: termsUrl,
termsHash: termsHash,
numTokens: ventureTokenPurchaseAmount,
tokenPrice: tokenPrice,
hurdle: hurdle,
releaseScheduleStartTimeStamp: releaseScheduleStartTimeStamp,
tokenLockDuration: tokenLockDuration,
releaseDuration: releaseDuration,
inviteCode: inviteCode
});
bool isSignatureValid = SignatureUtil.verifySignature(DOMAIN_SEPARATOR, signatureData, signature);
require(isSignatureValid, "FixedPriceAllocator: Invalid signature");
// first time using this invite code
if (claimedInvites[inviteCode] == address(0)) {
// bump remaining allocation for this wallet address (i.e. same wallet can use multiple invite codes)
remainingAccountAllocationTokenAllowance[
account
] += maxVentureTokenPurchase;
}
uint256 remainingGlobalTokenAllocation = totalTokensForAllocation -
totalAllocationTokenAllocated;
if (remainingGlobalTokenAllocation < ventureTokenPurchaseAmount) {
revert(
"FixedPriceAllocator: Insufficient tokens available for purchase"
);
}
allocation[account] += ventureTokenPurchaseAmount;
remainingAccountAllocationTokenAllowance[
account
] -= ventureTokenPurchaseAmount;
totalAllocationTokenAllocated += ventureTokenPurchaseAmount;
claimedInvites[inviteCode] = account;
if (totalAllocationTokenAllocated == totalTokensForAllocation) {
_close();
}
// the purchase tokens to transfer
uint256 purchaseTokenAmount = allocationToPurchaseToken(
ventureTokenPurchaseAmount
);
paidAmounts[account] += purchaseTokenAmount;
totalPaidAmount += purchaseTokenAmount;
if (totalAllocationTokenAllocated >= hurdle) {
SafeERC20.safeTransferFrom(
venture.treasuryToken(),
msg.sender,
venture.fundsAddress(),
purchaseTokenAmount
);
if (!isHurdleReached) {
isHurdleReached = true;
emit HurdleReached();
}
} else {
// escrow
SafeERC20.safeTransferFrom(
purchaseToken,
msg.sender,
address(this),
purchaseTokenAmount
);
}
emit Purchase(account, purchaseTokenAmount, ventureTokenPurchaseAmount, signature, ventureSignature);
}
/**
* @notice Allows a purchaser to claim tokens that have been released and not yet claimed
*/
function claim() external nonReentrant {
require(
!isOpen,
"FixedPriceAllocator: Can only claim once allocator is closed"
);
if (allocation[msg.sender] == 0)
revert(
"FixedPriceAllocator: This account has not purchased any tokens, 0 claimable"
);
if (allocationToken == purchaseToken) {
SafeERC20.safeTransfer(
allocationToken,
msg.sender,
paidAmounts[msg.sender]
);
emit Claimed(
msg.sender,
paidAmounts[msg.sender]
);
} else {
uint256 claimableAmount = calculateTotalTokensReleased(msg.sender) -
accountClaimed[msg.sender];
require(claimableAmount != 0, "FixedPriceAllocator: Nothing to claim");
accountClaimed[msg.sender] += claimableAmount;
totalClaimed += claimableAmount;
SafeERC20.safeTransfer(
allocationToken,
msg.sender,
claimableAmount
);
emit Claimed(msg.sender, claimableAmount);
}
}
/**
* @notice Transfers the amount that was held in escrow to the venture if the hurdle amount was reached
*/
function claimEscrow() external {
require(
!isEscrowClaimed,
"FixedPriceAllocator: Escrow has already been claimed"
);
require(
venture.isAdminOrAllocatorManager(msg.sender),
"FixedPriceAllocator: only allocator manager can claim escrow funds"
);
require(
totalAllocationTokenAllocated >= hurdle,
"FixedPriceAllocator: Sale has not reached hurdle"
);
uint256 escrowAmount = purchaseToken.balanceOf(address(this));
SafeERC20.safeTransfer(
venture.treasuryToken(),
venture.fundsAddress(),
escrowAmount
);
isEscrowClaimed = true;
emit EscrowClaimed(escrowAmount, msg.sender);
}
/**
* @notice Closes the allocator so that no further purchases can be made, and transfers any remaining tokens back to the venture
*/
function close() external {
require(
venture.isAdminOrAllocatorManager(msg.sender),
"FixedPriceAllocator: only allocator manager can close allocator"
);
require(
isOpen,
"FixedPriceAllocator: Allocator is already closed"
);
// If escrow amount is still held in contract, transfer to venture
uint256 remainingAllocation;
bool isAllocationTokenSet = (address(allocationToken) != address(0));
_close();
if (totalAllocationTokenAllocated >= hurdle) {
if (!isEscrowClaimed) {
uint256 escrowAmount = purchaseToken.balanceOf(address(this));
SafeERC20.safeTransfer(
venture.treasuryToken(),
venture.fundsAddress(),
escrowAmount
);
isEscrowClaimed = true;
}
remainingAllocation =
totalTokensForAllocation -
totalAllocationTokenAllocated;
// return any unsold venture tokens to venture wallet or venture contract.
if(isAllocationTokenSet){
SafeERC20.safeTransfer(
allocationToken,
venture.fundsAddress(),
remainingAllocation
);
}
} else {
remainingAllocation = totalTokensForAllocation;
// return any unsold venture tokens to venture wallet or venture contract.
if(isAllocationTokenSet){
SafeERC20.safeTransfer(
allocationToken,
venture.fundsAddress(),
remainingAllocation
);
}
// when the allocator is closed if Hurdle is NOT met set the ventureToken to purchaseToken and remove any vesting so
// funders can call claimFor to refund their initial investment
allocationToken = purchaseToken;
// This will make so allocation is claimable right away
releaseScheduleStartTimeStamp =
block.timestamp -
releaseDuration -
tokenLockDuration;
}
venture.markUnallocatedTokensReturned(address(this), remainingAllocation);
}
function _close() internal {
isOpen = false;
emit AllocatorClosed(msg.sender);
}
/**
* @notice Calculates the amount of purchased tokens that has been released according to the release schedule
* @param account The account to calculate the released amount for
*/
function calculateReleased(
address account
) public view returns (uint256 releasedAmount) {
// TODO This is true with 0 sold also
if (allocation[account] == 0)
revert(
"FixedPriceAllocator: This account has not purchased any tokens, 0 claimable"
);
if (
totalAllocationTokenAllocated == totalClaimed ||
allocation[account] == accountClaimed[account]
) {
revert("FixedPriceAllocator: All tokens have been claimed");
}
if (address(allocationToken) == address(0)) {
revert(
"FixedPriceAllocator: Allocation Token has not been set yet"
);
}
uint256 timestamp = block.timestamp;
uint256 releaseStartTimestamp = releaseScheduleStartTimeStamp +
tokenLockDuration;
if (timestamp < releaseStartTimestamp) {
return 0;
}
uint256 elapsedReleaseSeconds = timestamp - releaseStartTimestamp;
// minimum claimDuration to 1 sec to prevent /0
uint256 _releaseDuration = 1;
if (releaseDuration != 0) {
_releaseDuration = releaseDuration;
}
if (elapsedReleaseSeconds > _releaseDuration) {
return allocation[account];
}
releasedAmount =
(allocation[account] * elapsedReleaseSeconds) /
_releaseDuration;
}
/**
* @notice Sets the token address for the token that was sold and transfers the amount required to fulfill all claims to this contract
* @param _allocationToken The token that was sold using this contract, the required amount will be transferred to the contract
* @param _setReleaseScheduleStart If set to true, starts the distribution schedule
* @dev Use '_setClaimableScheduleStart' if token minting did not happen on schedule, to start the schedule since the token is now available
* @dev PLEASE NOTE, only 18 decimal tokens are supported
*/
function setAllocationToken(
IERC20 _allocationToken,
bool _setReleaseScheduleStart
) external {
require(
!isOpen,
"FixedPriceAllocator: Cannot set token while allocator is open"
);
require(
venture.isAdminOrAllocatorManager(msg.sender),
"FixedPriceAllocator: only allocator manager can set the token"
);
require(
address(allocationToken) == address(0),
"FixedPriceAllocator: Venture token already set"
);
require(
address(_allocationToken) != address(purchaseToken),
"FixedPriceAllocator: Can NOT set the claim token to purchase token"
);
require(
address(_allocationToken) != address(0),
"FixedPriceAllocator: Token address invalid"
);
SafeERC20.safeTransferFrom(
_allocationToken,
msg.sender,
address(this),
totalAllocationTokenAllocated
);
if (_setReleaseScheduleStart) {
releaseScheduleStartTimeStamp = block.timestamp;
}
allocationToken = _allocationToken;
emit AllocationTokenSet(address(_allocationToken));
}
/**
* @notice Migrates this contract from being managed by current venture to a new venture `_newVenture`
* All access control and admin rights are managed by the venture.
* @param _newVenture The new venture contract that will manage this allocator
*/
function migrateVenture(address _newVenture) external {
require(
_newVenture != address(0),
"FixedPriceAllocator: invalid new venture"
);
Venture newVenture = Venture(_newVenture);
require(
newVenture.tokenSupply() > totalTokensForAllocation,
"FixedPriceAllocator: Venture has insufficient token supply"
);
require(
newVenture != venture,
"FixedPriceAllocator: Can not update to same venture"
);
require(
venture.isAdmin(msg.sender),
"FixedPriceAllocator: only venture admin can update allocator"
);
require(
newVenture.isAdmin(msg.sender),
"FixedPriceAllocator: only venture admin can update allocator"
);
address oldVenture = address(venture);
venture = newVenture;
emit VentureMigrated(oldVenture, address(newVenture), msg.sender);
}
/**
* @notice Calculates the amount of tokens that has been released according to the release schedule
* @param account The account to calculate the released amount for
*/
function calculateTotalTokensReleased(
address account
) public view returns (uint256) {
return calculateReleased(account);
}
/**
* @notice Given an allocation amount, calculates the amount of purchase tokens.
* Also used when escrow is being returned as hurdle has not been met.
* accounts for the 18 decimals of both numbers (1e36), and then converts to decimals of purchase token.
* @param _allocation The amount of allocation tokens
*/
function allocationToPurchaseToken(
uint256 _allocation
) internal view returns (uint256) {
uint256 purchaseTokenDecimals = 10**IERC20Metadata(address(purchaseToken)).decimals();
return ((_allocation * tokenPrice * purchaseTokenDecimals) / 1e36);
}
}
contracts/ERC20ManualAllocator.sol
//SPDX-License-Identifier: CC-BY-NC-ND-2.5
pragma solidity 0.8.16;
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { Types } from "./Types.sol";
import { Venture } from "./Venture.sol";
import { SignatureUtil } from "./utils/SignatureValidation.sol";
/**
* @title ERC20MAnualAllocator
* @author Jubi
* @notice This contract allows a Venture to create an allocation of Venture tokens,
* and will allocate the tokens to the relevant accounts according to a distribution schedule
* This is a partner to ERC20FixedPriceAllocator, but assumes that contracts and funds exchange happened off-chain
* so it only manages the distribution of tokens
*/
contract ERC20ManualAllocator is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
/// @notice The name used to identify this Allocator in dApps
string public name;
/// @notice A description about this Allocator for dApps
string public description;
/// @notice Is the allocator open/active
bool public isOpen;
/// @notice Token price
uint256 public tokenPrice;
/// @notice Total amount of Venture tokens that can be allocated via this allocator
uint256 public totalTokensForAllocation;
/// @notice The timestamp at which the distribution schedule to release tokens for claiming, starts.
/// Typically happens after the Venture Token is minted and can be set using setVentureToken
uint256 public releaseScheduleStartTimeStamp;
/// @notice The number of seconds after starting the distribution schedule, that tokens will be locked from claiming
uint256 public tokenLockDuration;
/// @notice The duration over which tokens are released for claiming after the tokenLockDuration
uint256 public releaseDuration;
/// @notice The Venture Token that allocated
IERC20 public allocationToken;
/// @notice the Venture that manages this contract
Venture public venture;
/// @notice Tokens that have been allocated to a specific address
mapping(address => uint256) public allocation;
/// @notice Total tokens allocated from this allocator
uint256 public totalAllocationTokenAllocated;
/// @notice Number of allocationToken claimed by a specific address
mapping(address => uint256) public accountClaimed;
/// @notice Total allocationToken claimed from this allocator
uint256 public totalClaimed;
/**
* @notice This event is emitted when an allocation is made
* @param account The account that was allocated tokens
* @param allocatedAmount The amount of allocationToken that will be allocated to the account
*/
event TokensAllocated(
address account,
uint256 allocatedAmount
);
/**
* @notice This event is emitted a Claim is made
* @param account The account that claimed allocationToken
* @param amount The amount that was claimed
*/
event Claimed(address account, uint256 amount);
/**
* @notice This event is emitted when an `admin` migrates the venture that manages this allocator
* from `oldVenture` to `newVenture`
* @param oldVenture The venture that is been deprecated
* @param newVenture The venture that is assigned as the new manager
* @param admin The admin account that perform the migration
*/
event VentureMigrated(
address indexed oldVenture,
address indexed newVenture,
address admin
);
/**
* @dev Emitted when the allocator is closed and no more allocations can be made.
* @param account The account that closed the allocator.
*/
event AllocatorClosed(address account);
/**
* @notice This function is used to initialize the contract
* @dev PLEASE NOTE, this contract supports prices with the decimals specific to the purchase token, i.e. $USDC 1 as 1000000
* Allocation token is only supported with 18 decimals
* @param _config The configuration for this allocator
*/
function initialize(
Types.AllocatorConfig memory _config
) external initializer {
__Ownable_init();
__ReentrancyGuard_init();
_transferOwnership(_config.venture.owner());
name = _config.name;
description = _config.description;
venture = _config.venture;
tokenPrice = _config.tokenPrice;
allocationToken = _config.allocationToken;
totalTokensForAllocation = _config.tokensForAllocation;
releaseScheduleStartTimeStamp = _config.releaseScheduleStartTimeStamp;
tokenLockDuration = _config.tokenLockDuration;
releaseDuration = _config.releaseDuration;
if (address(allocationToken) != address(0)) {
allocationToken.safeTransferFrom(
msg.sender,
address(this),
totalTokensForAllocation
);
}
isOpen = true;
}
/**
* @notice This function is used to allocate allocationToken, `tokenAllocationAmount` specifying the number of tokens being allocted as long as:
* 1. The allocator is open
* 2. There is sufficient unsold allocationToken to fulfill the allocation
* @param tokenAllocationAmount The amount of allocationToken to allocate
* @param account The account that will receive the allocationToken
*/
function allocate(
uint256 tokenAllocationAmount,
address account
) external {
require(
venture.isAdminOrAllocatorManager(msg.sender),
"Allocator: only allocator manager can allocate tokens"
);
require(isOpen, "Allocator: Allocation Closed");
uint256 remainingGlobalTokenAllocation = totalTokensForAllocation -
totalAllocationTokenAllocated;
if (remainingGlobalTokenAllocation < tokenAllocationAmount) {
revert(
"Allocator: Insufficient tokens available for allocation"
);
}
_allocate(tokenAllocationAmount, account);
}
/**
* @notice This function is used to allocate allocationToken, `tokenAllocationAmount` specifying the number of tokens being allocted as long as:
* 1. The allocator is open
* 2. There is sufficient unsold allocationToken to fulfill the allocation
* @param tokenAllocationAmounts The amount of allocationToken to allocate
* @param accounts The account that will receive the allocationToken
*/
function allocateBulk(
uint256[] memory tokenAllocationAmounts,
address[] memory accounts
) external {
require(
venture.isAdminOrAllocatorManager(msg.sender),
"Allocator: only allocator manager can allocate tokens"
);
require(isOpen, "Allocator: Allocation Closed");
require(tokenAllocationAmounts.length == accounts.length, "Allocator: Each recipient must have an amount");
uint256 remainingGlobalTokenAllocation;
for (uint256 i; i < accounts.length; ++i) {
remainingGlobalTokenAllocation = totalTokensForAllocation -
totalAllocationTokenAllocated;
if (remainingGlobalTokenAllocation < tokenAllocationAmounts[i]) {
revert(
"Allocator: Insufficient tokens available for allocation"
);
}
_allocate(tokenAllocationAmounts[i], accounts[i]);
}
}
/**
* @dev This function is used to allocate allocationToken, `tokenAllocationAmount` specifying the number of tokens being allocted as long as:
* @param tokenAllocationAmount The amount of allocationToken to allocate
* @param account The account that will receive the allocationToken
*/
function _allocate(
uint256 tokenAllocationAmount,
address account
) private {
allocation[account] += tokenAllocationAmount;
totalAllocationTokenAllocated += tokenAllocationAmount;
if (totalAllocationTokenAllocated == totalTokensForAllocation) {
_close();
}
emit TokensAllocated(account, tokenAllocationAmount);
}
/**
* @notice Allows an account to claim tokens that have been released and not yet claimed
*/
function claim() external nonReentrant {
require(
!isOpen,
"Allocator: Can only claim once allocator is closed"
);
if (allocation[msg.sender] == 0){
revert(
"Allocator: This account has not been allocated tokens, 0 claimable"
);
}
uint256 claimableAmount = calculateReleased(msg.sender) -
accountClaimed[msg.sender];
require(claimableAmount != 0, "Allocator: Nothing to claim");
accountClaimed[msg.sender] += claimableAmount;
totalClaimed += claimableAmount;
SafeERC20.safeTransfer(
allocationToken,
msg.sender,
claimableAmount
);
emit Claimed(msg.sender, claimableAmount);
}
/**
* @notice Closes the allocator so that no further allocations can be made, and transfers any remaining tokens back to the venture
*/
function close() external {
require(
venture.isAdminOrAllocatorManager(msg.sender),
"Allocator: only allocator manager can close allocator"
);
require(
isOpen,
"Allocator: Allocator is already closed"
);
uint256 remainingAllocation =
totalTokensForAllocation -
totalAllocationTokenAllocated;
_close();
// return any unallocated venture tokens to venture wallet or venture contract.
if(address(allocationToken) != address(0) && remainingAllocation != 0){
SafeERC20.safeTransfer(
allocationToken,
venture.fundsAddress(),
remainingAllocation
);
}
venture.markUnallocatedTokensReturned(address(this) ,remainingAllocation);
}
function _close() internal {
isOpen = false;
emit AllocatorClosed(msg.sender);
}
/**
* @notice Calculates the amount of allocated tokens that has been released according to the release schedule
* @param account The account to calculate the released amount for
*/
function calculateReleased(
address account
) public view returns (uint256 releasedAmount) {
// TODO This is true with 0 sold also
if (allocation[account] == 0)
revert(
"Allocator: This account has not been allocated tokens, 0 claimable"
);
if (
totalAllocationTokenAllocated == totalClaimed ||
allocation[account] == accountClaimed[account]
) {
revert("Allocator: All tokens have been claimed");
}
if (address(allocationToken) == address(0)) {
revert(
"Allocator: Allocation Token has not been set yet"
);
}
uint256 timestamp = block.timestamp;
uint256 releaseStartTimestamp = releaseScheduleStartTimeStamp +
tokenLockDuration;
if (timestamp < releaseStartTimestamp) {
return 0;
}
uint256 elapsedReleaseSeconds = timestamp - releaseStartTimestamp;
// minimum claimDuration to 1 sec to prevent /0
uint256 _releaseDuration = 1;
if (releaseDuration != 0) {
_releaseDuration = releaseDuration;
}
if (elapsedReleaseSeconds > _releaseDuration) {
return allocation[account];
}
releasedAmount =
(allocation[account] * elapsedReleaseSeconds) /
_releaseDuration;
}
/**
* @notice Sets the token address for the token that was sold and transfers the amount required to fulfill all claims to this contract
* @param _allocationToken The token that was sold using this contract, the required amount will be transferred to the contract
* @param _setReleaseScheduleStart If set to true, starts the distribution schedule
* @dev Use '_setClaimableScheduleStart' if token minting did not happen on schedule, to start the schedule since the token is now available
* @dev PLEASE NOTE, only 18 decimal tokens are supported
*/
function setAllocationToken(
IERC20 _allocationToken,
bool _setReleaseScheduleStart
) external {
require(
!isOpen,
"Allocator: Cannot set token while allocator is open"
);
require(
venture.isAdminOrAllocatorManager(msg.sender),
"Allocator: only allocator manager can set the token"
);
require(
address(allocationToken) == address(0),
"Allocator: Venture token already set"
);
require(
address(_allocationToken) != address(0),
"Allocator: Token address invalid"
);
SafeERC20.safeTransferFrom(
_allocationToken,
msg.sender,
address(this),
totalAllocationTokenAllocated
);
if (_setReleaseScheduleStart) {
releaseScheduleStartTimeStamp = block.timestamp;
}
allocationToken = _allocationToken;
}
/**
* @notice Migrates this contract from being managed by current venture to a new venture `_newVenture`
* All access control and admin rights are managed by the venture.
* @param _newVenture The new venture contract that will manage this allocator
*/
function migrateVenture(address _newVenture) external {
require(
_newVenture != address(0),
"Allocator: invalid new venture"
);
Venture newVenture = Venture(_newVenture);
require(
newVenture.tokenSupply() > totalTokensForAllocation,
"Allocator: Venture has insufficient token supply"
);
require(
newVenture != venture,
"Allocator: Can not update to same venture"
);
require(
venture.isAdmin(msg.sender),
"Allocator: only venture admin can update allocator"
);
require(
newVenture.isAdmin(msg.sender),
"Allocator: only venture admin can update allocator"
);
address oldVenture = address(venture);
venture = newVenture;
emit VentureMigrated(oldVenture, address(newVenture), msg.sender);
}
}
contracts/ERC20OptionsAllocator.sol
//SPDX-License-Identifier: CC-BY-NC-ND-2.5
pragma solidity 0.8.16;
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {Types} from "./Types.sol";
import {Venture} from "./Venture.sol";
import {SignatureUtil} from "./utils/SignatureValidation.sol";
/**
* @title ERC20OptionsAllocator
* @author Jubi
* @notice This contract allows a Venture to Venture token options to addresses,
* and will allow accounts to execute options according to a vesting schedule
*/
contract ERC20OptionsAllocator is
Initializable,
OwnableUpgradeable,
ReentrancyGuardUpgradeable
{
using SafeERC20 for IERC20;
string public constant version = "1.0.0";
string public constant contractType = "ERC20OptionsAllocator";
/// @notice The name used to identify this Allocator in dApps
string public name;
/// @notice Is the allocator open/active
bool public isOpen;
/// @notice Token price in 18 decimals
uint256 public strikePrice;
/// @notice Total amount of Venture tokens that can be allocated via this allocator
uint256 public totalTokensForAllocation;
/// @notice The timestamp at which the distribution schedule to release tokens for claiming, starts.
/// Typically happens after the Venture Token is minted and can be set using setVentureToken
uint256 public vestingScheduleStartTimeStamp;
/// @notice The number of seconds after starting the distribution schedule, that tokens will be locked from claiming
uint256 public vestingCliffDuration;
/// @notice The duration over which tokens are vested, only claimable after cliff vestingCliffDuration
uint256 public vestingDuration;
/// @notice Date at which all allocations are vested
/// @dev vestingScheduleStartTimeStamp + vestingDuration
uint256 public vestingEndDateTimeStamp;
/// @notice The token accepted for purchasing the Venture Token
IERC20 public purchaseToken;
/// @notice The Venture Token that allocated
IERC20 public allocationToken;
/// @notice the Venture that manages this contract
Venture public venture;
/// @notice Tokens that have been allocated to a specific address
mapping(address => uint256) public allocation;
/// @notice A list of accounts that did not vest the entire schedule
mapping(address => uint256) public vestingStopped;
/// @notice Total tokens allocated from this allocator
uint256 public totalAllocationTokenAllocated;
/// @notice Number of allocationToken claimed by a specific address
mapping(address => uint256) public accountOptionsExercised;
/// @notice Total allocationToken claimed from this allocator
uint256 public totalClaimed;
/**
* @notice This event is emitted when an allocation is made
* @param account The account that was allocated tokens
* @param allocatedAmount The amount of allocationToken that will be allocated to the account
*/
event TokensAllocated(address account, uint256 allocatedAmount);
/**
* @dev Emitted when an account's vesting period has been terminated.
* @param account The address of the account whose vesting period has been terminated.
* @param vestingEndDate The end date of the accounts vesting period.
*/
event AccountVestingTerminated(address account, uint256 vestingEndDate);
/**
* @notice This event is emitted when an Option to purchase is executed
* @param account The account that exeuted the option
* @param amount The amount that was purchased
* @param paidAmount The cost of the purchase
*/
event OptionExecuted(address account, uint256 amount, uint256 paidAmount);
/**
* @notice This event is emitted when an `admin` migrates the venture that manages this allocator
* from `oldVenture` to `newVenture`
* @param oldVenture The venture that is been deprecated
* @param newVenture The venture that is assigned as the new manager
* @param admin The admin account that perform the migration
*/
event VentureMigrated(
address indexed oldVenture,
address indexed newVenture,
address admin
);
/**
* @dev Emitted when the allocator is closed and no more allocations can be made.
* @param account The account that closed the allocator.
*/
event AllocatorClosed(address account);
/**
* @notice This function is used to initialize the contract
* @dev This contract only supports allocation tokens with 18 decimals.
* The token price is also in 18 decimals, and will be converted to purchase token decimals via contract call
* to determine decimals
* @param _config The configuration for this allocator
*/
function initialize(
Types.AllocatorConfig memory _config
) external initializer {
__Ownable_init();
__ReentrancyGuard_init();
_transferOwnership(_config.venture.owner());
name = _config.name;
venture = _config.venture;
strikePrice = _config.tokenPrice;
allocationToken = _config.allocationToken;
purchaseToken = _config.venture.treasuryToken();
totalTokensForAllocation = _config.tokensForAllocation;
vestingScheduleStartTimeStamp = _config.releaseScheduleStartTimeStamp;
vestingCliffDuration = _config.tokenLockDuration;
vestingDuration = _config.releaseDuration;
vestingEndDateTimeStamp = vestingScheduleStartTimeStamp + vestingDuration;
if (address(allocationToken) != address(0)) {
allocationToken.safeTransferFrom(
msg.sender,
address(this),
totalTokensForAllocation
);
}
isOpen = true;
}
/**
* @notice This function is used to allocate allocationToken, `tokenAllocationAmount` specifying the number of tokens being allocted as long as:
* 1. The allocator is open
* 2. There is sufficient unsold allocationToken to fulfill the allocation
* @param tokenAllocationAmount The amount of allocationToken to allocate
* @param account The account that will receive the allocationToken
*/
function allocate(uint256 tokenAllocationAmount, address account) external {
require(
venture.isAdminOrAllocatorManager(msg.sender),
"Allocator: only allocator manager can allocate tokens"
);
require(isOpen, "Allocator: Allocation Closed");
uint256 remainingGlobalTokenAllocation = totalTokensForAllocation -
totalAllocationTokenAllocated;
if (remainingGlobalTokenAllocation < tokenAllocationAmount) {
revert("Allocator: Insufficient tokens available for allocation");
}
_allocate(tokenAllocationAmount, account);
}
/**
* @notice This function is used to allocate allocationToken, `tokenAllocationAmount` specifying the number of tokens being allocted as long as:
* 1. The allocator is open
* 2. There is sufficient unsold allocationToken to fulfill the allocation
* @param tokenAllocationAmounts The amount of allocationToken to allocate
* @param accounts The account that will receive the allocationToken
*/
function allocateBulk(
uint256[] memory tokenAllocationAmounts,
address[] memory accounts
) external {
require(
venture.isAdminOrAllocatorManager(msg.sender),
"Allocator: only allocator manager can allocate tokens"
);
require(isOpen, "Allocator: Allocation Closed");
require(
tokenAllocationAmounts.length == accounts.length,
"Allocator: Each recipient must have an amount"
);
uint256 remainingGlobalTokenAllocation = totalTokensForAllocation -
totalAllocationTokenAllocated;
for (uint256 i; i < accounts.length; ++i) {
if (remainingGlobalTokenAllocation < tokenAllocationAmounts[i]) {
revert(
"TokenAllocator: Insufficient tokens available for allocation"
);
}
remainingGlobalTokenAllocation -= tokenAllocationAmounts[i];
_allocate(tokenAllocationAmounts[i], accounts[i]);
}
}
/**
* @dev This function is used to allocate allocationToken, `tokenAllocationAmount` specifying the number of tokens being allocted as long as:
* @param tokenAllocationAmount The amount of allocationToken to allocate
* @param account The account that will receive the allocationToken
*/
function _allocate(uint256 tokenAllocationAmount, address account) private {
allocation[account] += tokenAllocationAmount;
totalAllocationTokenAllocated += tokenAllocationAmount;
if (totalAllocationTokenAllocated == totalTokensForAllocation) {
_close();
}
emit TokensAllocated(account, tokenAllocationAmount);
}
/**
* @notice Stop vesting for an account
* @param account The account to stop vesting for
*/
function terminateVesting(address account) external {
require(
venture.isAdminOrAllocatorManager(msg.sender),
"Allocator: only allocator manager"
);
require(
allocation[account] != 0,
"Allocator: Account has no allocation"
);
require(
vestingEndDateTimeStamp > block.timestamp,
"Allocator: Vesting period ended"
);
require(
vestingStopped[account] == 0,
"Allocator: Vesting already terminated"
);
vestingStopped[account] = block.timestamp;
emit AccountVestingTerminated(account, block.timestamp);
if (address(allocationToken) != address(0)) {
SafeERC20.safeTransfer(
allocationToken,
venture.fundsAddress(),
calculateWillNotVest(account)
);
}
venture.markUnallocatedTokensReturned(
address(this),
calculateWillNotVest(account)
);
}
/**
* @notice Allows an account to execute the vested options to purchase tokens
*/
function executeOption() external nonReentrant {
if (address(allocationToken) == address(0)) {
revert("Allocator: Allocation Token has not been set yet");
}
if (allocation[msg.sender] == 0) {
revert("Allocator: Account not allocated tokens");
}
if (allocation[msg.sender] == accountOptionsExercised[msg.sender]) {
revert("Allocator: All options executed");
}
uint256 releasedAmount = calculateVested(msg.sender) -
accountOptionsExercised[msg.sender];
require(releasedAmount != 0, "Allocator: No options available");
accountOptionsExercised[msg.sender] += releasedAmount;
totalClaimed += releasedAmount;
SafeERC20.safeTransferFrom(
purchaseToken,
msg.sender,
venture.fundsAddress(),
allocationToPurchaseToken(releasedAmount)
);
SafeERC20.safeTransfer(allocationToken, msg.sender, releasedAmount);
emit OptionExecuted(msg.sender, releasedAmount, allocationToPurchaseToken(releasedAmount));
}
/**
* @notice Closes the allocator so that no further allocations can be made, and transfers any remaining tokens back to the venture
*/
function close() external {
require(
venture.isAdminOrAllocatorManager(msg.sender),
"Allocator: only allocator manager can close allocator"
);
require(isOpen, "Allocator: Allocator is already closed");
uint256 remainingAllocation = totalTokensForAllocation -
totalAllocationTokenAllocated;
_close();
// return any unallocated venture tokens to venture wallet or venture contract.
if (address(allocationToken) != address(0)) {
SafeERC20.safeTransfer(
allocationToken,
venture.fundsAddress(),
remainingAllocation
);
}
venture.markUnallocatedTokensReturned(
address(this),
remainingAllocation
);
}
function _close() internal {
isOpen = false;
emit AllocatorClosed(msg.sender);
}
/**
* @notice Calculates the amount of allocated tokens that has been vested according to the vesting schedule
* @param account The account to calculate the vested amount for
*/
function calculateVested(
address account
) public view returns (uint256 releasedAmount) {
uint256 vestingTimestamp = block.timestamp;
if (vestingStopped[account] != 0) {
vestingTimestamp = vestingStopped[account];
}
return calculateVestedAt(account, vestingTimestamp);
}
/**
* @notice Calculates the amount of tokens that will be released at a specific timestamp for an account
* @param account The account to calculate the released amount for
* @param timestamp The timestamp to calculate the released amount at
*/
function calculateVestedAt(
address account,
uint256 timestamp
) public view returns (uint256 vestedAmount) {
uint256 vestingStartTimestamp = vestingScheduleStartTimeStamp +
vestingCliffDuration;
if (timestamp <= vestingStartTimestamp) {
return 0;
}
uint256 elapsedReleaseSeconds = timestamp -
vestingScheduleStartTimeStamp;
// minimum claimDuration to 1 sec to prevent /0
uint256 _vestingDuration = 1;
if (vestingDuration != 0) {
_vestingDuration = vestingDuration;
}
if (elapsedReleaseSeconds > _vestingDuration) {
return allocation[account];
}
return (allocation[account] * elapsedReleaseSeconds) / _vestingDuration;
}
/**
* @notice Calculates the amount of allocated tokens that will never vest
* @param account The account to calculate the unvested amount for
*/
function calculateWillNotVest(
address account
) public view returns (uint256 unvestedAmount) {
if (allocation[account] == 0) {
revert("Allocator: Account has not been allocated tokens");
}
if (
vestingStopped[account] == 0 ||
vestingStopped[account] >= vestingEndDateTimeStamp
) {
return 0;
}
// If vesting stopped before cliff, then all tokens are forfeit
if (
vestingStopped[account] <
vestingScheduleStartTimeStamp + vestingCliffDuration
) {
return allocation[account];
}
return
allocation[account] -
calculateVestedAt(account, vestingStopped[account]);
}
/**
* @notice Sets the token address for the token that was sold and transfers the amount required to fulfill all claims to this contract
* @param _allocationToken The token that was sold using this contract, the required amount will be transferred to the contract
* @dev Use '_setClaimableScheduleStart' if token minting did not happen on schedule, to start the schedule since the token is now available
*/
function setAllocationToken(IERC20 _allocationToken) external {
require(
venture.isAdminOrAllocatorManager(msg.sender),
"Allocator: only allocator manager can set the token"
);
require(
address(allocationToken) == address(0),
"Allocator: Venture token already set"
);
require(
address(_allocationToken) != address(0),
"Allocator: Token address invalid"
);
if (isOpen) {
SafeERC20.safeTransferFrom(
_allocationToken,
msg.sender,
address(this),
totalTokensForAllocation
);
} else {
SafeERC20.safeTransferFrom(
_allocationToken,
msg.sender,
address(this),
totalAllocationTokenAllocated
);
}
allocationToken = _allocationToken;
}
/**
* @notice Migrates this contract from being managed by current venture to a new venture `_newVenture`
* All access control and admin rights are managed by the venture.
* @param _newVenture The new venture contract that will manage this allocator
*/
function migrateVenture(address _newVenture) external {
require(_newVenture != address(0), "Allocator: invalid new venture");
Venture newVenture = Venture(_newVenture);
require(
newVenture.tokenSupply() > totalTokensForAllocation,
"Allocator: Venture has insufficient token supply"
);
require(
newVenture != venture,
"Allocator: Can not update to same venture"
);
require(
venture.isAdmin(msg.sender),
"Allocator: only venture admin can update allocator"
);
require(
newVenture.isAdmin(msg.sender),
"Allocator: only venture admin can update allocator"
);
address oldVenture = address(venture);
venture = newVenture;
emit VentureMigrated(oldVenture, address(newVenture), msg.sender);
}
/**
* @notice Calculates the amount of purchase token required to purchase the given allocation of options.
* @dev calculates the number of purchase tokens, accounts for the 18 decimals of both numbers, and then converts to decimals of purchase token.
* @param _allocation The allocation of options to be purchased.
* @return The amount of purchase token required to purchase the given allocation of options.
*/
function allocationToPurchaseToken(
uint256 _allocation
) internal view returns (uint256) {
uint256 purchaseTokenDecimals = 10 **
IERC20Metadata(address(purchaseToken)).decimals();
return ((_allocation * strikePrice * purchaseTokenDecimals) / 1e36);
}
}
contracts/NftAllocator.sol
//SPDX-License-Identifier: CC-BY-NC-ND-2.5
pragma solidity 0.8.16;
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { ERC721A, ERC721A__IERC721Receiver, IERC721A } from "erc721a/contracts/ERC721A.sol";
import { Types } from "./Types.sol";
import { Venture } from "./Venture.sol";
import { SignatureUtil } from "./utils/SignatureValidation.sol";
/**
* @title NftAllocator
* @notice With this contract you can invest and claim a nft
*/
contract NftAllocator is Initializable, OwnableUpgradeable, ERC721A__IERC721Receiver, ReentrancyGuardUpgradeable {
struct TokensAllocated {
/// @notice the account that claimed the tokens
address account;
/// @notice the amount of tokens allocation claimed
uint256 claimed;
/// @notice the amount of tokens allocation unclaimed
uint256 unclaimed;
}
/// @notice The address where Jubi fees will be sent
address public jubiFundsAddress;
/// @notice The Jubi fee amount
uint256 public jubiFee;
/// @notice The funds a venture will get per investment
uint256 public ventureFunds;
/// @notice which nft investors will be claiming
IERC721A public nft;
/// @notice the Venture that manages this contract
Venture public venture;
/// @notice The name used to identify this Allocator in Dapps
string public name;
/// @notice Is the allocator open
bool public isOpen;
/// @notice price to pay for nft
uint256 public nftPrice;
/// @notice max number of nft to sale
uint256 public tokensForAllocation;
/// @notice merkle root that captures all valid invite codes
bytes32 public inviteCodesMerkleRoot;
/// @notice Hashed domain separator as per EIP721
bytes32 public DOMAIN_SEPARATOR;
/// @notice Data hash of the signed terms of this allocator
bytes32 public termsHash;
/// @notice the URL where the terms of this allocator can be found
string public termsUrl;
/// @notice The signature of the token allocations terms by the venture's representative
/// signature is for ALL invite codes and the entire token allocation, and counts as counter signature for each purchase
bytes public ventureSignature;
/// @notice maps invitesCodes => TokensAllocated
mapping(bytes32 => TokensAllocated) public invitesAllocation;
/// @notice all address in this mapping have invested in this allocator, No is the number of active claims in this allocator
mapping(address => uint256) public pendingClaims;
/// @notice number of investors
uint256 public investmentsCount;
/// @notice number of investors which have NOT collected their nft
uint256 public totalUnclaimed;
/// @notice A list of tokenIds received by this contract
mapping(uint256 => uint256) public tokenIds;
/// @notice The total of `tokenIds`
uint256 public tokenIdsLength;
/// @notice The next token id from `tokenIds` to be claimed
uint256 public nextTokenId;
/**
* @notice This event is emitted an investment is made
* @param account The account that invested
* @param investment The amount that was invested
*/
event Investment(address indexed account, uint256 investment, uint256 numTokens, bytes signature, bytes ventureSignature);
/**
* @notice This event is emitted after an nft was claimed
* @param account The account that claimed
* @param tokenId The nft id that was claimed
*/
event Claimed(address indexed account, uint256 indexed tokenId);
/**
* @notice This event is emitted after an investment and no nft where available for claim
* @param account The account that invested
* @param ventureFunds The amount that are hold by this contract until NFt is claimed
* @param pending The number of pending claims added to `account`
*/
event PendingClaim(address indexed account, uint256 ventureFunds, uint256 pending);
/**
* @notice This event is emitted a nft is transferred to this contract
* @param tokenId The transferred nft tokenId
*/
event NftReceived(uint256 indexed tokenId);
/**
* @notice This event is emitted when an `admin` migrates the venture that manages this allocator
* from `oldVenture` to `newVenture`
* @param oldVenture The venture that is been deprecated
* @param newVenture The venture that is assigned as the new manager
* @param admin The admin account that perform the migration
*/
event VentureMigrated(address indexed oldVenture, address indexed newVenture, address admin);
/**
* @dev Emitted when the allocator is closed.
* @param account The account that closed the allocator.
*/
event AllocatorClosed(address account);
/**
* @dev Emitted when an NFT contract is set for an account.
* @param nft The address of the NFT contract.
* @param account The address of the account.
*/
event NFTSet(address nft, address account);
/**
* @notice Initializes a NftAllocator with `config`.
* @param _jubiFundsAddress The address where Jubi funds will be sent
* @param _jubiFeePercent The fee Jubi will be charging
* @param _config The config to initialize the NftAllocator
*/
function initialize(address _jubiFundsAddress, Types.Fraction memory _jubiFeePercent, Types.NftAllocatorConfig memory _config, address _founder) external initializer {
__Ownable_init();
__ReentrancyGuard_init();
_transferOwnership(_config.venture.owner());
jubiFundsAddress = _jubiFundsAddress;
nft = _config.nft;
venture = _config.venture;
nftPrice = _config.nftPrice;
tokensForAllocation = _config.tokensForAllocation;
inviteCodesMerkleRoot = _config.inviteCodesMerkleRoot;
jubiFee = nftPrice * _jubiFeePercent.num / _jubiFeePercent.den;
ventureFunds = nftPrice - jubiFee;
isOpen = true;
name = _config.name;
bytes32 founderDomain = SignatureUtil.hashDomain( SignatureUtil.EIP712Domain({
name : name,
version : '1',
chainId : block.chainid,
verifyingContract : _founder
}));
SignatureUtil.SignatureData memory signatureData = SignatureUtil.SignatureData({
signer: _founder,
termsUrl: _config.signatureStore.termsUrl,
termsHash: _config.signatureStore.termsHash,
numTokens: _config.tokensForAllocation,
tokenPrice: _config.nftPrice,
hurdle: 0,
releaseScheduleStartTimeStamp: 0,
tokenLockDuration: 0,
releaseDuration: 0,
inviteCode: _config.signatureStore.config.inviteCode
});
bool isSignatureValid = SignatureUtil.verifySignature(founderDomain, signatureData, _config.signatureStore.config.signature);
require(isSignatureValid, "NFTAllocator: Invalid signature");
termsUrl = _config.signatureStore.termsUrl;
termsHash = _config.signatureStore.termsHash;
ventureSignature = _config.signatureStore.config.signature;
DOMAIN_SEPARATOR = SignatureUtil.hashDomain( SignatureUtil.EIP712Domain({
name : name,
version : '1',
chainId : block.chainid,
verifyingContract : address(this)
}));
}
/**
* @notice Makes an investment in this allocator
* @param numTokens The number of tokens to invest
* @param inviteCode The invite code to access this investment
* @param merkleProof The proof to verify the invite code `inviteCode` is correct
*
* Emits a {Investment} event.
* May emit a {Claimed} event.
* May emit a {PendingClaim} event.
*/
function invest(uint256 numTokens, uint256 minAllowedTokens, uint256 maxAllowedTokens, bytes32 inviteCode, bytes32[] calldata merkleProof, bytes memory signature) external nonReentrant {
require(tokensForAllocation > investmentsCount, "NftAllocator: Closed, goal reached");
require(tokensForAllocation >= investmentsCount + numTokens, "NftAllocator: Investment will exceed tokens allocation");
require(numTokens != 0, "NftAllocator: min 1 token to invest");
require(MerkleProof.verify(merkleProof, inviteCodesMerkleRoot, keccak256(abi.encode(inviteCode, minAllowedTokens, maxAllowedTokens))), "NftAllocator: Invalid invite code");
require(invitesAllocation[inviteCode].account == msg.sender || invitesAllocation[inviteCode].account == address(0), "NftAllocator: only one wallet per invite code");
require(numTokens >= minAllowedTokens || (invitesAllocation[inviteCode].claimed + invitesAllocation[inviteCode].unclaimed) >= minAllowedTokens, "NftAllocator: can not invest less than minimum");
require(numTokens <= maxAllowedTokens && (invitesAllocation[inviteCode].claimed + invitesAllocation[inviteCode].unclaimed + numTokens) <= maxAllowedTokens, "NftAllocator: can not invest more than maximum");
require(isOpen, "NftAllocator: Closed");
invitesAllocation[inviteCode].account = msg.sender;
totalUnclaimed += numTokens;
//TODO allow hurdle and schedule for NFTs
SignatureUtil.SignatureData memory signatureData = SignatureUtil.SignatureData({
signer: msg.sender,
termsUrl: termsUrl,
termsHash: termsHash,
numTokens: numTokens,
tokenPrice: nftPrice,
hurdle: 0,
releaseScheduleStartTimeStamp: 0,
tokenLockDuration: 0,
releaseDuration: 0,
inviteCode: inviteCode
});
bool isSignatureValid = SignatureUtil.verifySignature(DOMAIN_SEPARATOR, signatureData, signature);
require(isSignatureValid, "NFTAllocator: Invalid signature");
if (address(nft) != address(0) && nft.balanceOf(address(this)) >= totalUnclaimed && (tokenIdsLength - nextTokenId) >= numTokens) {
totalUnclaimed -= numTokens;
invitesAllocation[inviteCode].claimed += uint128(numTokens);
for (uint256 i; i < numTokens;) {
nft.safeTransferFrom(address(this), msg.sender, tokenIds[nextTokenId]);
emit Claimed(msg.sender, tokenIds[nextTokenId]);
unchecked {
i++;
nextTokenId++;
}
}
} else {
pendingClaims[msg.sender] += numTokens;
invitesAllocation[inviteCode].unclaimed += numTokens;
emit PendingClaim(msg.sender, ventureFunds, numTokens);
}
investmentsCount += numTokens;
SafeERC20.safeTransferFrom(venture.treasuryToken(), msg.sender, venture.fundsAddress(), ventureFunds * numTokens);
SafeERC20.safeTransferFrom(venture.treasuryToken(), msg.sender, jubiFundsAddress, jubiFee * numTokens);
emit Investment(msg.sender, nftPrice * numTokens, numTokens, signature, ventureSignature);
}
/**
* @notice Claims a nft with id `tokenId`
* @param numToClaim The number of token to be claim by `msg.sender`
* Emits a {Claimed} event.
*/
function claim(uint256 numToClaim) external nonReentrant {
require(address(nft) != address(0), "NftAllocator: No nft token assigned to allocator");
require(numToClaim != 0, "NftAllocator: min 1 token to claim");
require(pendingClaims[msg.sender] != 0, "NftAllocator: no active claim");
require(pendingClaims[msg.sender] >= numToClaim, "NftAllocator: trying to claim more than allowed");
uint256 contractNftBalance = nft.balanceOf(address(this));
require(contractNftBalance >= totalUnclaimed, "NftAllocator: Not enough claimable nft");
totalUnclaimed -= numToClaim;
pendingClaims[msg.sender] -= numToClaim;
for (uint256 i; i < numToClaim;) {
nft.safeTransferFrom(address(this), msg.sender, tokenIds[nextTokenId]);
emit Claimed(msg.sender, tokenIds[nextTokenId]);
unchecked {
i++;
nextTokenId++;
}
}
}
/**
* @notice Closes this allocator, as consequence investments are DISABLED
*/
function close() external {
require(venture.isAdminOrAllocatorManager(msg.sender), "NftAllocator: only allocator manager can close allocator");
isOpen = false;
emit AllocatorClosed(msg.sender);
}
/**
* @notice Sets the nft to `_nft`. Can only be called once.
*/
function setNft(IERC721A _nft) external {
require(venture.isAdminOrAllocatorManager(msg.sender), "NftAllocator: only allocator manager can set nft");
require(address(nft) == address(0), "NftAllocator: Token is already set");
require(address(_nft) != address(0), "NftAllocator: Token address invalid");
nft = _nft;
emit NFTSet(address(_nft), msg.sender);
}
/**
* @notice Migrates current venture to a new venture manager `_newVenture`
* @param _newVenture The new venture manager for this allocator
*/
function migrateVenture(address _newVenture) external {
require(_newVenture != address(0), "NftAllocator: invalid new venture");
Venture newVenture = Venture(_newVenture);
require(newVenture != venture, "NftAllocator: Can not update to same venture");
require(venture.isAdmin(msg.sender), "NftAllocator: only venture admin can update allocator");
require(newVenture.isAdmin(msg.sender), "NftAllocator: only venture admin can update allocator");
address oldVenture = address(venture);
venture = newVenture;
emit VentureMigrated(oldVenture, address(newVenture), msg.sender);
}
function onERC721Received(
address,
address,
uint256 tokenId,
bytes calldata
) override external returns (bytes4) {
require(msg.sender == address(nft), "NftAllocator: Invalid nft received");
emit NftReceived(tokenId);
tokenIds[tokenIdsLength] = tokenId;
unchecked {tokenIdsLength++;}
return ERC721A__IERC721Receiver.onERC721Received.selector;
}
}
contracts/Types.sol
//SPDX-License-Identifier: CC-BY-NC-ND-2.5
pragma solidity 0.8.16;
import { SafeERC20,IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ERC721A } from "erc721a/contracts/ERC721A.sol";
import { Venture } from "./Venture.sol";
library Types {
struct VentureConfig {
address fundsAddress;
IERC20 ventureToken;
IERC20 treasuryToken;
uint256 tokenSupply;
string name;
string site;
string logoUrl;
string description;
}
struct NftAllocatorConfig {
ERC721A nft;
Venture venture;
string name;
uint256 nftPrice;
uint256 tokensForAllocation;
bytes32 inviteCodesMerkleRoot;
string merkleTreeId;
SignatureStoreNftAllocatorInitialConfig signatureStore;
}
// TODO: this can now be collapsed into a single struct for both NFT and ERC20
struct SignatureStoreNftAllocatorInitialConfig {
string termsUrl;
bytes32 termsHash;
uint256 hurdle;
uint256 releaseScheduleStartTimeStamp;
uint256 tokenLockDuration;
uint256 releaseDuration;
SignatureStoreNftAllocator config;
}
struct SignatureStoreNftAllocator {
bytes signature;
bytes32 inviteCode;
uint256 numTokens;
}
struct ERC20FixedPriceAllocatorConfig {
Venture venture;
string name;
string description;
IERC20 allocationToken;
uint256 tokensForAllocation;
bytes32 inviteCodesMerkleRoot;
string merkleTreeId;
ERC20FixedPriceAllocatorSignatureInitialConfig signatureStoreConfig;
}
struct ERC20FixedPriceAllocatorSignatureInitialConfig {
string termsUrl;
bytes32 termsHash;
uint256 tokenPrice;
uint256 hurdle;
uint256 releaseScheduleStartTimeStamp;
uint256 tokenLockDuration;
uint256 releaseDuration;
ERC20FixedPriceAllocatorSignatureConfig config;
}
struct ERC20FixedPriceAllocatorSignatureConfig {
bytes signature;
uint256 numTokens;
bytes32 inviteCode;
}
struct AllocatorConfig {
Venture venture;
string name;
string description;
IERC20 allocationToken;
uint256 tokensForAllocation;
uint256 tokenPrice;
uint256 releaseScheduleStartTimeStamp;
uint256 tokenLockDuration;
uint256 releaseDuration;
}
struct TokenConfig {
string name;
string symbol;
address owner;
address[] minterburners;
}
enum AllocatorType {
NFT,
ERC20_FIXED_PRICE,
ERC20_MANUAL,
ERC20_OPTIONS_ALLOCATOR
}
enum ImplementationType {
VENTURE,
NFT_ALLOCATOR,
ERC20_FIXED_PRICE_ALLOCATOR,
ERC20_ULTIMATE_TOKEN,
ERC20_GOVERNANCE_TOKEN,
ERC20_BASIC_TOKEN,
ERC20_OPTIONS_ALLOCATOR
}
struct Fraction {
uint128 num;
uint128 den;
}
}
contracts/Venture.sol
//SPDX-License-Identifier: CC-BY-NC-ND-2.5
pragma solidity 0.8.16;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {Types} from "./Types.sol";
/**
* @title Venture
* @notice You can use this Contract to manage your venture
*/
contract Venture is Ownable, Initializable, AccessControl {
using SafeERC20 for IERC20;
/// @notice The address to send the venture Funds
address public fundsAddress;
/// @notice The Token this venture will give for investments
IERC20 public ventureToken;
/// @notice The Token this venture will accept as investments
IERC20 public treasuryToken;
/// @notice The total Token supply, only to be used whilst the token is not minted
/// @notice The total Token supply, only to be used whilst the token is not minted
uint256 public tokenSupply;
/// @notice Total tokens allocated using all allocators per token
/// @dev ventureToken allocation is stored against venterToken address
mapping(address => uint256) totalTokensAllocated;
/// @notice The venture name
string public name;
/// @notice The venture site
string public site;
/// @notice The venture logoUrl
string public logoUrl;
/// @notice The venture description
string public description;
/// @notice A list of allocators this venture manages
address[] public allocators;
/// @notice A mapping of allocator => AllocatorType
mapping(address => uint256) public allocatorType;
/// @dev Admin role has access to all actions
bytes32 public constant ADMIN = keccak256("ADMIN");
/// @dev Allocator manager can manage allocators
bytes32 public constant ALLOCATOR_MANAGER = keccak256("ALLOCATOR_MANAGER");
/// @dev Allocator attacher can attach allocators
bytes32 public constant ALLOCATOR_ATTACHER = keccak256("ALLOCATOR_ATTACHER");
/**
* @notice This event is emitted when an Allocator(`allocator`) is added to this venture, of type `allocatorType`.
* @param allocator The allocator that was added.
* @param allocatorType The type of allocator that was added
* @param tokensAllocated The total tokens allocated by this allocator
*/
event AllocatorAdded(address indexed allocator, uint256 allocatorType, uint256 tokensAllocated);
/**
* @notice This event is emitted when an Allocator(`allocator`) is closed, and unallocated tokens have been returned to the venture wallet (fundsAddress).
* @param allocator The allocator that was added.
* @param tokensReturned The number of tokens not allocated by this allocator and returned to the venture wallet (fundsAddress)
*/
event UnallocatedTokensReturned(address indexed allocator, uint256 tokensReturned);
/**
* @dev Emitted when the venture token address is set.
* @param ventureToken The address of the venture token.
*/
event VentureTokenSet(address indexed ventureToken);
/**
* @dev Emitted when the venture token supply is set.
* @param tokenSupply The total supply of the venture token.
*/
event VentureTokenSupplySet(uint256 tokenSupply);
/**
* @notice Initializes a venture with `config`, it also sets the owner,
* a manager, and the factory as an allocator manager
* @dev PLEASE NOTE, this contract supports prices with the decimals specific to the purchase token, i.e. $USDC 1 as 1000000
* Allocation token is only supported with 18 decimals
* @param config The config to initialize the Venture
*/
function initialize(Types.VentureConfig memory config, address _creator) external initializer {
// Ownable
_transferOwnership(config.fundsAddress);
// AccessControl
_grantRole(DEFAULT_ADMIN_ROLE, config.fundsAddress);
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(DEFAULT_ADMIN_ROLE, _creator);
_addAdmin(config.fundsAddress);
_addAdmin(msg.sender);
_addAdmin(_creator);
_addAllocatorAttacher(msg.sender);
_revokeRole(ADMIN, msg.sender);
_revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
// Initializable
fundsAddress = config.fundsAddress;
ventureToken = config.ventureToken;
treasuryToken = config.treasuryToken;
// TODO make this work.
// require(config.ventureToken.totalSupply() == tokenSupply || address(ventureToken) == address(0), "Venture: Token has insufficient supply");
tokenSupply = config.tokenSupply;
name = config.name;
site = config.site;
logoUrl = config.logoUrl;
description = config.description;
// emit ManagerAdded(_creator);
}
/**
* @notice Adds an allocator: `newAllocator` of type: `_type` to this venture
* @param _newAllocator The address of the allocator to be added
* @param _allocatorType The type of allocator
*/
function addAllocator(address _newAllocator, uint256 _allocatorType, uint256 _tokensForAllocation) external {
require(_isAdminOrAllocatorManager(msg.sender) || _isAllocatorAttacher(msg.sender), "Venture: Only Admin or Manager or Attacher");
require(_newAllocator != address(0), "Venture: Allocator address invalid");
require(_tokensForAllocation != 0, "Venture: Allocator tokens invalid");
allocators.push(_newAllocator);
allocatorType[_newAllocator] = _allocatorType;
totalTokensAllocated[_newAllocator] = totalTokensAllocated[_newAllocator] + _tokensForAllocation;
emit AllocatorAdded(_newAllocator, _allocatorType, _tokensForAllocation);
}
/**
* @notice Marks the unallocated tokens returned by the allocator.
* @dev It is expected that this function only ever gets called by an allocator.
* @param _allocator The address of the allocator.
* @param _tokensReturned The number of tokens returned.
*/
function markUnallocatedTokensReturned(address _allocator, uint256 _tokensReturned) external {
require(msg.sender == owner() || totalTokensAllocated[_allocator] != 0, "Venture: invalid venture allocator or owner");
require(_tokensReturned != 0, "Venture: Tokens returned invalid");
require(_allocator != address(0), "Venture: Allocator address invalid");
totalTokensAllocated[_allocator] = totalTokensAllocated[_allocator] - _tokensReturned;
emit UnallocatedTokensReturned(_allocator, _tokensReturned);
}
/**
* @notice Sets the ventureToken to `_ventureToken`. Can only be called once.
*/
function setVentureToken(IERC20 _ventureToken) external onlyAdmin {
require(address(ventureToken) == address(0), "Venture: Token is already set");
require(address(_ventureToken) != address(0), "Venture: Token address invalid");
require(_ventureToken.totalSupply() == tokenSupply || tokenSupply == 0, "Venture: Token does not meet supply requirements");
require(_ventureToken.totalSupply() != 0, "Venture: Insufficient token supply");
ventureToken = _ventureToken;
emit VentureTokenSet(address(_ventureToken));
}
/**
* @notice Sets the tokenSupply to `_ventureToken`. Can only be called once.
*/
function setVentureTokenSupply(uint256 _tokenSupply) external onlyAdmin {
require(tokenSupply == 0, "Venture: Token Supply is already set");
tokenSupply = _tokenSupply;
emit VentureTokenSupplySet(_tokenSupply);
}
/// @notice Helper to get all allocators
function getAllocators() external view returns (address[] memory) {
return allocators;
}
function addAdmin(address _newAdmin) external virtual onlyOwner {
_addAdmin(_newAdmin);
}
function removeAdmin(address _oldAdmin) external virtual onlyOwner {
_removeAdmin(_oldAdmin);
}
function addAllocatorManager(address newAllocatorManager) external virtual onlyAdmin {
_addAllocatorManager(newAllocatorManager);
}
function removeAllocatorManager(address oldAllocatorManager) external virtual onlyAdmin {
_removeAllocatorManager(oldAllocatorManager);
}
/// @notice Checks if `maybeAdmin` is an Admin
/// @return true if `maybeAdmin` has ADMIN role
function isAdmin(address maybeAdmin) external virtual view returns (bool) {
return hasRole(ADMIN, maybeAdmin);
}
/// @notice Checks if `maybeAllocatorManager` is an Admin OR Allocator Manager
/// @return true if `maybeAllocatorManager` has ADMIN || ALLOCATOR_MANAGER role
function isAdminOrAllocatorManager(address maybeAllocatorManager) external virtual view returns (bool) {
return _isAdminOrAllocatorManager(maybeAllocatorManager);
}
function _isAdminOrAllocatorManager(address maybeAllocatorManager) internal view returns (bool) {
return hasRole(ADMIN, maybeAllocatorManager) || hasRole(ALLOCATOR_MANAGER, maybeAllocatorManager);
}
function _isAllocatorAttacher(address maybeAllocatorAttacher) internal view returns (bool) {
return hasRole(ALLOCATOR_ATTACHER, maybeAllocatorAttacher);
}
/// @notice Revokes ADMIN role from `newAdmin`
function _removeAdmin(address oldAdmin) private {
revokeRole(ADMIN, oldAdmin);
}
/// @notice Grants ADMIN role to `newAdmin`
function _addAdmin(address newAdmin) private {
grantRole(ADMIN, newAdmin);
}
/// @notice Grants ALLOCATOR_MANAGER role to `newAllocatorManager`
function _addAllocatorManager(address newAllocatorManager) private {
grantRole(ALLOCATOR_MANAGER, newAllocatorManager);
}
/// @notice Revokes ALLOCATOR_MANAGER role from `newAllocatorManager`
function _removeAllocatorManager(address oldAllocatorManager) private {
revokeRole(ALLOCATOR_MANAGER, oldAllocatorManager);
}
/// @notice Grants ALLOCATOR_ATTACHER role to `newAllocatorAttacher`
function _addAllocatorAttacher(address newAllocatorAttacher) private {
grantRole(ALLOCATOR_ATTACHER, newAllocatorAttacher);
}
/// @notice Revokes ALLOCATOR_ATTACHER role from `newAllocatorAttacher`
function _removeAllocatorAttacher(address oldAllocatorAttacher) private {
revokeRole(ALLOCATOR_ATTACHER, oldAllocatorAttacher);
}
modifier onlyAdmin() {
require(hasRole(ADMIN, msg.sender), "Venture: Restricted to Admin Role");
_;
}
}
contracts/interfaces/IJubiERC20.sol
// SPDX-License-Identifier: CC-BY-NC-ND-2.5
pragma solidity 0.8.16;
interface IJubiERC20 {
function minters(address account) external view returns (bool);
function owner() external view returns (address);
function pause() external;
function unpause() external;
function setMinter(address account, bool canMint) external;
function mint(address to, uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function burn(uint256 amount) external;
function recoverERC20(address tokenAddress, address toAddress, uint256 tokenAmount) external;
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function getCurrentVotes(address account) external view returns (uint256);
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256);
function snapshot() external returns (uint256);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function transferOwnership(address newOwner) external;
}contracts/utils/SignatureValidation.sol
// SPDX-License-Identifier: CC-BY-NC-ND-2.5
pragma solidity 0.8.16;
library SignatureUtil {
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
struct SignatureData {
/// @notice The wallet that signed the message
address signer;
/// @notice location of the unhashed (full) data version
string termsUrl;
/// @notice hashed version of the terms url content
bytes32 termsHash;
/// @notice number of tokens to purchase (founder: number of tokens to allocate)
uint256 numTokens;
/// @notice Price (number of treasury type tokens e.g. $USDC) per sale token
uint256 tokenPrice;
/// @notice minimum tokens to be purchased for the sale to be successful
uint256 hurdle;
/// @notice the date at which the token is expected to be minted and the token release scheduled starts
uint256 releaseScheduleStartTimeStamp;
/// @notice period that tokens are locked before they start being released
uint256 tokenLockDuration;
/// @notice period over which tokens are released for claiming after `tokenLockDuration`
uint256 releaseDuration;
/// @notice invite code used for the purchase, or the merkletree root for all invite codes when creating the sale
bytes32 inviteCode;
}
/// @notice ABI Encode Typehash for Signature Data
bytes32 constant SIGNATURE_TYPEHASH = keccak256(
"SignatureData(address signer,string termsUrl,bytes32 termsHash,uint256 numTokens,uint256 tokenPrice,uint256 hurdle,uint256 releaseScheduleStartTimeStamp,uint256 tokenLockDuration,uint256 releaseDuration,bytes32 inviteCode)"
);
/// @notice ABI Encode Typehash for EIP712 Domain
bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
///
/// @notice Hash input data
/// @param eip712Domain EIP712 Domain struct to be hashed
///
function hashDomain(EIP712Domain memory eip712Domain) internal pure returns (bytes32) {
return keccak256(abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
));
}
///
/// @notice Hash input data
/// @param s Signature Data struct to be hashed
///
function signatureDataHash(SignatureData memory s) internal pure returns (bytes32) {
return keccak256(abi.encode(
SIGNATURE_TYPEHASH,
s.signer,
keccak256(bytes(s.termsUrl)),
s.termsHash,
s.numTokens,
s.tokenPrice,
s.hurdle,
s.releaseScheduleStartTimeStamp,
s.tokenLockDuration,
s.releaseDuration,
s.inviteCode
));
}
function verifySignature(bytes32 domain, SignatureData memory data, bytes memory signature) internal pure returns (bool) {
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
domain,
signatureDataHash(data)
));
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(signature);
return data.signer == ecrecover(digest, v, r, s);
}
///
/// @notice Split a signature into (r s v) values, used for ecrecover
/// @param signature The signed message
///
function splitSignature(bytes memory signature) internal pure returns (uint8, bytes32, bytes32) {
require(signature.length == 65, "SignatureVerification: Invalid Signature");
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := byte(0, mload(add(signature, 96)))
}
return (v, r, s);
}
}
erc721a/contracts/ERC721A.sol
// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.3
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import './IERC721A.sol';
/**
* @dev Interface of ERC721 token receiver.
*/
interface ERC721A__IERC721Receiver {
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 ERC721A is IERC721A {
// Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
struct TokenApprovalRef {
address value;
}
// =============================================================
// 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;
// =============================================================
// STORAGE
// =============================================================
// The next token ID to be minted.
uint256 private _currentIndex;
// The number of tokens burned.
uint256 private _burnCounter;
// Token name
string private _name;
// Token symbol
string private _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) private _packedOwnerships;
// Mapping owner address to address data.
//
// Bits Layout:
// - [0..63] `balance`
// - [64..127] `numberMinted`
// - [128..191] `numberBurned`
// - [192..255] `aux`
mapping(address => uint256) private _packedAddressData;
// Mapping from token ID to approved address.
mapping(uint256 => TokenApprovalRef) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// =============================================================
// CONSTRUCTOR
// =============================================================
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_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 _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 _currentIndex - _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 _currentIndex - _startTokenId();
}
}
/**
* @dev Returns the total number of tokens burned.
*/
function _totalBurned() internal view virtual returns (uint256) {
return _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 _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return (_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 (_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(_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 = _packedAddressData[owner];
uint256 auxCasted;
// Cast `aux` with assembly to avoid redundant masking.
assembly {
auxCasted := aux
}
packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
_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 _name;
}
/**
* @dev Returns the token collection symbol.
*/
function symbol() public view virtual override returns (string memory) {
return _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(_packedOwnerships[index]);
}
/**
* @dev Initializes the ownership slot minted at `index` for efficiency purposes.
*/
function _initializeOwnershipAt(uint256 index) internal virtual {
if (_packedOwnerships[index] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
/**
* Returns the packed ownership data of `tokenId`.
*/
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr)
if (curr < _currentIndex) {
uint256 packed = _packedOwnerships[curr];
// If not burned.
if (packed & _BITMASK_BURNED == 0) {
// 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, `curr` will not underflow.
//
// We can directly compare the packed value.
// If the address is zero, packed will be zero.
while (packed == 0) {
packed = _packedOwnerships[--curr];
}
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.
* 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) public payable virtual override {
address owner = ownerOf(tokenId);
if (_msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_tokenApprovals[tokenId].value = to;
emit Approval(owner, to, tokenId);
}
/**
* @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 _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 {
_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 _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 < _currentIndex && // If within bounds,
_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)
{
TokenApprovalRef storage tokenApproval = _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.
--_packedAddressData[from]; // Updates: `balance -= 1`.
++_packedAddressData[to]; // Updates: `balance += 1`.
// Updates:
// - `address` to the next owner.
// - `startTimestamp` to the timestamp of transfering.
// - `burned` to `false`.
// - `nextInitialized` to `true`.
_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 (_packedOwnerships[nextTokenId] == 0) {
// If the next slot is within bounds.
if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_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__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(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 = _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`.
_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`.
_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();
_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 = _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`.
_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`.
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
_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 = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (index < end);
// Reentrancy protection.
if (_currentIndex != end) revert();
}
}
}
/**
* @dev Equivalent to `_safeMint(to, quantity, '')`.
*/
function _safeMint(address to, uint256 quantity) internal virtual {
_safeMint(to, quantity, '');
}
// =============================================================
// 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;`.
_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`.
_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 (_packedOwnerships[nextTokenId] == 0) {
// If the next slot is within bounds.
if (nextTokenId != _currentIndex) {
// Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
_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 {
_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 = _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);
_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)
}
}
}
erc721a/contracts/IERC721A.sol
// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.2.3
// Creator: Chiru Labs
pragma solidity ^0.8.4;
/**
* @dev Interface of ERC721A.
*/
interface IERC721A {
/**
* 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);
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 999999,
"enabled": true
},
"evmVersion": "london",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.