Overview
ETH Balance
ETH Value
$0.00Latest 10 from a total of 10 transactions
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| Deploy | 362273778 | 182 days ago | IN | 0 ETH | 0.00003991 | ||||
| Deploy | 362273724 | 182 days ago | IN | 0 ETH | 0.00004068 | ||||
| Deploy Buy Produ... | 362271853 | 182 days ago | IN | 0 ETH | 0.00001556 | ||||
| Deploy Liquidity... | 362271839 | 182 days ago | IN | 0 ETH | 0.0000266 | ||||
| Deploy Vault Man... | 362271824 | 182 days ago | IN | 0 ETH | 0.00002099 | ||||
| Deploy Dca | 362271810 | 182 days ago | IN | 0 ETH | 0.00004359 | ||||
| Deploy Subscript... | 362271796 | 182 days ago | IN | 0 ETH | 0.0000214 | ||||
| Deploy Strategy ... | 362271782 | 182 days ago | IN | 0 ETH | 0.00002344 | ||||
| Deploy Strategy ... | 362271769 | 182 days ago | IN | 0 ETH | 0.0000318 | ||||
| Deploy Strategy ... | 362271755 | 182 days ago | IN | 0 ETH | 0.00003942 |
Latest 16 internal transactions
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 362273778 | 182 days ago | Contract Creation | 0 ETH | |||
| 362273724 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271853 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271853 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271839 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271839 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271824 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271824 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271810 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271810 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271796 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271796 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271782 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271769 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271755 | 182 days ago | Contract Creation | 0 ETH | |||
| 362271755 | 182 days ago | Contract Creation | 0 ETH |
Cross-Chain Transactions
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0x33fB26E7...4d7202658 The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {ERC1967Proxy} from '@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol';
import {GenericDeployer} from './GenericDeployer.sol';
import {SubscriptionManager} from '../SubscriptionManager.sol';
import {StrategyManager} from '../StrategyManager.sol';
import {DollarCostAverage} from '../DollarCostAverage.sol';
import {VaultManager} from '../VaultManager.sol';
import {LiquidityManager} from '../LiquidityManager.sol';
import {BuyProduct} from '../BuyProduct.sol';
contract ProjectDeployer is GenericDeployer {
// Strategies
address public strategyInvestor;
address public strategyPositionManager;
ProxyAddress public strategyManager;
// Products
ProxyAddress public dca;
ProxyAddress public vaultManager;
ProxyAddress public liquidityManager;
ProxyAddress public buyProduct;
// Helpers
ProxyAddress public subscriptionManager;
function deployStrategyInvestor(
bytes memory _code,
bytes32 _salt
) external onlyOwner {
strategyInvestor = deploy(_code, _salt);
}
function deployStrategyPositionManager(
bytes memory _code,
bytes32 _salt
) external onlyOwner {
strategyPositionManager = deploy(_code, _salt);
}
function deploySubscriptionManager(
ProxyDeploymentInfo calldata _subscriptionManagerDeploymentInfo,
SubscriptionManager.InitializeParams memory _subscriptionManagerParams
) external onlyOwner {
subscriptionManager = deployProxy(_subscriptionManagerDeploymentInfo);
SubscriptionManager(subscriptionManager.proxy).initialize(_subscriptionManagerParams);
}
function deployStrategyManager(
ProxyDeploymentInfo calldata _strategyManagerDeploymentInfo,
StrategyManager.InitializeParams memory _strategyManagerParam
) external onlyOwner {
strategyManager = deployProxy(_strategyManagerDeploymentInfo);
StrategyManager(strategyManager.proxy).initialize(_strategyManagerParam);
}
function deployDca(
ProxyDeploymentInfo calldata _dcaDeploymentInfo,
DollarCostAverage.InitializeParams memory _dcaParams
) external onlyOwner {
dca = deployProxy(_dcaDeploymentInfo);
DollarCostAverage(dca.proxy).initialize(_dcaParams);
}
function deployVaultManager(
ProxyDeploymentInfo calldata _vaultManagerDeploymentInfo,
VaultManager.InitializeParams memory _vaultManagerParams
) external onlyOwner {
vaultManager = deployProxy(_vaultManagerDeploymentInfo);
VaultManager(vaultManager.proxy).initialize(_vaultManagerParams);
}
function deployLiquidityManager(
ProxyDeploymentInfo calldata _liquidityManagerDeploymentInfo,
LiquidityManager.InitializeParams memory _liquidityManagerParams
) external onlyOwner {
liquidityManager = deployProxy(_liquidityManagerDeploymentInfo);
LiquidityManager(liquidityManager.proxy).initialize(_liquidityManagerParams);
}
function deployBuyProduct(
ProxyDeploymentInfo calldata _buyProductDeploymentInfo,
BuyProduct.InitializeParams memory _buyProductParams
) external onlyOwner {
buyProduct = deployProxy(_buyProductDeploymentInfo);
BuyProduct(buyProduct.proxy).initialize(_buyProductParams);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* 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;
}// 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);
}// 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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.0;
interface IERC5267Upgradeable {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}// 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);
}// 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 {Initializable} from "../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 {
// 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;
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
/**
* @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;
}// 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;
}
}// 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} from "./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 {
/// @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");
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @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;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (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.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface 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].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated 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);
}// 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));
}
}// 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);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.8;
import "./ECDSAUpgradeable.sol";
import "../../interfaces/IERC5267Upgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* _Available since v3.4._
*
* @custom:storage-size 52
*/
abstract contract EIP712Upgradeable is Initializable, IERC5267Upgradeable {
bytes32 private constant _TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @custom:oz-renamed-from _HASHED_NAME
bytes32 private _hashedName;
/// @custom:oz-renamed-from _HASHED_VERSION
bytes32 private _hashedVersion;
string private _name;
string private _version;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
_name = name;
_version = version;
// Reset prior values in storage if upgrading
_hashedName = 0;
_hashedVersion = 0;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator();
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {EIP-5267}.
*
* _Available since v4.9._
*/
function eip712Domain()
public
view
virtual
override
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
// If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
// and the EIP712 domain is not reliable, as it will be missing name and version.
require(_hashedName == 0 && _hashedVersion == 0, "EIP712: Uninitialized");
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Name() internal virtual view returns (string memory) {
return _name;
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Version() internal virtual view returns (string memory) {
return _version;
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
*/
function _EIP712NameHash() internal view returns (bytes32) {
string memory name = _EIP712Name();
if (bytes(name).length > 0) {
return keccak256(bytes(name));
} else {
// If the name is empty, the contract may have been upgraded without initializing the new storage.
// We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
bytes32 hashedName = _hashedName;
if (hashedName != 0) {
return hashedName;
} else {
return keccak256("");
}
}
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
*/
function _EIP712VersionHash() internal view returns (bytes32) {
string memory version = _EIP712Version();
if (bytes(version).length > 0) {
return keccak256(bytes(version));
} else {
// If the version is empty, the contract may have been upgraded without initializing the new storage.
// We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
bytes32 hashedVersion = _hashedVersion;
if (hashedVersion != 0) {
return hashedVersion;
} else {
return keccak256("");
}
}
}
/**
* @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[48] private __gap;
}// 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 MathUpgradeable {
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);
}
}
}// 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 SignedMathUpgradeable {
/**
* @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);
}
}
}// 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
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
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 = MathUpgradeable.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(SignedMathUpgradeable.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, MathUpgradeable.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));
}
}// 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);
}
}// 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 IERC1822Proxiable {
/**
* @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);
}// 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 IERC1967 {
/**
* @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);
}// 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 IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.0;
import "../Proxy.sol";
import "./ERC1967Upgrade.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializing the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) payable {
_upgradeToAndCall(_logic, _data, false);
}
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/IERC1967.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*/
abstract contract ERC1967Upgrade is IERC1967 {
// 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 StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _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 (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(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 StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overridden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the 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 have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the 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);
}// 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);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (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;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
// 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 StorageSlot {
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
}
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
abstract contract HubOwnable is OwnableUpgradeable, UUPSUpgradeable {
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
// solhint-disable-next-line no-empty-blocks
function _authorizeUpgrade(address) internal override onlyOwner {}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
abstract contract OnlyStrategyManager is Initializable {
address public strategyManager;
error Unauthorized();
modifier onlyStrategyManager() {
if (msg.sender != strategyManager)
revert Unauthorized();
_;
}
function __OnlyStrategyManager_init(
address _strategyManager
) internal onlyInitializing {
strategyManager = _strategyManager;
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Upgradeable, SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IBeefyVaultV7} from '../interfaces/IBeefyVaultV7.sol';
import {HubRouter} from "../libraries/HubRouter.sol";
import {VaultManager} from '../VaultManager.sol';
import {LiquidityManager} from "../LiquidityManager.sol";
import {StrategyStorage} from "./StrategyStorage.sol";
import {ReferralStorage} from "../libraries/ReferralStorage.sol";
import {SubscriptionManager} from "../SubscriptionManager.sol";
import {UseFee} from "./UseFee.sol";
contract StrategyInvestor is StrategyStorage {
using SafeERC20Upgradeable for IERC20Upgradeable;
error InvalidParamsLength();
error InsufficientFunds();
struct DcaInvestParams {
DcaInvestment[] dcaInvestments;
IERC20Upgradeable inputToken;
uint amount;
bytes[] swaps;
}
struct VaultInvestParams {
VaultInvestment[] vaultInvestments;
IERC20Upgradeable inputToken;
uint amount;
bytes[] swaps;
}
/// part of LiquidityInvestParams
struct LiquidityInvestZapParams {
bytes swapToken0;
bytes swapToken1;
uint swapAmountToken0;
uint swapAmountToken1;
int24 tickLower;
int24 tickUpper;
uint amount0Min;
uint amount1Min;
}
struct LiquidityInvestParams {
LiquidityInvestment[] investments;
IERC20Upgradeable inputToken;
uint amount;
uint8 liquidityTotalPercentage;
LiquidityInvestZapParams[] zaps;
}
struct BuyInvestParams {
BuyInvestment[] investments;
IERC20Upgradeable inputToken;
uint amount;
bytes[] swaps;
}
struct CollectFeesParams {
uint strategyId;
uint stableAmount;
SubscriptionManager.Permit investorPermit;
SubscriptionManager.Permit strategistPermit;
}
/**
* @dev swaps bytes are the encoded versions of HubRouter.SwapData used in the "execute" and "executeNative" functions
*/
struct InvestParams {
uint strategyId;
IERC20Upgradeable inputToken;
uint inputAmount;
bytes inputTokenSwap;
bytes[] dcaSwaps;
bytes[] vaultSwaps;
bytes[] buySwaps;
LiquidityInvestZapParams[] liquidityZaps;
SubscriptionManager.Permit investorPermit;
SubscriptionManager.Permit strategistPermit;
}
struct InvestNativeParams {
uint strategyId;
bytes inputTokenSwap;
bytes[] dcaSwaps;
bytes[] vaultSwaps;
bytes[] buySwaps;
LiquidityInvestZapParams[] liquidityZaps;
SubscriptionManager.Permit investorPermit;
SubscriptionManager.Permit strategistPermit;
}
struct WeightedProduct {
UseFee product;
uint8 weight;
}
error StrategyUnavailable();
function invest(InvestParams memory _params) external {
if (_params.strategyId > _strategies.length)
revert StrategyUnavailable();
uint initialInputTokenBalance = _params.inputToken.balanceOf(address(this));
_params.inputToken.safeTransferFrom(msg.sender, address(this), _params.inputAmount);
_invest(
_params,
HubRouter.execute(
_params.inputTokenSwap,
_params.inputToken,
stable,
_params.inputToken.balanceOf(address(this)) - initialInputTokenBalance
)
);
}
function investNative(InvestNativeParams memory _params) external payable {
if (_params.strategyId > _strategies.length)
revert StrategyUnavailable();
_invest(
InvestParams({
strategyId: _params.strategyId,
inputToken: IERC20Upgradeable(address(0)),
inputAmount: msg.value,
inputTokenSwap: '',
dcaSwaps: _params.dcaSwaps,
vaultSwaps: _params.vaultSwaps,
buySwaps: _params.buySwaps,
liquidityZaps: _params.liquidityZaps,
investorPermit: _params.investorPermit,
strategistPermit: _params.strategistPermit
}),
HubRouter.executeNative(_params.inputTokenSwap, stable)
);
}
function _invest(
InvestParams memory _investParams,
uint stableAmount
) internal {
Strategy storage strategy = _strategies[_investParams.strategyId];
uint stableAmountAfterFees = _collectFees(
CollectFeesParams({
strategyId: _investParams.strategyId,
stableAmount: stableAmount,
investorPermit: _investParams.investorPermit,
strategistPermit: _investParams.strategistPermit
})
);
uint[] memory dcaPositionIds = _investInDca(
DcaInvestParams({
dcaInvestments: _dcaInvestmentsPerStrategy[_investParams.strategyId],
inputToken: stable,
amount: stableAmountAfterFees,
swaps: _investParams.dcaSwaps
})
);
VaultPosition[] memory vaultPositions = _investInVaults(
VaultInvestParams({
vaultInvestments: _vaultInvestmentsPerStrategy[_investParams.strategyId],
inputToken: stable,
amount: stableAmountAfterFees,
swaps: _investParams.vaultSwaps
})
);
LiquidityPosition[] memory liquidityPositions = _investInLiquidity(
LiquidityInvestParams({
investments: _liquidityInvestmentsPerStrategy[_investParams.strategyId],
inputToken: stable,
amount: stableAmountAfterFees,
liquidityTotalPercentage: strategy.percentages[PRODUCT_LIQUIDITY],
zaps: _investParams.liquidityZaps
})
);
BuyPosition[] memory buyPositions = _investInToken(
BuyInvestParams({
investments: _buyInvestmentsPerStrategy[_investParams.strategyId],
inputToken: stable,
amount: stableAmountAfterFees,
swaps: _investParams.buySwaps
})
);
uint positionId = _positions[msg.sender].length;
Position storage position = _positions[msg.sender].push();
position.strategyId = _investParams.strategyId;
_dcaPositionsPerPosition[msg.sender][positionId] = dcaPositionIds;
for (uint i; i < vaultPositions.length; ++i)
_vaultPositionsPerPosition[msg.sender][positionId].push(vaultPositions[i]);
for (uint i; i < liquidityPositions.length; ++i)
_liquidityPositionsPerPosition[msg.sender][positionId].push(liquidityPositions[i]);
for (uint i; i < buyPositions.length; ++i)
_buyPositionsPerPosition[msg.sender][positionId].push(buyPositions[i]);
emit PositionCreated(
msg.sender,
_investParams.strategyId,
positionId,
address(_investParams.inputToken),
_investParams.inputAmount,
stableAmountAfterFees,
dcaPositionIds,
vaultPositions,
liquidityPositions,
buyPositions
);
}
function _investInDca(
DcaInvestParams memory _params
) private returns (uint[] memory) {
if (_params.dcaInvestments.length == 0)
return new uint[](0);
if (_params.dcaInvestments.length != _params.swaps.length)
revert InvalidParamsLength();
uint[] memory dcaPositionIds = new uint[](_params.dcaInvestments.length);
uint nextDcaPositionId = dca.getPositionsLength(address(this));
for (uint i; i < _params.dcaInvestments.length; ++i) {
DcaInvestment memory investment = _params.dcaInvestments[i];
IERC20Upgradeable poolInputToken = IERC20Upgradeable(dca.getPool(investment.poolId).inputToken);
uint swapOutput = HubRouter.execute(
_params.swaps[i],
_params.inputToken,
poolInputToken,
_params.amount * investment.percentage / 100
);
poolInputToken.safeTransfer(address(dca), swapOutput);
dca.investUsingStrategy(investment.poolId, investment.swaps, swapOutput);
dcaPositionIds[i] = nextDcaPositionId;
++nextDcaPositionId;
}
return dcaPositionIds;
}
function _investInVaults(
VaultInvestParams memory _params
) private returns (VaultPosition[] memory) {
if (_params.vaultInvestments.length == 0)
return new VaultPosition[](0);
if (_params.vaultInvestments.length != _params.swaps.length)
revert InvalidParamsLength();
VaultPosition[] memory vaultPositions = new VaultPosition[](_params.vaultInvestments.length);
for (uint i; i < _params.vaultInvestments.length; ++i) {
VaultInvestment memory investment = _params.vaultInvestments[i];
IBeefyVaultV7 vault = IBeefyVaultV7(investment.vault);
IERC20Upgradeable vaultWantToken = vault.want();
uint swapOutput = HubRouter.execute(
_params.swaps[i],
_params.inputToken,
vaultWantToken,
_params.amount * investment.percentage / 100
);
vaultWantToken.safeTransfer(address(vaultManager), swapOutput);
uint initialBalance = vault.balanceOf(address(this));
vaultManager.investUsingStrategy(investment.vault, swapOutput);
vaultPositions[i] = VaultPosition(
investment.vault,
vault.balanceOf(address(this)) - initialBalance
);
}
return vaultPositions;
}
function _investInLiquidity(
LiquidityInvestParams memory _params
) private returns (LiquidityPosition[] memory) {
if (_params.investments.length == 0)
return new LiquidityPosition[](0);
if (_params.investments.length != _params.zaps.length)
revert InvalidParamsLength();
LiquidityPosition[] memory liquidityPositions = new LiquidityPosition[](_params.investments.length);
_params.inputToken.safeTransfer(
address(liquidityManager),
_params.liquidityTotalPercentage * _params.amount / 100
);
for (uint i; i < _params.investments.length; ++i) {
LiquidityInvestment memory investment = _params.investments[i];
LiquidityInvestZapParams memory zap = _params.zaps[i];
uint currentInvestmentAmount = _params.amount * investment.percentage / 100;
if (zap.swapAmountToken0 + zap.swapAmountToken1 > currentInvestmentAmount)
revert InsufficientFunds();
(uint tokenId, uint128 liquidity) = liquidityManager.investUniswapV3UsingStrategy(
LiquidityManager.InvestUniswapV3Params({
positionManager: address(investment.positionManager),
inputToken: _params.inputToken,
depositAmountInputToken: currentInvestmentAmount,
token0: investment.token0,
token1: investment.token1,
fee: investment.fee,
swapToken0: zap.swapToken0,
swapToken1: zap.swapToken1,
swapAmountToken0: zap.swapAmountToken0,
swapAmountToken1: zap.swapAmountToken1,
tickLower: zap.tickLower,
tickUpper: zap.tickUpper,
amount0Min: zap.amount0Min,
amount1Min: zap.amount1Min
})
);
liquidityPositions[i] = LiquidityPosition(
investment.positionManager,
tokenId,
liquidity
);
}
return liquidityPositions;
}
function _investInToken(
BuyInvestParams memory _params
) private returns (BuyPosition[] memory) {
if (_params.swaps.length == 0)
return new BuyPosition[](0);
BuyPosition[] memory buyPositions = new BuyPosition[](_params.swaps.length);
for (uint i; i < _params.swaps.length; ++i) {
BuyInvestment memory investment = _params.investments[i];
uint swapOutput = HubRouter.execute(
_params.swaps[i],
_params.inputToken,
investment.token,
_params.amount * investment.percentage / 100
);
buyPositions[i] = BuyPosition(investment.token, swapOutput);
}
return buyPositions;
}
function _collectFees(
CollectFeesParams memory _params
) internal virtual returns (uint remainingAmount) {
Strategy storage strategy = _strategies[_params.strategyId];
ReferralStorage.ReferralStruct storage referralStorage = ReferralStorage.getReferralStruct();
address referrer = referralStorage.referrals[msg.sender];
bool strategistSubscribed = subscriptionManager.isSubscribed(strategy.creator, _params.strategistPermit);
bool userSubscribed = subscriptionManager.isSubscribed(msg.sender, _params.investorPermit);
(uint amountBaseFee, uint amountNonSubscriberFee) = _calculateFees(
_params.stableAmount,
userSubscribed,
[
WeightedProduct(dca, strategy.percentages[PRODUCT_DCA]),
WeightedProduct(vaultManager, strategy.percentages[PRODUCT_VAULTS]),
WeightedProduct(liquidityManager, strategy.percentages[PRODUCT_LIQUIDITY]),
WeightedProduct(buyProduct, strategy.percentages[PRODUCT_BUY])
]
);
uint strategistFee;
uint referrerFee;
if (strategistSubscribed) {
uint32 currentStrategistPercentage = _hottestStrategiesMapping[_params.strategyId]
? hotStrategistPercentage
: strategistPercentage;
strategistFee = amountBaseFee * currentStrategistPercentage / 100;
_strategistRewards[strategy.creator] += strategistFee;
emit Fee(
msg.sender,
strategy.creator,
strategistFee,
abi.encode(_params.strategyId, FEE_TO_STRATEGIST)
);
}
if (referrer != address(0)) {
referrerFee = (amountBaseFee - strategistFee) * referralStorage.referrerPercentage / 100;
referralStorage.referrerRewards[referrer] += referrerFee;
emit Fee(
msg.sender,
referrer,
referrerFee,
abi.encode(_params.strategyId, FEE_TO_REFERRER)
);
}
uint protocolFee = amountBaseFee + amountNonSubscriberFee - strategistFee - referrerFee;
stable.safeTransfer(treasury, protocolFee);
emit Fee(
msg.sender,
treasury,
protocolFee,
abi.encode(_params.strategyId, FEE_TO_PROTOCOL)
);
return _params.stableAmount - amountBaseFee - amountNonSubscriberFee;
}
function _calculateFees(
uint _amount,
bool _userSubscribed,
WeightedProduct[4] memory _weightedProducts
) internal view returns (
uint amountBaseFee,
uint amountNonSubscriberFee
) {
uint32 totalBaseFeeBP;
uint32 totalNonSubscriberFeeBP;
if (_userSubscribed) {
for (uint i; i < _weightedProducts.length; ++i) {
totalBaseFeeBP += _weightedProducts[i].product.baseFeeBP() * _weightedProducts[i].weight;
}
}
else {
for (uint i; i < _weightedProducts.length; ++i) {
WeightedProduct memory weightedProduct = _weightedProducts[i];
totalBaseFeeBP += weightedProduct.product.baseFeeBP() * weightedProduct.weight;
totalNonSubscriberFeeBP += weightedProduct.product.nonSubscriberFeeBP() * weightedProduct.weight;
}
}
return (
totalBaseFeeBP * _amount / 1_000_000,
_userSubscribed // ternary for gas optimization only
? 0
: totalNonSubscriberFeeBP * _amount / 1_000_000
);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Upgradeable, SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {StrategyStorage} from "./StrategyStorage.sol";
import {DollarCostAverage} from "../DollarCostAverage.sol";
import {IBeefyVaultV7} from '../interfaces/IBeefyVaultV7.sol';
import {INonfungiblePositionManager} from '../interfaces/INonfungiblePositionManager.sol';
import {PairHelpers} from "../helpers/PairHelpers.sol";
contract StrategyPositionManager is StrategyStorage {
using SafeERC20Upgradeable for IERC20Upgradeable;
struct LiquidityMinOutputs {
uint minOutputToken0;
uint minOutputToken1;
}
error PositionAlreadyClosed();
error InvalidPositionId(address investor, uint positionId);
function closePosition(
uint _positionId,
LiquidityMinOutputs[] calldata _liquidityMinOutputs
) external {
Position storage position = _positions[msg.sender][_positionId];
if (position.closed)
revert PositionAlreadyClosed();
position.closed = true;
emit PositionClosed(
msg.sender,
position.strategyId,
_positionId,
_closePositionsDca(_dcaPositionsPerPosition[msg.sender][_positionId]),
_closePositionsVault(_vaultPositionsPerPosition[msg.sender][_positionId]),
_closePositionsLiquidity(
_liquidityPositionsPerPosition[msg.sender][_positionId],
_liquidityMinOutputs
),
_collectPositionsBuy(_buyPositionsPerPosition[msg.sender][_positionId])
);
}
function _closePositionsDca(
uint[] memory _positions
) private returns (uint[][] memory) {
uint[][] memory withdrawnAmounts = new uint[][](_positions.length);
for (uint i; i < _positions.length; ++i) {
uint positionId = _positions[i];
DollarCostAverage.PoolInfo memory poolInfo = dca.getPool(
dca.getPosition(address(this), positionId).poolId
);
IERC20Upgradeable inputToken = IERC20Upgradeable(poolInfo.inputToken);
IERC20Upgradeable outputToken = IERC20Upgradeable(poolInfo.outputToken);
uint initialInputTokenBalance = inputToken.balanceOf(address(this));
uint initialOutputTokenBalance = outputToken.balanceOf(address(this));
dca.closePosition(positionId);
uint inputTokenAmount = inputToken.balanceOf(address(this)) - initialInputTokenBalance;
uint outputTokenAmount = outputToken.balanceOf(address(this)) - initialOutputTokenBalance;
if (inputTokenAmount > 0 || outputTokenAmount > 0) {
withdrawnAmounts[i] = new uint[](2);
if (inputTokenAmount > 0) {
withdrawnAmounts[i][0] = inputTokenAmount;
inputToken.safeTransfer(msg.sender, inputTokenAmount);
}
if (outputTokenAmount > 0) {
withdrawnAmounts[i][1] = outputTokenAmount;
outputToken.safeTransfer(msg.sender, outputTokenAmount);
}
}
}
return withdrawnAmounts;
}
function _closePositionsVault(
VaultPosition[] memory _positions
) private returns (uint[] memory) {
uint[] memory withdrawnAmounts = new uint[](_positions.length);
for (uint i; i < _positions.length; ++i) {
VaultPosition memory vaultPosition = _positions[i];
IBeefyVaultV7 vault = IBeefyVaultV7(vaultPosition.vault);
uint initialBalance = vault.want().balanceOf(address(this));
vault.withdraw(vaultPosition.amount);
uint withdrawnAmount = vault.want().balanceOf(address(this)) - initialBalance;
if (withdrawnAmount > 0) {
withdrawnAmounts[i] = withdrawnAmount;
vault.want().safeTransfer(msg.sender, withdrawnAmount);
}
}
return withdrawnAmounts;
}
function _closePositionsLiquidity(
LiquidityPosition[] memory _positions,
LiquidityMinOutputs[] memory _minOutputs
) private returns (uint[][] memory) {
uint[][] memory withdrawnAmounts = new uint[][](_positions.length);
for (uint index; index < _positions.length; ++index) {
LiquidityPosition memory position = _positions[index];
LiquidityMinOutputs memory minOutput = _minOutputs.length > index
? _minOutputs[index]
: LiquidityMinOutputs(0, 0);
PairHelpers.Pair memory pair = PairHelpers.fromLiquidityToken(
position.positionManager,
position.tokenId
);
position.positionManager.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: position.tokenId,
liquidity: position.liquidity,
amount0Min: minOutput.minOutputToken0,
amount1Min: minOutput.minOutputToken1,
deadline: block.timestamp
})
);
(uint amount0, uint amount1) = _claimLiquidityPositionTokens(position, pair);
withdrawnAmounts[index] = new uint[](2);
withdrawnAmounts[index][0] = amount0;
withdrawnAmounts[index][1] = amount1;
}
return withdrawnAmounts;
}
function collectPosition(uint _positionId) external {
if (_positionId >= _positions[msg.sender].length)
revert InvalidPositionId(msg.sender, _positionId);
Position storage position = _positions[msg.sender][_positionId];
if (position.closed)
revert PositionAlreadyClosed();
BuyPosition[] memory buyPositions = _buyPositionsPerPosition[msg.sender][_positionId];
if (buyPositions.length > 0)
delete _buyPositionsPerPosition[msg.sender][_positionId];
emit PositionCollected(
msg.sender,
position.strategyId,
_positionId,
_collectPositionsDca(_dcaPositionsPerPosition[msg.sender][_positionId]),
_collectPositionsLiquidity(_liquidityPositionsPerPosition[msg.sender][_positionId]),
_collectPositionsBuy(buyPositions)
);
}
function _collectPositionsDca(uint[] memory _positions) private returns (uint[] memory) {
uint[] memory withdrawnAmounts = new uint[](_positions.length);
for (uint i; i < _positions.length; ++i) {
uint positionId = _positions[i];
DollarCostAverage.PoolInfo memory poolInfo = dca.getPool(dca.getPosition(address(this), positionId).poolId);
IERC20Upgradeable outputToken = IERC20Upgradeable(poolInfo.outputToken);
uint initialOutputTokenBalance = outputToken.balanceOf(address(this));
dca.collectPosition(positionId);
uint outputTokenAmount = outputToken.balanceOf(address(this)) - initialOutputTokenBalance;
if (outputTokenAmount > 0) {
withdrawnAmounts[i] = outputTokenAmount;
outputToken.safeTransfer(msg.sender, outputTokenAmount);
}
}
return withdrawnAmounts;
}
function _collectPositionsLiquidity(
LiquidityPosition[] memory _positions
) private returns (uint[][] memory) {
uint[][] memory withdrawnAmounts = new uint[][](_positions.length);
for (uint index; index < _positions.length; ++index) {
LiquidityPosition memory position = _positions[index];
PairHelpers.Pair memory pair = PairHelpers.fromLiquidityToken(
position.positionManager,
position.tokenId
);
(uint amount0, uint amount1) = _claimLiquidityPositionTokens(position, pair);
withdrawnAmounts[index] = new uint[](2);
withdrawnAmounts[index][0] = amount0;
withdrawnAmounts[index][1] = amount1;
}
return withdrawnAmounts;
}
function _collectPositionsBuy(
BuyPosition[] memory _positions
) private returns (uint[] memory) {
uint[] memory withdrawnAmounts = new uint[](_positions.length);
for (uint i; i < _positions.length; ++i) {
BuyPosition memory position = _positions[i];
position.token.safeTransfer(msg.sender, position.amount);
withdrawnAmounts[i] = position.amount;
}
return withdrawnAmounts;
}
function _claimLiquidityPositionTokens(
LiquidityPosition memory _position,
PairHelpers.Pair memory _pair
) private returns (uint amount0, uint amount1) {
address recipient = msg.sender;
(uint initialBalance0, uint initialBalance1) = PairHelpers.getBalances(_pair, recipient);
_position.positionManager.collect(
INonfungiblePositionManager.CollectParams({
tokenId: _position.tokenId,
recipient: recipient,
amount0Max: type(uint128).max,
amount1Max: type(uint128).max
})
);
(uint finalBalance0, uint finalBalance1) = PairHelpers.getBalances(_pair, recipient);
amount0 = finalBalance0 - initialBalance0;
amount1 = finalBalance1 - initialBalance1;
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {INonfungiblePositionManager} from '../interfaces/INonfungiblePositionManager.sol';
import {SubscriptionManager} from '../SubscriptionManager.sol';
import {LiquidityManager} from '../LiquidityManager.sol';
import {VaultManager} from "../VaultManager.sol";
import {DollarCostAverage} from '../DollarCostAverage.sol';
import {UseTreasury} from "./UseTreasury.sol";
import {UseFee} from "./UseFee.sol";
contract StrategyStorage is UseTreasury {
// @notice percentages is a mapping from product id to its percentage
struct Strategy {
address creator;
mapping(uint8 => uint8) percentages;
}
/**
* Investment structs
*
* Interfaces of how investments are stored for each product in a strategy
*/
struct DcaInvestment {
uint208 poolId;
uint16 swaps;
uint8 percentage;
}
struct VaultInvestment {
address vault;
uint8 percentage;
}
/// @notice Represents a liquidity investment in Uniswap V3, allowing bounds to be set as percentage offsets or specific ticks.
/// @dev When `usePercentageBounds` is true, `lowerBound` and `upperBound` are percentage offsets from the current price at the time of investment. When false, they represent actual tick values.
struct LiquidityInvestment {
INonfungiblePositionManager positionManager;
uint8 percentage;
IERC20Upgradeable token0;
IERC20Upgradeable token1;
uint24 fee; // The Uniswap V3 pool fee tier (e.g., 500, 3000, 10000)
bool usePercentageBounds; // Determines if bounds are percentage offsets (true) or tick values (false)
int24 lowerBound; // Lower bound as a percentage offset or tick value
int24 upperBound; // Upper bound as a percentage offset or tick value
}
struct BuyInvestment {
IERC20Upgradeable token;
uint8 percentage;
}
/**
* Position structs
*
* Interfaces for users' positions to be stored in the Strategy contract
*/
struct Position {
uint strategyId;
bool closed;
}
struct VaultPosition {
address vault;
uint amount;
}
struct LiquidityPosition {
INonfungiblePositionManager positionManager;
uint tokenId;
uint128 liquidity;
}
struct BuyPosition {
IERC20Upgradeable token;
uint amount;
}
/* ----- CONSTANTS ----- */
// PRODUCTS
uint8 public constant PRODUCT_DCA = 0;
uint8 public constant PRODUCT_VAULTS = 1;
uint8 public constant PRODUCT_LIQUIDITY = 2;
uint8 public constant PRODUCT_BUY = 3;
// FEES
uint8 public constant FEE_TO_PROTOCOL = 0;
uint8 public constant FEE_TO_STRATEGIST = 1;
uint8 public constant FEE_TO_REFERRER = 2;
Strategy[] internal _strategies;
mapping(uint => bool) internal _hottestStrategiesMapping;
uint[] internal _hottestStrategiesArray;
uint8 public maxHottestStrategies;
mapping(address => uint) internal _strategistRewards;
IERC20Upgradeable public stable;
address public zapManager;
SubscriptionManager public subscriptionManager;
DollarCostAverage public dca;
VaultManager public vaultManager;
LiquidityManager public liquidityManager;
UseFee public buyProduct;
uint32 public strategistPercentage;
uint32 public hotStrategistPercentage;
mapping(uint => DcaInvestment[]) internal _dcaInvestmentsPerStrategy;
mapping(uint => VaultInvestment[]) internal _vaultInvestmentsPerStrategy;
mapping(uint => LiquidityInvestment[]) internal _liquidityInvestmentsPerStrategy;
mapping(uint => BuyInvestment[]) internal _buyInvestmentsPerStrategy;
mapping(address => Position[]) internal _positions;
// @dev investor => strategy position id => dca position ids
mapping(address => mapping(uint => uint[])) internal _dcaPositionsPerPosition;
// @dev investor => strategy position id => vault positions
mapping(address => mapping(uint => VaultPosition[])) internal _vaultPositionsPerPosition;
// @dev investor => strategy position id => liquidity positions
mapping(address => mapping(uint => LiquidityPosition[])) internal _liquidityPositionsPerPosition;
// @dev investor => strategy position id => buy positions
mapping(address => mapping(uint => BuyPosition[])) internal _buyPositionsPerPosition;
event Fee(address from, address to, uint amount, bytes data);
event PositionCreated(
address user,
uint strategyId,
uint positionId,
address inputToken,
uint inputTokenAmount,
uint stableAmountAfterFees,
uint[] dcaPositionIds,
VaultPosition[] vaultPositions,
LiquidityPosition[] liquidityPositions,
BuyPosition[] tokenPositions
);
event PositionClosed(
address user,
uint strategyId,
uint positionId,
uint[][] dcaWithdrawnAmounts,
uint[] vaultWithdrawnAmount,
uint[][] liquidityWithdrawnAmounts,
uint[] buyWithdrawnAmounts
);
event PositionCollected(
address user,
uint strategyId,
uint positionId,
uint[] dcaWithdrawnAmounts,
uint[][] liquidityWithdrawnAmounts,
uint[] buyWithdrawnAmounts
);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Upgradeable, SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
// @dev can only be used in contracts that aren't holding users' funds
abstract contract UseDust {
using SafeERC20Upgradeable for IERC20Upgradeable;
// @notice arbitrary number to prevent transferring insignificant amounts of tokens
uint private constant MIN_DUST = 100;
function _sendDust(IERC20Upgradeable _token, address _to) internal {
uint balance = _token.balanceOf(address(this));
// @dev using ">" instead of ">=" to save gas since the difference is negligible
if (balance > MIN_DUST)
_token.safeTransfer(_to, balance);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {IERC20Upgradeable, SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {SubscriptionManager} from "../SubscriptionManager.sol";
import {UseTreasury} from "./UseTreasury.sol";
abstract contract UseFee is OwnableUpgradeable, UseTreasury {
using SafeERC20Upgradeable for IERC20Upgradeable;
SubscriptionManager public subscriptionManager;
uint32 constant public MAX_FEE = 1_000;
uint32 public baseFeeBP;
uint32 public nonSubscriberFeeBP;
event Fee(address from, address to, uint amount, bytes data);
event FeeUpdated(uint32 baseFeeBP, uint nonSubscriberFeeBP);
error FeeTooHigh();
function __UseFee_init(
address _treasury,
address _subscriptionManager,
uint32 _baseFeeBP,
uint32 _nonSubscriberFeeBP
) internal onlyInitializing {
setTreasury(_treasury);
subscriptionManager = SubscriptionManager(_subscriptionManager);
_setFee(_baseFeeBP, _nonSubscriberFeeBP);
}
function calculateFee(
address _user,
uint _amount,
SubscriptionManager.Permit calldata _permit
) public view returns (uint baseFee, uint nonSubscriberFee) {
return (
_getBaseFee(_amount),
_getNonSubscriberFee(_user, _amount, _permit)
);
}
function getFeePercentage(
bool _subscribed
) external view returns (uint32) {
return _subscribed ? baseFeeBP : baseFeeBP + nonSubscriberFeeBP;
}
function _getBaseFee(
uint _amount
) private view returns (uint) {
return _amount * baseFeeBP / 10_000;
}
function _getNonSubscriberFee(
address _user,
uint _amount,
SubscriptionManager.Permit calldata _permit
) private view returns (uint) {
return subscriptionManager.isSubscribed(_user, _permit)
? 0
: _amount * nonSubscriberFeeBP / 10_000;
}
function _pullFunds(
address _token,
uint _depositAmount,
bytes memory _eventData,
SubscriptionManager.Permit calldata _subscriptionPermit
) internal returns (uint remainingAmount) {
(uint baseFee, uint nonSubscriberFee) = calculateFee(msg.sender, _depositAmount, _subscriptionPermit);
uint depositFee = baseFee + nonSubscriberFee;
uint initialBalance = IERC20Upgradeable(_token).balanceOf(address(this));
IERC20Upgradeable(_token).safeTransferFrom(msg.sender, treasury, depositFee);
IERC20Upgradeable(_token).safeTransferFrom(msg.sender, address(this), _depositAmount - depositFee);
emit Fee(msg.sender, treasury, depositFee, _eventData);
return IERC20Upgradeable(_token).balanceOf(address(this)) - initialBalance;
}
function setFee(uint32 _baseFeeBP, uint32 _nonSubscriberFeeBP) external onlyOwner {
_setFee(_baseFeeBP, _nonSubscriberFeeBP);
}
function _setFee(uint32 _baseFeeBP, uint32 _nonSubscriberFeeBP) internal {
if (_baseFeeBP > MAX_FEE || _nonSubscriberFeeBP > MAX_FEE)
revert FeeTooHigh();
baseFeeBP = _baseFeeBP;
nonSubscriberFeeBP = _nonSubscriberFeeBP;
emit FeeUpdated(_baseFeeBP, _nonSubscriberFeeBP);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
abstract contract UseTreasury is OwnableUpgradeable {
address public treasury;
event TreasuryUpdated(address treasury);
error InvalidZeroAddress();
function setTreasury(address _treasury) public onlyOwner {
if (_treasury == address(0))
revert InvalidZeroAddress();
treasury = _treasury;
emit TreasuryUpdated(_treasury);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {HubOwnable} from "./abstract/HubOwnable.sol";
import {UseFee} from "./abstract/UseFee.sol";
/// @dev This contract is an implementation of the UseFee contract for the Tokens product used in strategies
contract BuyProduct is HubOwnable, UseFee {
struct InitializeParams {
address owner;
address treasury;
address subscriptionManager;
uint32 baseFeeBP;
uint32 nonSubscriberFeeBP;
}
function initialize(InitializeParams memory _params) public initializer {
__Ownable_init();
__UseFee_init(
_params.treasury,
_params.subscriptionManager,
_params.baseFeeBP,
_params.nonSubscriberFeeBP
);
transferOwnership(_params.owner);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {ERC1967Proxy} from '@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol';
contract GenericDeployer is Ownable {
struct ProxyDeploymentInfo {
bytes code;
bytes32 implementationSalt;
bytes32 proxySalt;
}
struct ProxyAddress {
address implementation;
address proxy;
}
function deploy(
bytes memory _code,
bytes32 _salt
) public onlyOwner returns (address addr) {
assembly {
addr := create2(0, add(_code, 0x20), mload(_code), _salt)
if iszero(extcodesize(addr)) {revert(0, 0)}
}
}
function deployProxy(
ProxyDeploymentInfo calldata _deployInfo
) public onlyOwner returns (ProxyAddress memory) {
address implementation = deploy(_deployInfo.code, _deployInfo.implementationSalt);
address proxy = deploy(
abi.encodePacked(
type(ERC1967Proxy).creationCode,
abi.encode(implementation, "")
),
_deployInfo.proxySalt
);
return ProxyAddress(implementation, proxy);
}
function getDeployAddress(
bytes memory _code,
bytes32 _salt
) public view returns (address) {
bytes32 initCodeHash = keccak256(_code);
bytes32 data = keccak256(abi.encodePacked(
bytes1(0xff),
address(this),
_salt,
initCodeHash
));
return address(uint160(uint256(data)));
}
function getDeployProxyAddress(
ProxyDeploymentInfo calldata _deploymentInfo
) public view returns (ProxyAddress memory) {
address implementation = getDeployAddress(
_deploymentInfo.code,
_deploymentInfo.implementationSalt
);
return ProxyAddress({
proxy: getDeployAddress(
abi.encodePacked(
type(ERC1967Proxy).creationCode,
abi.encode(implementation, "")
),
_deploymentInfo.proxySalt
),
implementation: implementation
});
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Upgradeable, SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {ISwapRouter} from "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import {MathHelpers} from "./helpers/MathHelpers.sol";
import {HubOwnable} from "./abstract/HubOwnable.sol";
import {OnlyStrategyManager} from "./abstract/OnlyStrategyManager.sol";
import {UseFee} from "./abstract/UseFee.sol";
import {SubscriptionManager} from "./SubscriptionManager.sol";
contract DollarCostAverage is HubOwnable, UseFee, OnlyStrategyManager {
using SafeERC20Upgradeable for IERC20Upgradeable;
struct PositionInfo {
// @dev Single slot
uint16 swaps;
uint16 finalSwap;
uint16 lastUpdateSwap;
// @dev Uses uint208 to fill the remaining of the slot
uint208 poolId;
// @dev Single slot
uint amountPerSwap;
}
struct PoolInfo {
// Single slot
address inputToken;
// @dev Single slot
address outputToken;
// @dev Able to represent up to 596_523 hours
uint32 interval;
uint16 performedSwaps;
// @dev One slot each
uint nextSwapAmount;
uint lastSwapTimestamp;
address router;
bytes path;
}
struct SwapInfo {
// @dev This must match the type of PositionInfo.poolId
uint208 poolId;
uint minOutputAmount;
}
struct InitializeParams {
address owner;
address treasury;
address swapper;
address strategyManager;
address subscriptionManager;
uint32 baseFeeBP;
uint32 nonSubscriberFeeBP;
}
uint128 public constant SWAP_QUOTE_PRECISION = 10 ** 18;
uint32 public constant MIN_INTERVAL = 8 hours;
uint8 private constant HOP_ENCODING_SIZE_IN_BYTES = 43;
// @dev user => position
mapping(address => PositionInfo[]) internal positionInfo;
// @dev poolId => swap number => delta
mapping(uint208 => mapping(uint16 => uint)) internal endingPositionDeduction;
// @dev poolId => swap number => accumulated ratio
mapping(uint208 => mapping(uint16 => uint)) internal accruedSwapQuoteByPool;
// @dev inputToken => outputToken => interval => boolean
mapping(address => mapping(address => mapping(uint32 => bool))) internal existingPools;
PoolInfo[] internal poolInfo;
address public swapper;
error InvalidAmount();
error InvalidNumberOfSwaps();
error InvalidPoolId();
error InvalidPositionId();
error InvalidPoolPath();
error InvalidPoolInterval();
error DuplicatePool();
error TooEarlyToSwap(uint timeRemaining);
error NoTokensToSwap();
error CallerIsNotSwapper();
event PoolCreated(uint208 poolId, address inputToken, address outputToken, address router, bytes path, uint interval);
event PositionCreated(address user, uint208 poolId, uint positionId, uint swaps, uint amountPerSwap, uint finalSwap);
event PositionCollected(address user, uint positionId, uint outputTokenAmount);
event PositionClosed(address user, uint positionId, uint inputTokenAmount, uint outputTokenAmount);
event Swap(uint208 poolId, uint amountIn, uint amountOut);
event SetPoolPath(uint208 poolId, bytes oldPath, bytes newPath);
event SetPoolRouter(uint208 poolId, address oldRouter, address newRouter);
event SetSwapper(address oldSwapper, address newSwapper);
function initialize(InitializeParams calldata _initializeParams) external initializer {
if (_initializeParams.swapper == address(0))
revert InvalidZeroAddress();
__Ownable_init();
__UseFee_init(
_initializeParams.treasury,
_initializeParams.subscriptionManager,
_initializeParams.baseFeeBP,
_initializeParams.nonSubscriberFeeBP
);
__OnlyStrategyManager_init(_initializeParams.strategyManager);
transferOwnership(_initializeParams.owner);
swapper = _initializeParams.swapper;
}
function createPool(
address _inputToken,
address _outputToken,
address _router,
bytes calldata _path,
uint32 _interval
) external virtual onlyOwner {
if (_interval < MIN_INTERVAL)
revert InvalidPoolInterval();
if (existingPools[_inputToken][_outputToken][_interval])
revert DuplicatePool();
existingPools[_inputToken][_outputToken][_interval] = true;
(address firstToken, address lastToken) = extractAddresses(_path);
if (firstToken != _inputToken || lastToken != _outputToken)
revert InvalidPoolPath();
if (
_inputToken == address(0) ||
_outputToken == address(0) ||
_router == address(0)
)
revert InvalidZeroAddress();
uint208 poolId = uint208(poolInfo.length);
poolInfo.push(PoolInfo({
inputToken: _inputToken,
outputToken: _outputToken,
router: _router,
path: _path,
interval: _interval,
nextSwapAmount: 0,
performedSwaps: 0,
lastSwapTimestamp: 0
}));
emit PoolCreated(poolId, _inputToken, _outputToken, _router, _path, _interval);
}
function invest(
uint208 _poolId,
uint16 _swaps,
uint _amount,
SubscriptionManager.Permit calldata _subscriptionPermit
) external virtual {
if (_poolId >= poolInfo.length)
revert InvalidPoolId();
if (_swaps == 0)
revert InvalidNumberOfSwaps();
PoolInfo memory pool = poolInfo[_poolId];
_invest(
_poolId,
_swaps,
_pullFunds(
pool.inputToken,
_amount,
abi.encode(_poolId),
_subscriptionPermit
)
);
}
function investUsingStrategy(
uint208 _poolId,
uint16 _swaps,
uint _amount
) external virtual onlyStrategyManager {
_invest(_poolId, _swaps, _amount);
}
function _invest(uint208 _poolId, uint16 _swaps, uint _amount) internal virtual {
if (_amount == 0)
revert InvalidAmount();
PoolInfo storage pool = poolInfo[_poolId];
uint amountPerSwap = _amount / _swaps;
uint16 finalSwap = pool.performedSwaps + _swaps;
pool.nextSwapAmount += amountPerSwap;
endingPositionDeduction[_poolId][finalSwap + 1] += amountPerSwap;
uint positionId = positionInfo[msg.sender].length;
positionInfo[msg.sender].push(
PositionInfo({
swaps: _swaps,
amountPerSwap: amountPerSwap,
poolId: _poolId,
finalSwap: finalSwap,
lastUpdateSwap: pool.performedSwaps
})
);
emit PositionCreated(msg.sender, _poolId, positionId, _swaps, amountPerSwap, finalSwap);
}
function swap(SwapInfo[] calldata swapInfo) external virtual {
if (msg.sender != swapper)
revert CallerIsNotSwapper();
uint timestamp = block.timestamp;
for (uint32 i; i < swapInfo.length; ++i) {
uint208 poolId = swapInfo[i].poolId;
if (poolId >= poolInfo.length)
revert InvalidPoolId();
PoolInfo storage pool = poolInfo[poolId];
if (timestamp < pool.lastSwapTimestamp + pool.interval)
revert TooEarlyToSwap(pool.lastSwapTimestamp + pool.interval - timestamp);
uint inputTokenAmount = pool.nextSwapAmount;
if (inputTokenAmount == 0)
revert NoTokensToSwap();
uint contractBalanceBeforeSwap = IERC20Upgradeable(pool.outputToken).balanceOf(address(this));
IERC20Upgradeable(pool.inputToken).safeApprove(pool.router, inputTokenAmount);
ISwapRouter(pool.router).exactInput(ISwapRouter.ExactInputParams({
path: pool.path,
recipient: address(this),
deadline: timestamp,
amountIn: inputTokenAmount,
amountOutMinimum: swapInfo[i].minOutputAmount
}));
uint outputTokenAmount = IERC20Upgradeable(pool.outputToken).balanceOf(address(this)) - contractBalanceBeforeSwap;
uint swapQuote = (outputTokenAmount * SWAP_QUOTE_PRECISION) / inputTokenAmount;
mapping(uint16 => uint) storage poolAccruedQuotes = accruedSwapQuoteByPool[poolId];
poolAccruedQuotes[pool.performedSwaps + 1] = poolAccruedQuotes[pool.performedSwaps] + swapQuote;
pool.performedSwaps += 1;
pool.nextSwapAmount -= endingPositionDeduction[poolId][pool.performedSwaps + 1];
pool.lastSwapTimestamp = timestamp;
emit Swap(poolId, inputTokenAmount, outputTokenAmount);
}
}
function closePosition(uint _positionId) external virtual {
PositionInfo[] storage userPositions = positionInfo[msg.sender];
if (_positionId >= userPositions.length)
revert InvalidPositionId();
PositionInfo storage position = userPositions[_positionId];
PoolInfo storage pool = poolInfo[position.poolId];
uint inputTokenAmount = _calculateInputTokenBalance(msg.sender, _positionId);
uint outputTokenAmount = _calculateOutputTokenBalance(msg.sender, _positionId);
if (position.finalSwap > pool.performedSwaps) {
pool.nextSwapAmount -= position.amountPerSwap;
endingPositionDeduction[position.poolId][position.finalSwap + 1] -= position.amountPerSwap;
}
position.lastUpdateSwap = pool.performedSwaps;
position.amountPerSwap = 0;
if (inputTokenAmount > 0)
IERC20Upgradeable(pool.inputToken).safeTransfer(msg.sender, inputTokenAmount);
if (outputTokenAmount > 0)
IERC20Upgradeable(pool.outputToken).safeTransfer(msg.sender, outputTokenAmount);
emit PositionClosed(msg.sender, _positionId, inputTokenAmount, outputTokenAmount);
}
function collectPosition(uint _positionId) external virtual {
PositionInfo[] storage userPositions = positionInfo[msg.sender];
if (_positionId >= userPositions.length)
revert InvalidPositionId();
PositionInfo storage position = userPositions[_positionId];
PoolInfo memory pool = poolInfo[position.poolId];
uint outputTokenAmount = _calculateOutputTokenBalance(msg.sender, _positionId);
position.lastUpdateSwap = pool.performedSwaps;
IERC20Upgradeable(pool.outputToken).safeTransfer(msg.sender, outputTokenAmount);
emit PositionCollected(msg.sender, _positionId, outputTokenAmount);
}
function setPoolRouterAndPath(
uint208 _poolId,
address _router,
bytes calldata _path
) external virtual onlyOwner {
setPoolPath(_poolId, _path);
setPoolRouter(_poolId, _router);
}
function setSwapper(address _swapper) external virtual onlyOwner {
if (_swapper == address(0))
revert InvalidZeroAddress();
emit SetSwapper(swapper, _swapper);
swapper = _swapper;
}
function getPoolsLength() external virtual view returns (uint) {
return poolInfo.length;
}
function getPool(uint208 poolId) public virtual view returns (PoolInfo memory) {
return poolInfo[poolId];
}
function getPositionsLength(address _user) external virtual view returns (uint) {
return positionInfo[_user].length;
}
function getPosition(address _user, uint _positionId) external virtual view returns (PositionInfo memory) {
if (_positionId >= positionInfo[_user].length)
revert InvalidPositionId();
return positionInfo[_user][_positionId];
}
function getPositions(address _user) external virtual view returns (PositionInfo[] memory) {
return positionInfo[_user];
}
function getPositionBalances(
address _user,
uint _positionId
) public virtual view returns (
uint inputTokenBalance,
uint outputTokenBalance
) {
inputTokenBalance = _calculateInputTokenBalance(_user, _positionId);
outputTokenBalance = _calculateOutputTokenBalance(_user, _positionId);
}
function poolPath(uint208 _poolId) external virtual view returns (bytes memory path) {
if (_poolId >= poolInfo.length)
revert InvalidPoolId();
return poolInfo[_poolId].path;
}
function setPoolPath(uint208 _poolId, bytes calldata _path) public virtual onlyOwner {
if (_poolId >= poolInfo.length)
revert InvalidPoolId();
PoolInfo storage pool = poolInfo[_poolId];
(address firstToken, address lastToken) = extractAddresses(_path);
if (firstToken != pool.inputToken || lastToken != pool.outputToken)
revert InvalidPoolPath();
emit SetPoolPath(_poolId, pool.path, _path);
pool.path = _path;
}
function setPoolRouter(uint208 _poolId, address _router) public virtual onlyOwner {
if (_router == address(0))
revert InvalidZeroAddress();
address oldRouter = poolInfo[_poolId].router;
poolInfo[_poolId].router = _router;
emit SetPoolRouter(_poolId, oldRouter, _router);
}
function _calculateOutputTokenBalance(address _user, uint _positionId) internal virtual view returns (uint) {
PositionInfo memory position = positionInfo[_user][_positionId];
PoolInfo memory pool = poolInfo[position.poolId];
uint16 swapToConsider = MathHelpers.minU16(pool.performedSwaps, position.finalSwap);
// @dev This means that the last interaction was happened before a new swap happened
// and the user already withdrawn all the output tokens
if (position.lastUpdateSwap > swapToConsider)
return 0;
uint quoteAtMostRecentSwap = accruedSwapQuoteByPool[position.poolId][swapToConsider];
uint quoteAtLastUpdate = accruedSwapQuoteByPool[position.poolId][position.lastUpdateSwap];
uint positionAccumulatedRatio = quoteAtMostRecentSwap - quoteAtLastUpdate;
return positionAccumulatedRatio * position.amountPerSwap / SWAP_QUOTE_PRECISION;
}
function _calculateInputTokenBalance(
address _user,
uint _positionId
) internal virtual view returns (uint) {
PositionInfo memory position = positionInfo[_user][_positionId];
uint performedSwaps = poolInfo[position.poolId].performedSwaps;
if (position.finalSwap < performedSwaps)
return 0;
return (position.finalSwap - performedSwaps) * position.amountPerSwap;
}
// Extracts the first and last addresses from the given bytes data
function extractAddresses(
bytes memory data
) internal pure returns (
address _inputToken,
address _outputToken
) {
if (data.length < 40)
revert InvalidPoolPath();
// Initialize variables for addresses
uint firstAddressBytes;
uint lastAddressBytes;
// Calculate the offset for the start of the last address
uint lastAddressOffset = data.length - 20;
// To extract the first address, load the first 20 bytes as an address directly
assembly {
firstAddressBytes := mload(add(data, 20))
}
// To Extracting the last address, load the last 20 bytes as an address
assembly {
lastAddressBytes := mload(add(data, add(lastAddressOffset, 20)))
}
_inputToken = address(uint160(firstAddressBytes));
_outputToken = address(uint160(lastAddressBytes));
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
library MathHelpers {
function min(uint _a, uint _b) internal pure returns (uint) {
return _a > _b ? _b : _a;
}
function minU16(uint16 _a, uint16 _b) internal pure returns (uint16) {
return _a > _b ? _b : _a;
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {INonfungiblePositionManager} from '../interfaces/INonfungiblePositionManager.sol';
library PairHelpers {
struct Pair {
address token0;
address token1;
}
function getBalances(
Pair memory _pair,
address _owner
) internal view returns (uint balance0, uint balance1) {
balance0 = IERC20Upgradeable(_pair.token0).balanceOf(_owner);
balance1 = IERC20Upgradeable(_pair.token1).balanceOf(_owner);
}
function fromLiquidityToken(
INonfungiblePositionManager _positionManager,
uint _tokenId
) internal view returns (Pair memory pair) {
(,, address token0, address token1,,,,,,,,) = _positionManager.positions(_tokenId);
return Pair(token0, token1);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IBeefyVaultV7 is IERC20Upgradeable {
function want() external view returns (IERC20Upgradeable);
function balance() external view returns (uint);
function available() external view returns (uint256);
function getPricePerFullShare() external view returns (uint256);
function depositAll() external;
function deposit(uint _amount) external;
function earn() external;
function withdrawAll() external;
function withdraw(uint256 _shares) external;
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
interface ICall {
error LowLevelCallFailed(address to, bytes inputData, bytes revertData);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
import '@uniswap/v3-periphery/contracts/interfaces/IPoolInitializer.sol';
import '@uniswap/v3-periphery/contracts/interfaces/IERC721Permit.sol';
import '@uniswap/v3-periphery/contracts/interfaces/IPeripheryPayments.sol';
import '@uniswap/v3-periphery/contracts/interfaces/IPeripheryImmutableState.sol';
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is IPoolInitializer, IPeripheryPayments, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit {
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId) external view returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params) external payable returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (
uint256 amount0,
uint256 amount1
);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.24;
interface IUniversalRouter {
/// @notice Thrown when a required command has failed
error ExecutionFailed(uint256 commandIndex, bytes message);
/// @notice Thrown when attempting to send ETH directly to the contract
error ETHNotAccepted();
/// @notice Thrown when executing commands with an expired deadline
error TransactionDeadlinePassed();
/// @notice Thrown when attempting to execute commands and an incorrect number of inputs are provided
error LengthMismatch();
// @notice Thrown when an address that isn't WETH tries to send ETH to the router without calldata
error InvalidEthSender();
/// @notice Executes encoded commands along with provided inputs. Reverts if deadline has expired.
/// @param commands A set of concatenated commands, each 1 byte in length
/// @param inputs An array of byte strings containing abi encoded inputs for each command
/// @param deadline The deadline by which the transaction must be executed
function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline) external payable;
/// @notice Executes encoded commands along with provided inputs.
/// @param commands A set of concatenated commands, each 1 byte in length
/// @param inputs An array of byte strings containing abi encoded inputs for each command
function execute(bytes calldata commands, bytes[] calldata inputs) external payable;
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Upgradeable, SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IUniversalRouter} from "../interfaces/IUniversalRouter.sol";
library HubRouter {
using SafeERC20Upgradeable for IERC20Upgradeable;
error InvalidSwap();
struct SwapData {
IUniversalRouter router;
bytes commands;
bytes[] inputs;
}
/**
* @notice Performs a zap operation using the specified protocol call data.
* @param _encodedSwapData - Encoded version of `SwapData`
* @param _inputToken - The ERC20 token to be sold.
* @param _outputToken - The ERC20 token to be bought.
* @param _amount - Amount of input tokens to be sold
* @return outputAmount - The amount of output tokens bought. If no zap is needed, returns the input token amount.
*/
function execute(
bytes memory _encodedSwapData,
IERC20Upgradeable _inputToken,
IERC20Upgradeable _outputToken,
uint _amount
) internal returns (uint outputAmount) {
if (_encodedSwapData.length == 0) {
if (_inputToken == _outputToken || _amount == 0)
return _amount;
else
revert InvalidSwap();
}
uint initialOutputBalance = _outputToken.balanceOf(address(this));
SwapData memory swapData = _decodeSwapData(_encodedSwapData);
_inputToken.safeTransfer(address(swapData.router), _amount);
swapData.router.execute(swapData.commands, swapData.inputs);
return _outputToken.balanceOf(address(this)) - initialOutputBalance;
}
/**
* @notice Performs a zap operation using the specified protocol call data.
* @param _encodedSwapData - Encoded version of `SwapData`. Must include WRAP_ETH command.
* @param _outputToken - The ERC20 token to be bought.
* @return outputAmount - The amount of output tokens bought. If no zap is needed, returns the input token amount.
*/
function executeNative(
bytes memory _encodedSwapData,
IERC20Upgradeable _outputToken
) internal returns (uint outputAmount) {
if (_encodedSwapData.length == 0)
revert InvalidSwap();
uint initialOutputBalance = _outputToken.balanceOf(address(this));
SwapData memory swapData = _decodeSwapData(_encodedSwapData);
swapData.router.execute{value: msg.value}(swapData.commands, swapData.inputs);
return _outputToken.balanceOf(address(this)) - initialOutputBalance;
}
function _decodeSwapData(bytes memory _encodedSwapData) internal pure returns (SwapData memory) {
return abi.decode(_encodedSwapData, (SwapData));
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
library ReferralStorage {
bytes32 constant private REFERRAL_STORAGE_POSITION = keccak256("referral.storage");
struct ReferralStruct {
mapping(address => bool) investedBefore;
mapping(address => address) referrals;
mapping(address => uint) referrerRewards;
uint32 referrerPercentage;
}
function getReferralStruct() internal pure returns (ReferralStruct storage referralStruct) {
bytes32 position = REFERRAL_STORAGE_POSITION;
assembly {
referralStruct.slot := position
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Upgradeable, SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {INonfungiblePositionManager} from "./interfaces/INonfungiblePositionManager.sol";
import {HubOwnable} from "./abstract/HubOwnable.sol";
import {OnlyStrategyManager} from "./abstract/OnlyStrategyManager.sol";
import {UseFee} from "./abstract/UseFee.sol";
import {UseDust} from "./abstract/UseDust.sol";
import {HubRouter} from "./libraries/HubRouter.sol";
import {SubscriptionManager} from "./SubscriptionManager.sol";
contract LiquidityManager is HubOwnable, UseFee, UseDust, OnlyStrategyManager {
using SafeERC20Upgradeable for IERC20Upgradeable;
struct InitializeParams {
address owner;
address treasury;
address subscriptionManager;
address strategyManager;
// @deprecated must keep variable to maintain storage layout
address zapManager;
uint32 baseFeeBP;
uint32 nonSubscriberFeeBP;
}
struct InvestUniswapV3Params {
address positionManager;
IERC20Upgradeable inputToken;
IERC20Upgradeable token0;
IERC20Upgradeable token1;
uint24 fee;
uint depositAmountInputToken;
bytes swapToken0;
bytes swapToken1;
uint swapAmountToken0;
uint swapAmountToken1;
int24 tickLower;
int24 tickUpper;
uint amount0Min;
uint amount1Min;
}
// @deprecated must keep variable to maintain storage layout
address public zapManager;
event PositionCreated(address user, address positionManager, uint tokenId, uint128 liquidity);
error InsufficientFunds(uint requested, uint available);
error InvalidInvestment();
function initialize(InitializeParams calldata _params) external initializer {
__Ownable_init();
__UseFee_init(
_params.treasury,
_params.subscriptionManager,
_params.baseFeeBP,
_params.nonSubscriberFeeBP
);
__OnlyStrategyManager_init(_params.strategyManager);
transferOwnership(_params.owner);
zapManager = _params.zapManager;
}
function investUniswapV3(
InvestUniswapV3Params calldata _params,
SubscriptionManager.Permit calldata _subscriptionPermit
) external virtual returns (
uint tokenId,
uint128 liquidity
) {
uint remainingAmount = _pullFunds(
address(_params.inputToken),
_params.depositAmountInputToken,
abi.encode(_params.inputToken, _params.token0, _params.token1, _params.fee),
_subscriptionPermit
);
uint requested = _params.swapAmountToken0 + _params.swapAmountToken1;
if (requested > remainingAmount)
revert InsufficientFunds(requested, remainingAmount);
if (_params.token0 >= _params.token1)
revert InvalidInvestment();
return _investUniswapV3(_params);
}
function investUniswapV3UsingStrategy(
InvestUniswapV3Params calldata _params
) external virtual onlyStrategyManager returns (
uint tokenId,
uint128 liquidity
) {
return _investUniswapV3(_params);
}
function _investUniswapV3(
InvestUniswapV3Params calldata _params
) internal virtual returns (
uint tokenId,
uint128 liquidity
) {
uint inputAmount0 = HubRouter.execute(
_params.swapToken0,
_params.inputToken,
_params.token0,
_params.swapAmountToken0
);
uint inputAmount1 = HubRouter.execute(
_params.swapToken1,
_params.inputToken,
_params.token1,
_params.swapAmountToken1
);
_params.token0.safeIncreaseAllowance(address(_params.positionManager), inputAmount0);
_params.token1.safeIncreaseAllowance(address(_params.positionManager), inputAmount1);
(tokenId, liquidity,,) = INonfungiblePositionManager(_params.positionManager).mint(
INonfungiblePositionManager.MintParams({
token0: address(_params.token0),
token1: address(_params.token1),
fee: _params.fee,
tickLower: _params.tickLower,
tickUpper: _params.tickUpper,
amount0Desired: inputAmount0,
amount1Desired: inputAmount1,
amount0Min: _params.amount0Min,
amount1Min: _params.amount1Min,
recipient: msg.sender,
deadline: block.timestamp
})
);
emit PositionCreated(msg.sender, _params.positionManager, tokenId, liquidity);
}
function sendDust(IERC20Upgradeable _token, address _to) external virtual onlyStrategyManager {
_sendDust(_token, _to);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Upgradeable, SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {HubOwnable} from "./abstract/HubOwnable.sol";
import {UseFee} from "./abstract/UseFee.sol";
import {StrategyStorage} from "./abstract/StrategyStorage.sol";
import {StrategyInvestor} from "./abstract/StrategyInvestor.sol";
import {StrategyPositionManager} from "./abstract/StrategyPositionManager.sol";
import {ICall} from './interfaces/ICall.sol';
import {SubscriptionManager} from "./SubscriptionManager.sol";
import {LiquidityManager} from './LiquidityManager.sol';
import {VaultManager} from "./VaultManager.sol";
import {DollarCostAverage} from './DollarCostAverage.sol';
contract StrategyManager is StrategyStorage, HubOwnable, ICall {
using SafeERC20Upgradeable for IERC20Upgradeable;
struct InitializeParams {
address owner;
address treasury;
address strategyInvestor;
address strategyPositionManager;
IERC20Upgradeable stable;
SubscriptionManager subscriptionManager;
DollarCostAverage dca;
VaultManager vaultManager;
LiquidityManager liquidityManager;
UseFee buyProduct;
// @deprecated must keep variable to maintain storage layout
address zapManager;
uint8 maxHottestStrategies;
uint32 strategistPercentage;
uint32 hotStrategistPercentage;
}
struct CreateStrategyParams {
DcaInvestment[] dcaInvestments;
VaultInvestment[] vaultInvestments;
LiquidityInvestment[] liquidityInvestments;
BuyInvestment[] buyInvestments;
SubscriptionManager.Permit permit;
bytes32 metadataHash;
}
struct InvestInProductParams {
uint strategyId;
uint amount;
bytes[] swaps;
}
address public strategyInvestor;
address public strategyPositionManager;
event StrategyCreated(address strategist, uint strategyId, bytes32 metadataHash);
event CollectedStrategistRewards(address strategist, uint amount);
event StrategistPercentageUpdated(uint32 discountPercentage);
event HotStrategistPercentageUpdated(uint32 discountPercentage);
event HottestStrategiesUpdated(uint[] strategies);
event MaxHotStrategiesUpdated(uint8 max);
error Unauthorized();
error LimitExceeded();
error InvalidTotalPercentage();
error InvalidInvestment();
error PercentageTooHigh();
function initialize(InitializeParams calldata _initializeParams) external initializer {
__Ownable_init();
setMaxHottestStrategies(_initializeParams.maxHottestStrategies);
setStrategistPercentage(_initializeParams.strategistPercentage);
setHotStrategistPercentage(_initializeParams.hotStrategistPercentage);
setTreasury(_initializeParams.treasury);
transferOwnership(_initializeParams.owner);
strategyInvestor = _initializeParams.strategyInvestor;
strategyPositionManager = _initializeParams.strategyPositionManager;
stable = _initializeParams.stable;
subscriptionManager = _initializeParams.subscriptionManager;
dca = _initializeParams.dca;
vaultManager = _initializeParams.vaultManager;
liquidityManager = _initializeParams.liquidityManager;
buyProduct = _initializeParams.buyProduct;
}
function createStrategy(CreateStrategyParams memory _params) external virtual {
uint investmentCount = _params.dcaInvestments.length + _params.vaultInvestments.length;
if (!subscriptionManager.isSubscribed(msg.sender, _params.permit))
revert Unauthorized();
if (investmentCount > 20)
revert LimitExceeded();
uint8 dcaPercentage;
uint8 vaultPercentage;
uint8 liquidityPercentage;
uint8 tokenPercentage;
for (uint i; i < _params.dcaInvestments.length; ++i)
dcaPercentage += _params.dcaInvestments[i].percentage;
for (uint i; i < _params.vaultInvestments.length; ++i)
vaultPercentage += _params.vaultInvestments[i].percentage;
for (uint i; i < _params.liquidityInvestments.length; ++i)
liquidityPercentage += _params.liquidityInvestments[i].percentage;
for (uint i; i < _params.buyInvestments.length; ++i)
tokenPercentage += _params.buyInvestments[i].percentage;
if (dcaPercentage + vaultPercentage + liquidityPercentage + tokenPercentage != 100)
revert InvalidTotalPercentage();
uint strategyId = _strategies.length;
Strategy storage strategy = _strategies.push();
strategy.creator = msg.sender;
strategy.percentages[PRODUCT_DCA] = dcaPercentage;
strategy.percentages[PRODUCT_VAULTS] = vaultPercentage;
strategy.percentages[PRODUCT_LIQUIDITY] = liquidityPercentage;
strategy.percentages[PRODUCT_BUY] = tokenPercentage;
// Assigning isn't possible because you can't convert an array of structs from memory to storage
for (uint i; i < _params.dcaInvestments.length; ++i) {
DcaInvestment memory dcaStrategy = _params.dcaInvestments[i];
if (dcaStrategy.poolId >= dca.getPoolsLength())
revert DollarCostAverage.InvalidPoolId();
if (dcaStrategy.swaps == 0)
revert DollarCostAverage.InvalidNumberOfSwaps();
_dcaInvestmentsPerStrategy[strategyId].push(dcaStrategy);
}
for (uint i; i < _params.vaultInvestments.length; ++i) {
VaultInvestment memory vaultStrategy = _params.vaultInvestments[i];
_vaultInvestmentsPerStrategy[strategyId].push(vaultStrategy);
}
for (uint i; i < _params.liquidityInvestments.length; ++i) {
LiquidityInvestment memory liquidityStrategy = _params.liquidityInvestments[i];
if (
liquidityStrategy.token0 >= liquidityStrategy.token1 ||
liquidityStrategy.lowerBound >= liquidityStrategy.upperBound
)
revert InvalidInvestment();
_liquidityInvestmentsPerStrategy[strategyId].push(liquidityStrategy);
}
for (uint i; i < _params.buyInvestments.length; ++i)
_buyInvestmentsPerStrategy[strategyId].push(_params.buyInvestments[i]);
emit StrategyCreated(msg.sender, strategyId, _params.metadataHash);
}
function invest(StrategyInvestor.InvestParams calldata _params) external virtual {
_makeDelegateCall(
strategyInvestor,
abi.encodeWithSelector(StrategyInvestor.invest.selector, _params)
);
}
function closePosition(
uint _positionId,
StrategyPositionManager.LiquidityMinOutputs[] calldata _liquidityMinOutputs
) external virtual {
_makeDelegateCall(
strategyPositionManager,
abi.encodeWithSelector(StrategyPositionManager.closePosition.selector, _positionId, _liquidityMinOutputs)
);
}
function collectPosition(uint _positionId) external virtual {
_makeDelegateCall(
strategyPositionManager,
abi.encodeWithSelector(StrategyPositionManager.collectPosition.selector, _positionId)
);
}
function collectStrategistRewards() public virtual {
uint strategistReward = _strategistRewards[msg.sender];
_strategistRewards[msg.sender] = 0;
stable.safeTransfer(msg.sender, strategistReward);
emit CollectedStrategistRewards(msg.sender, strategistReward);
}
/**
* ----- Getters -----
*/
function getStrategistRewards(address _strategist) external virtual view returns (uint) {
return _strategistRewards[_strategist];
}
function getPositionsLength(address _investor) external virtual view returns (uint) {
return _positions[_investor].length;
}
function getPosition(
address _investor,
uint _index
) external virtual view returns (Position memory) {
return _positions[_investor][_index];
}
function getPositionInvestments(
address _investor,
uint _positionId
) external virtual view returns (
uint[] memory dcaPositions,
VaultPosition[] memory vaultPositions,
LiquidityPosition[] memory liquidityPositions,
BuyPosition[] memory buyPositions
) {
return (
_dcaPositionsPerPosition[_investor][_positionId],
_vaultPositionsPerPosition[_investor][_positionId],
_liquidityPositionsPerPosition[_investor][_positionId],
_buyPositionsPerPosition[_investor][_positionId]
);
}
function getPositions(address _investor) external virtual view returns (Position[] memory) {
return _positions[_investor];
}
function getStrategyCreator(uint _strategyId) external virtual view returns (address) {
return _strategies[_strategyId].creator;
}
function getStrategyInvestments(
uint _strategyId
) external virtual view returns (
DcaInvestment[] memory dcaInvestments,
VaultInvestment[] memory vaultInvestments,
LiquidityInvestment[] memory liquidityInvestments,
BuyInvestment[] memory buyInvestments
) {
return (
_dcaInvestmentsPerStrategy[_strategyId],
_vaultInvestmentsPerStrategy[_strategyId],
_liquidityInvestmentsPerStrategy[_strategyId],
_buyInvestmentsPerStrategy[_strategyId]
);
}
function getStrategiesLength() external virtual view returns (uint) {
return _strategies.length;
}
function getHotStrategies() external virtual view returns (uint[] memory) {
return _hottestStrategiesArray;
}
function isHot(uint _strategyId) external virtual view returns (bool) {
return _hottestStrategiesMapping[_strategyId];
}
/**
* ----- Internal functions -----
*/
function _makeDelegateCall(
address _target,
bytes memory _callData
) internal returns (
bytes memory
) {
(bool success, bytes memory resultData) = _target.delegatecall(_callData);
if (!success)
revert LowLevelCallFailed(_target, "", resultData);
return resultData;
}
/**
* ----- Contract management -----
*/
function setStrategistPercentage(uint32 _strategistPercentage) public virtual onlyOwner {
if (_strategistPercentage > 100)
revert PercentageTooHigh();
strategistPercentage = _strategistPercentage;
emit StrategistPercentageUpdated(_strategistPercentage);
}
function setHotStrategistPercentage(uint32 _hotStrategistPercentage) public virtual onlyOwner {
if (_hotStrategistPercentage > 100)
revert PercentageTooHigh();
hotStrategistPercentage = _hotStrategistPercentage;
emit HotStrategistPercentageUpdated(_hotStrategistPercentage);
}
function setHottestStrategies(uint[] calldata _strategyIds) external virtual onlyOwner {
if (_strategyIds.length > maxHottestStrategies)
revert LimitExceeded();
for (uint i; i < _hottestStrategiesArray.length; ++i)
_hottestStrategiesMapping[_hottestStrategiesArray[i]] = false;
for (uint i; i < _strategyIds.length; ++i)
_hottestStrategiesMapping[_strategyIds[i]] = true;
_hottestStrategiesArray = _strategyIds;
emit HottestStrategiesUpdated(_strategyIds);
}
function setMaxHottestStrategies(uint8 _maxHottestStrategies) public virtual onlyOwner {
maxHottestStrategies = _maxHottestStrategies;
emit MaxHotStrategiesUpdated(_maxHottestStrategies);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Upgradeable, SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {ECDSAUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import {EIP712Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import {HubOwnable} from "./abstract/HubOwnable.sol";
import {UseTreasury} from "./abstract/UseTreasury.sol";
contract SubscriptionManager is HubOwnable, UseTreasury, EIP712Upgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
struct InitializeParams {
address owner;
address treasury;
address subscriptionSigner;
IERC20Upgradeable token;
uint pricePerMonth;
}
struct Permit {
// deadline isn't the same as a subscription end date, it's just a deadline for the signature
uint deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
bytes32 private constant _PERMIT_TYPEHASH = keccak256("SubscriptionPermit(address user,uint256 deadline)");
address public subscriptionSigner;
IERC20Upgradeable public token;
uint public pricePerMonth;
uint constant public ONE_MONTH = 30 days;
event Subscribed(address user);
event SubscriptionSignerUpdated(address subscriptionSigner);
event PricePerMonthUpdated(uint pricePerMonth);
error PermitExpired();
error InvalidSignature();
error InvalidSubscriberFee();
function initialize(InitializeParams calldata _initializeParams) initializer public {
__Ownable_init();
__EIP712_init_unchained('defihub.fi', "1");
setTreasury(_initializeParams.treasury);
transferOwnership(_initializeParams.owner);
subscriptionSigner = _initializeParams.subscriptionSigner;
token = _initializeParams.token;
pricePerMonth = _initializeParams.pricePerMonth;
}
function subscribe() external virtual {
token.safeTransferFrom(msg.sender, treasury, getCost());
emit Subscribed(msg.sender);
}
function getCost() public virtual view returns (uint) {
return pricePerMonth * 12;
}
function isSubscribed(address _user, Permit calldata _permit) external virtual view returns (bool) {
if (_user == address(0) || _permit.deadline == 0)
return false;
if (_permit.deadline < block.timestamp)
revert PermitExpired();
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, _user, _permit.deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address recoveredSigner = ECDSAUpgradeable.recover(hash, _permit.v, _permit.r, _permit.s);
if (recoveredSigner != subscriptionSigner)
revert InvalidSignature();
return true;
}
function setSubscriptionSigner(address _subscriptionSigner) external virtual onlyOwner {
subscriptionSigner = _subscriptionSigner;
emit SubscriptionSignerUpdated(_subscriptionSigner);
}
function setSubscriptionPrice(uint _pricePerMonth) external virtual onlyOwner {
pricePerMonth = _pricePerMonth;
emit PricePerMonthUpdated(_pricePerMonth);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {IERC20Upgradeable, SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IBeefyVaultV7} from "./interfaces/IBeefyVaultV7.sol";
import {HubOwnable} from "./abstract/HubOwnable.sol";
import {OnlyStrategyManager} from "./abstract/OnlyStrategyManager.sol";
import {UseFee} from "./abstract/UseFee.sol";
import {SubscriptionManager} from "./SubscriptionManager.sol";
contract VaultManager is HubOwnable, UseFee, OnlyStrategyManager {
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeERC20Upgradeable for IBeefyVaultV7;
struct InitializeParams {
address owner;
address treasury;
address strategyManager;
address subscriptionManager;
uint32 baseFeeBP;
uint32 nonSubscriberFeeBP;
}
event PositionCreated(address user, address vault, uint amount);
function initialize(InitializeParams calldata _initializeParams) public initializer {
__Ownable_init();
__UseFee_init(
_initializeParams.treasury,
_initializeParams.subscriptionManager,
_initializeParams.baseFeeBP,
_initializeParams.nonSubscriberFeeBP
);
__OnlyStrategyManager_init(_initializeParams.strategyManager);
transferOwnership(_initializeParams.owner);
}
function invest(
address _vault,
uint _amount,
SubscriptionManager.Permit calldata _permit
) external {
IERC20Upgradeable want = IBeefyVaultV7(_vault).want();
_invest(
_vault,
_pullFunds(
address(want),
_amount,
abi.encode(_vault),
_permit
)
);
}
function investUsingStrategy(
address _vault,
uint _amount
) external virtual onlyStrategyManager {
_invest(_vault, _amount);
}
function _invest(address _vault, uint _amount) internal virtual {
IBeefyVaultV7 vault = IBeefyVaultV7(_vault);
IERC20Upgradeable want = vault.want();
want.safeIncreaseAllowance(_vault, _amount);
vault.deposit(_amount);
vault.safeTransfer(msg.sender, vault.balanceOf(address(this)));
emit PositionCreated(msg.sender, _vault, _amount);
}
}{
"optimizer": {
"enabled": true,
"runs": 800
},
"evmVersion": "paris",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"buyProduct","outputs":[{"internalType":"address","name":"implementation","type":"address"},{"internalType":"address","name":"proxy","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dca","outputs":[{"internalType":"address","name":"implementation","type":"address"},{"internalType":"address","name":"proxy","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"_code","type":"bytes"},{"internalType":"bytes32","name":"_salt","type":"bytes32"}],"name":"deploy","outputs":[{"internalType":"address","name":"addr","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"code","type":"bytes"},{"internalType":"bytes32","name":"implementationSalt","type":"bytes32"},{"internalType":"bytes32","name":"proxySalt","type":"bytes32"}],"internalType":"struct GenericDeployer.ProxyDeploymentInfo","name":"_buyProductDeploymentInfo","type":"tuple"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"treasury","type":"address"},{"internalType":"address","name":"subscriptionManager","type":"address"},{"internalType":"uint32","name":"baseFeeBP","type":"uint32"},{"internalType":"uint32","name":"nonSubscriberFeeBP","type":"uint32"}],"internalType":"struct BuyProduct.InitializeParams","name":"_buyProductParams","type":"tuple"}],"name":"deployBuyProduct","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"code","type":"bytes"},{"internalType":"bytes32","name":"implementationSalt","type":"bytes32"},{"internalType":"bytes32","name":"proxySalt","type":"bytes32"}],"internalType":"struct GenericDeployer.ProxyDeploymentInfo","name":"_dcaDeploymentInfo","type":"tuple"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"treasury","type":"address"},{"internalType":"address","name":"swapper","type":"address"},{"internalType":"address","name":"strategyManager","type":"address"},{"internalType":"address","name":"subscriptionManager","type":"address"},{"internalType":"uint32","name":"baseFeeBP","type":"uint32"},{"internalType":"uint32","name":"nonSubscriberFeeBP","type":"uint32"}],"internalType":"struct DollarCostAverage.InitializeParams","name":"_dcaParams","type":"tuple"}],"name":"deployDca","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"code","type":"bytes"},{"internalType":"bytes32","name":"implementationSalt","type":"bytes32"},{"internalType":"bytes32","name":"proxySalt","type":"bytes32"}],"internalType":"struct GenericDeployer.ProxyDeploymentInfo","name":"_liquidityManagerDeploymentInfo","type":"tuple"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"treasury","type":"address"},{"internalType":"address","name":"subscriptionManager","type":"address"},{"internalType":"address","name":"strategyManager","type":"address"},{"internalType":"address","name":"zapManager","type":"address"},{"internalType":"uint32","name":"baseFeeBP","type":"uint32"},{"internalType":"uint32","name":"nonSubscriberFeeBP","type":"uint32"}],"internalType":"struct LiquidityManager.InitializeParams","name":"_liquidityManagerParams","type":"tuple"}],"name":"deployLiquidityManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"code","type":"bytes"},{"internalType":"bytes32","name":"implementationSalt","type":"bytes32"},{"internalType":"bytes32","name":"proxySalt","type":"bytes32"}],"internalType":"struct GenericDeployer.ProxyDeploymentInfo","name":"_deployInfo","type":"tuple"}],"name":"deployProxy","outputs":[{"components":[{"internalType":"address","name":"implementation","type":"address"},{"internalType":"address","name":"proxy","type":"address"}],"internalType":"struct GenericDeployer.ProxyAddress","name":"","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"_code","type":"bytes"},{"internalType":"bytes32","name":"_salt","type":"bytes32"}],"name":"deployStrategyInvestor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"code","type":"bytes"},{"internalType":"bytes32","name":"implementationSalt","type":"bytes32"},{"internalType":"bytes32","name":"proxySalt","type":"bytes32"}],"internalType":"struct GenericDeployer.ProxyDeploymentInfo","name":"_strategyManagerDeploymentInfo","type":"tuple"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"treasury","type":"address"},{"internalType":"address","name":"strategyInvestor","type":"address"},{"internalType":"address","name":"strategyPositionManager","type":"address"},{"internalType":"contract IERC20Upgradeable","name":"stable","type":"address"},{"internalType":"contract SubscriptionManager","name":"subscriptionManager","type":"address"},{"internalType":"contract DollarCostAverage","name":"dca","type":"address"},{"internalType":"contract VaultManager","name":"vaultManager","type":"address"},{"internalType":"contract LiquidityManager","name":"liquidityManager","type":"address"},{"internalType":"contract UseFee","name":"buyProduct","type":"address"},{"internalType":"address","name":"zapManager","type":"address"},{"internalType":"uint8","name":"maxHottestStrategies","type":"uint8"},{"internalType":"uint32","name":"strategistPercentage","type":"uint32"},{"internalType":"uint32","name":"hotStrategistPercentage","type":"uint32"}],"internalType":"struct StrategyManager.InitializeParams","name":"_strategyManagerParam","type":"tuple"}],"name":"deployStrategyManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"_code","type":"bytes"},{"internalType":"bytes32","name":"_salt","type":"bytes32"}],"name":"deployStrategyPositionManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"code","type":"bytes"},{"internalType":"bytes32","name":"implementationSalt","type":"bytes32"},{"internalType":"bytes32","name":"proxySalt","type":"bytes32"}],"internalType":"struct GenericDeployer.ProxyDeploymentInfo","name":"_subscriptionManagerDeploymentInfo","type":"tuple"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"treasury","type":"address"},{"internalType":"address","name":"subscriptionSigner","type":"address"},{"internalType":"contract IERC20Upgradeable","name":"token","type":"address"},{"internalType":"uint256","name":"pricePerMonth","type":"uint256"}],"internalType":"struct SubscriptionManager.InitializeParams","name":"_subscriptionManagerParams","type":"tuple"}],"name":"deploySubscriptionManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"code","type":"bytes"},{"internalType":"bytes32","name":"implementationSalt","type":"bytes32"},{"internalType":"bytes32","name":"proxySalt","type":"bytes32"}],"internalType":"struct GenericDeployer.ProxyDeploymentInfo","name":"_vaultManagerDeploymentInfo","type":"tuple"},{"components":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"treasury","type":"address"},{"internalType":"address","name":"strategyManager","type":"address"},{"internalType":"address","name":"subscriptionManager","type":"address"},{"internalType":"uint32","name":"baseFeeBP","type":"uint32"},{"internalType":"uint32","name":"nonSubscriberFeeBP","type":"uint32"}],"internalType":"struct VaultManager.InitializeParams","name":"_vaultManagerParams","type":"tuple"}],"name":"deployVaultManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"_code","type":"bytes"},{"internalType":"bytes32","name":"_salt","type":"bytes32"}],"name":"getDeployAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"bytes","name":"code","type":"bytes"},{"internalType":"bytes32","name":"implementationSalt","type":"bytes32"},{"internalType":"bytes32","name":"proxySalt","type":"bytes32"}],"internalType":"struct GenericDeployer.ProxyDeploymentInfo","name":"_deploymentInfo","type":"tuple"}],"name":"getDeployProxyAddress","outputs":[{"components":[{"internalType":"address","name":"implementation","type":"address"},{"internalType":"address","name":"proxy","type":"address"}],"internalType":"struct GenericDeployer.ProxyAddress","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidityManager","outputs":[{"internalType":"address","name":"implementation","type":"address"},{"internalType":"address","name":"proxy","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"strategyInvestor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"strategyManager","outputs":[{"internalType":"address","name":"implementation","type":"address"},{"internalType":"address","name":"proxy","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"strategyPositionManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"subscriptionManager","outputs":[{"internalType":"address","name":"implementation","type":"address"},{"internalType":"address","name":"proxy","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"vaultManager","outputs":[{"internalType":"address","name":"implementation","type":"address"},{"internalType":"address","name":"proxy","type":"address"}],"stateMutability":"view","type":"function"}]Contract Creation Code
0x6080604052348015600f57600080fd5b50601733601b565b606b565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b611a9c8061007a6000396000f3fe608060405234801561001057600080fd5b506004361061018d5760003560e01c8063731d8c9d116100e3578063a9ae90731161008c578063cd89306211610066578063cd893062146103e8578063ed8bf391146103fb578063f2fde38b1461040e57600080fd5b8063a9ae907314610351578063ad9e9b8514610364578063bf158fd2146103ce57600080fd5b80639536b391116100bd5780639536b3911461031157806395c15cda146103245780639ada9b7b1461033757600080fd5b8063731d8c9d146102d35780638a4adf24146102e65780638da5cb5b1461030057600080fd5b8063342df78c116101455780634c7b9b941161011f5780634c7b9b94146102a557806359ce763a146102b8578063715018a6146102cb57600080fd5b8063342df78c1461025e57806339b70e38146102785780634af63f021461029257600080fd5b806321d2be391161017657806321d2be39146101e6578063236ec797146101f9578063338274381461022457600080fd5b80630470b26f146101925780631dc4dd8c146101d1575b600080fd5b6101a56101a0366004610c38565b610421565b6040805182516001600160a01b0390811682526020938401511692810192909252015b60405180910390f35b6101e46101df366004610d83565b610531565b005b6101e46101f4366004610e3b565b610604565b60015461020c906001600160a01b031681565b6040516001600160a01b0390911681526020016101c8565b600954600a5461023e916001600160a01b03908116911682565b604080516001600160a01b039384168152929091166020830152016101c8565b60055460065461023e916001600160a01b03908116911682565b60035460045461023e916001600160a01b03908116911682565b61020c6102a0366004610e3b565b61063a565b6101e46102b3366004610f72565b610661565b60025461020c906001600160a01b031681565b6101e46106c8565b6101e46102e1366004610f72565b6106dc565b60075460085461023e916001600160a01b03908116911682565b6000546001600160a01b031661020c565b6101a561031f366004610c38565b610743565b6101e4610332366004610fd3565b6108f2565b600b54600c5461023e916001600160a01b03908116911682565b6101e461035f36600461112d565b610957565b61020c610372366004610e3b565b8151602092830120604080516001600160f81b0319818601523060601b6bffffffffffffffffffffffff191660218201526035810193909352605580840192909252805180840390920182526075909201909152805191012090565b600d54600e5461023e916001600160a01b03908116911682565b6101e46103f6366004610e3b565b6109f1565b6101e46104093660046111de565b610a27565b6101e461041c3660046112a9565b610ad4565b604080518082019091526000808252602082015261043d610b69565b600061048a61044c84806112cd565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250505050602085013561063a565b9050600061050a604051806020016104a190610c13565b601f1982820381018352601f9091011660408181526001600160a01b0386166020830152808201526000606082015260800160408051601f19818403018152908290526104f1929160200161134b565b604051602081830303815290604052856040013561063a565b604080518082019091526001600160a01b039384168152921660208301525090505b919050565b610539610b69565b61054282610421565b8051600b80546001600160a01b03199081166001600160a01b0393841617909155602092830151600c8054909216908316908117909155604080516356fa66e360e01b815285518416600482015293850151831660248501528401519091166044830152606083015163ffffffff90811660648401526080840151166084830152906356fa66e39060a4015b600060405180830381600087803b1580156105e857600080fd5b505af11580156105fc573d6000803e3d6000fd5b505050505050565b61060c610b69565b610616828261063a565b600280546001600160a01b0319166001600160a01b03929092169190911790555050565b6000610644610b69565b818351602085016000f59050803b61065b57600080fd5b92915050565b610669610b69565b61067282610421565b8051600980546001600160a01b039283166001600160a01b031991821617909155602090920151600a80549190921692168217905560405163f562d8f560e01b815263f562d8f5906105ce9084906004016113ed565b6106d0610b69565b6106da6000610bc3565b565b6106e4610b69565b6106ed82610421565b8051600580546001600160a01b039283166001600160a01b031991821617909155602090920151600680549190921692168217905560405163f562d8f560e01b815263f562d8f5906105ce9084906004016113ed565b604080518082019091526000808252602082015260006107f861076684806112cd565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250508251602093840120604080516001600160f81b0319818701526bffffffffffffffffffffffff193060601b166021820152898601356035820152605580820193909352815180820390930183526075019052805193019290922092915050565b90506040518060400160405280826001600160a01b031681526020016108e06040518060200161082790610c13565b601f1982820381018352601f9091011660408181526001600160a01b0387166020830152808201526000606082015260800160408051601f1981840301815290829052610877929160200161134b565b60408051601f1981840301815282825280516020918201206001600160f81b0319848301526bffffffffffffffffffffffff193060601b166021850152898301356035850152605580850191909152825180850390910181526075909301909152815191012090565b6001600160a01b031690529392505050565b6108fa610b69565b61090382610421565b8051600380546001600160a01b039283166001600160a01b0319918216179091556020909201516004805491909216921682178155604051635d2bafc360e01b8152635d2bafc3916105ce918591016113fb565b61095f610b69565b61096882610421565b8051600d80546001600160a01b03199081166001600160a01b0393841617909155602092830151600e805490921690831690811790915560408051630647c2ad60e11b8152855184166004820152938501518316602485015284015182166044840152606084015190911660648301526080830151608483015290630c8f855a9060a4016105ce565b6109f9610b69565b610a03828261063a565b600180546001600160a01b0319166001600160a01b03929092169190911790555050565b610a2f610b69565b610a3882610421565b8051600780546001600160a01b03199081166001600160a01b0393841617909155602092830151600880549092169083169081179091556040805163039fe95160e61b815285518416600482015293850151831660248501528401518216604484015260608401519091166064830152608083015163ffffffff908116608484015260a08401511660a48301529063e7fa54409060c4016105ce565b610adc610b69565b6001600160a01b038116610b5d5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f646472657373000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b610b6681610bc3565b50565b6000546001600160a01b031633146106da5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610b54565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6104f48061157383390190565b600060608284031215610c3257600080fd5b50919050565b600060208284031215610c4a57600080fd5b813567ffffffffffffffff811115610c6157600080fd5b610c6d84828501610c20565b949350505050565b634e487b7160e01b600052604160045260246000fd5b60405160a0810167ffffffffffffffff81118282101715610cae57610cae610c75565b60405290565b60405160e0810167ffffffffffffffff81118282101715610cae57610cae610c75565b6040516101c0810167ffffffffffffffff81118282101715610cae57610cae610c75565b60405160c0810167ffffffffffffffff81118282101715610cae57610cae610c75565b604051601f8201601f1916810167ffffffffffffffff81118282101715610d4757610d47610c75565b604052919050565b6001600160a01b0381168114610b6657600080fd5b803561052c81610d4f565b803563ffffffff8116811461052c57600080fd5b60008082840360c0811215610d9757600080fd5b833567ffffffffffffffff811115610dae57600080fd5b610dba86828701610c20565b93505060a0601f1982011215610dcf57600080fd5b50610dd8610c8b565b6020840135610de681610d4f565b81526040840135610df681610d4f565b60208201526060840135610e0981610d4f565b6040820152610e1a60808501610d6f565b6060820152610e2b60a08501610d6f565b6080820152809150509250929050565b60008060408385031215610e4e57600080fd5b823567ffffffffffffffff811115610e6557600080fd5b8301601f81018513610e7657600080fd5b803567ffffffffffffffff811115610e9057610e90610c75565b610ea3601f8201601f1916602001610d1e565b818152866020838501011115610eb857600080fd5b8160208401602083013760006020928201830152969401359450505050565b600060e08284031215610ee957600080fd5b610ef1610cb4565b90508135610efe81610d4f565b81526020820135610f0e81610d4f565b60208201526040820135610f2181610d4f565b60408201526060820135610f3481610d4f565b6060820152610f4560808301610d64565b6080820152610f5660a08301610d6f565b60a0820152610f6760c08301610d6f565b60c082015292915050565b6000806101008385031215610f8657600080fd5b823567ffffffffffffffff811115610f9d57600080fd5b610fa985828601610c20565b925050610fb98460208501610ed7565b90509250929050565b803560ff8116811461052c57600080fd5b6000808284036101e0811215610fe857600080fd5b833567ffffffffffffffff811115610fff57600080fd5b61100b86828701610c20565b9350506101c0601f198201121561102157600080fd5b5061102a610cd7565b61103660208501610d64565b815261104460408501610d64565b602082015261105560608501610d64565b604082015261106660808501610d64565b606082015261107760a08501610d64565b608082015261108860c08501610d64565b60a082015261109960e08501610d64565b60c08201526110ab6101008501610d64565b60e08201526110bd6101208501610d64565b6101008201526110d06101408501610d64565b6101208201526110e36101608501610d64565b6101408201526110f66101808501610fc2565b6101608201526111096101a08501610d6f565b61018082015261111c6101c08501610d6f565b6101a0820152809150509250929050565b60008082840360c081121561114157600080fd5b833567ffffffffffffffff81111561115857600080fd5b61116486828701610c20565b93505060a0601f198201121561117957600080fd5b50611182610c8b565b602084013561119081610d4f565b815260408401356111a081610d4f565b602082015260608401356111b381610d4f565b604082015260808401356111c681610d4f565b606082015260a0939093013560808401525092909150565b60008082840360e08112156111f257600080fd5b833567ffffffffffffffff81111561120957600080fd5b61121586828701610c20565b93505060c0601f198201121561122a57600080fd5b50611233610cfb565b602084013561124181610d4f565b8152604084013561125181610d4f565b6020820152606084013561126481610d4f565b6040820152608084013561127781610d4f565b606082015261128860a08501610d6f565b608082015261129960c08501610d6f565b60a0820152809150509250929050565b6000602082840312156112bb57600080fd5b81356112c681610d4f565b9392505050565b6000808335601e198436030181126112e457600080fd5b83018035915067ffffffffffffffff8211156112ff57600080fd5b60200191503681900382131561131457600080fd5b9250929050565b6000815160005b8181101561133c5760208185018101518683015201611322565b50600093019283525090919050565b6000610c6d61135a838661131b565b8461131b565b6001600160a01b0381511682526001600160a01b0360208201511660208301526001600160a01b0360408201511660408301526001600160a01b0360608201511660608301526001600160a01b03608082015116608083015260a08101516113d060a084018263ffffffff169052565b5060c08101516113e860c084018263ffffffff169052565b505050565b60e0810161065b8284611360565b81516001600160a01b031681526101c08101602083015161142760208401826001600160a01b03169052565b50604083015161144260408401826001600160a01b03169052565b50606083015161145d60608401826001600160a01b03169052565b50608083015161147860808401826001600160a01b03169052565b5060a083015161149360a08401826001600160a01b03169052565b5060c08301516114ae60c08401826001600160a01b03169052565b5060e08301516114c960e08401826001600160a01b03169052565b506101008301516114e66101008401826001600160a01b03169052565b506101208301516115036101208401826001600160a01b03169052565b506101408301516115206101408401826001600160a01b03169052565b5061016083015161153761016084018260ff169052565b5061018083015161155161018084018263ffffffff169052565b506101a083015161156b6101a084018263ffffffff169052565b509291505056fe60806040526040516104f43803806104f4833981016040819052610022916102de565b61002e82826000610035565b5050610401565b61003e83610061565b60008251118061004b5750805b1561005c5761005a83836100a1565b505b505050565b61006a816100cd565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b60606100c683836040518060600160405280602781526020016104cd60279139610180565b9392505050565b6001600160a01b0381163b61013f5760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b6060600080856001600160a01b03168560405161019d91906103b2565b600060405180830381855af49150503d80600081146101d8576040519150601f19603f3d011682016040523d82523d6000602084013e6101dd565b606091505b5090925090506101ef868383876101f9565b9695505050505050565b60608315610268578251600003610261576001600160a01b0385163b6102615760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610136565b5081610272565b610272838361027a565b949350505050565b81511561028a5781518083602001fd5b8060405162461bcd60e51b815260040161013691906103ce565b634e487b7160e01b600052604160045260246000fd5b60005b838110156102d55781810151838201526020016102bd565b50506000910152565b600080604083850312156102f157600080fd5b82516001600160a01b038116811461030857600080fd5b60208401519092506001600160401b0381111561032457600080fd5b8301601f8101851361033557600080fd5b80516001600160401b0381111561034e5761034e6102a4565b604051601f8201601f19908116603f011681016001600160401b038111828210171561037c5761037c6102a4565b60405281815282820160200187101561039457600080fd5b6103a58260208301602086016102ba565b8093505050509250929050565b600082516103c48184602087016102ba565b9190910192915050565b60208152600082518060208401526103ed8160408501602087016102ba565b601f01601f19169190910160400192915050565b60be8061040f6000396000f3fe608060405236601057600e6013565b005b600e5b601f601b6021565b6065565b565b600060607f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5473ffffffffffffffffffffffffffffffffffffffff1690565b905090565b3660008037600080366000845af43d6000803e8080156083573d6000f35b3d6000fdfea2646970667358221220f0e299c966abdb3d24f34350b9a363263e9c84eda8bbb204800c8ad06ead5b7d64736f6c634300081a0033416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220ece09f0720a623f56961b3b9ff176829603b1b2e58313cf5fae0633976c5d75164736f6c634300081a0033
Deployed Bytecode
0x608060405234801561001057600080fd5b506004361061018d5760003560e01c8063731d8c9d116100e3578063a9ae90731161008c578063cd89306211610066578063cd893062146103e8578063ed8bf391146103fb578063f2fde38b1461040e57600080fd5b8063a9ae907314610351578063ad9e9b8514610364578063bf158fd2146103ce57600080fd5b80639536b391116100bd5780639536b3911461031157806395c15cda146103245780639ada9b7b1461033757600080fd5b8063731d8c9d146102d35780638a4adf24146102e65780638da5cb5b1461030057600080fd5b8063342df78c116101455780634c7b9b941161011f5780634c7b9b94146102a557806359ce763a146102b8578063715018a6146102cb57600080fd5b8063342df78c1461025e57806339b70e38146102785780634af63f021461029257600080fd5b806321d2be391161017657806321d2be39146101e6578063236ec797146101f9578063338274381461022457600080fd5b80630470b26f146101925780631dc4dd8c146101d1575b600080fd5b6101a56101a0366004610c38565b610421565b6040805182516001600160a01b0390811682526020938401511692810192909252015b60405180910390f35b6101e46101df366004610d83565b610531565b005b6101e46101f4366004610e3b565b610604565b60015461020c906001600160a01b031681565b6040516001600160a01b0390911681526020016101c8565b600954600a5461023e916001600160a01b03908116911682565b604080516001600160a01b039384168152929091166020830152016101c8565b60055460065461023e916001600160a01b03908116911682565b60035460045461023e916001600160a01b03908116911682565b61020c6102a0366004610e3b565b61063a565b6101e46102b3366004610f72565b610661565b60025461020c906001600160a01b031681565b6101e46106c8565b6101e46102e1366004610f72565b6106dc565b60075460085461023e916001600160a01b03908116911682565b6000546001600160a01b031661020c565b6101a561031f366004610c38565b610743565b6101e4610332366004610fd3565b6108f2565b600b54600c5461023e916001600160a01b03908116911682565b6101e461035f36600461112d565b610957565b61020c610372366004610e3b565b8151602092830120604080516001600160f81b0319818601523060601b6bffffffffffffffffffffffff191660218201526035810193909352605580840192909252805180840390920182526075909201909152805191012090565b600d54600e5461023e916001600160a01b03908116911682565b6101e46103f6366004610e3b565b6109f1565b6101e46104093660046111de565b610a27565b6101e461041c3660046112a9565b610ad4565b604080518082019091526000808252602082015261043d610b69565b600061048a61044c84806112cd565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250505050602085013561063a565b9050600061050a604051806020016104a190610c13565b601f1982820381018352601f9091011660408181526001600160a01b0386166020830152808201526000606082015260800160408051601f19818403018152908290526104f1929160200161134b565b604051602081830303815290604052856040013561063a565b604080518082019091526001600160a01b039384168152921660208301525090505b919050565b610539610b69565b61054282610421565b8051600b80546001600160a01b03199081166001600160a01b0393841617909155602092830151600c8054909216908316908117909155604080516356fa66e360e01b815285518416600482015293850151831660248501528401519091166044830152606083015163ffffffff90811660648401526080840151166084830152906356fa66e39060a4015b600060405180830381600087803b1580156105e857600080fd5b505af11580156105fc573d6000803e3d6000fd5b505050505050565b61060c610b69565b610616828261063a565b600280546001600160a01b0319166001600160a01b03929092169190911790555050565b6000610644610b69565b818351602085016000f59050803b61065b57600080fd5b92915050565b610669610b69565b61067282610421565b8051600980546001600160a01b039283166001600160a01b031991821617909155602090920151600a80549190921692168217905560405163f562d8f560e01b815263f562d8f5906105ce9084906004016113ed565b6106d0610b69565b6106da6000610bc3565b565b6106e4610b69565b6106ed82610421565b8051600580546001600160a01b039283166001600160a01b031991821617909155602090920151600680549190921692168217905560405163f562d8f560e01b815263f562d8f5906105ce9084906004016113ed565b604080518082019091526000808252602082015260006107f861076684806112cd565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250508251602093840120604080516001600160f81b0319818701526bffffffffffffffffffffffff193060601b166021820152898601356035820152605580820193909352815180820390930183526075019052805193019290922092915050565b90506040518060400160405280826001600160a01b031681526020016108e06040518060200161082790610c13565b601f1982820381018352601f9091011660408181526001600160a01b0387166020830152808201526000606082015260800160408051601f1981840301815290829052610877929160200161134b565b60408051601f1981840301815282825280516020918201206001600160f81b0319848301526bffffffffffffffffffffffff193060601b166021850152898301356035850152605580850191909152825180850390910181526075909301909152815191012090565b6001600160a01b031690529392505050565b6108fa610b69565b61090382610421565b8051600380546001600160a01b039283166001600160a01b0319918216179091556020909201516004805491909216921682178155604051635d2bafc360e01b8152635d2bafc3916105ce918591016113fb565b61095f610b69565b61096882610421565b8051600d80546001600160a01b03199081166001600160a01b0393841617909155602092830151600e805490921690831690811790915560408051630647c2ad60e11b8152855184166004820152938501518316602485015284015182166044840152606084015190911660648301526080830151608483015290630c8f855a9060a4016105ce565b6109f9610b69565b610a03828261063a565b600180546001600160a01b0319166001600160a01b03929092169190911790555050565b610a2f610b69565b610a3882610421565b8051600780546001600160a01b03199081166001600160a01b0393841617909155602092830151600880549092169083169081179091556040805163039fe95160e61b815285518416600482015293850151831660248501528401518216604484015260608401519091166064830152608083015163ffffffff908116608484015260a08401511660a48301529063e7fa54409060c4016105ce565b610adc610b69565b6001600160a01b038116610b5d5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f646472657373000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b610b6681610bc3565b50565b6000546001600160a01b031633146106da5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610b54565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6104f48061157383390190565b600060608284031215610c3257600080fd5b50919050565b600060208284031215610c4a57600080fd5b813567ffffffffffffffff811115610c6157600080fd5b610c6d84828501610c20565b949350505050565b634e487b7160e01b600052604160045260246000fd5b60405160a0810167ffffffffffffffff81118282101715610cae57610cae610c75565b60405290565b60405160e0810167ffffffffffffffff81118282101715610cae57610cae610c75565b6040516101c0810167ffffffffffffffff81118282101715610cae57610cae610c75565b60405160c0810167ffffffffffffffff81118282101715610cae57610cae610c75565b604051601f8201601f1916810167ffffffffffffffff81118282101715610d4757610d47610c75565b604052919050565b6001600160a01b0381168114610b6657600080fd5b803561052c81610d4f565b803563ffffffff8116811461052c57600080fd5b60008082840360c0811215610d9757600080fd5b833567ffffffffffffffff811115610dae57600080fd5b610dba86828701610c20565b93505060a0601f1982011215610dcf57600080fd5b50610dd8610c8b565b6020840135610de681610d4f565b81526040840135610df681610d4f565b60208201526060840135610e0981610d4f565b6040820152610e1a60808501610d6f565b6060820152610e2b60a08501610d6f565b6080820152809150509250929050565b60008060408385031215610e4e57600080fd5b823567ffffffffffffffff811115610e6557600080fd5b8301601f81018513610e7657600080fd5b803567ffffffffffffffff811115610e9057610e90610c75565b610ea3601f8201601f1916602001610d1e565b818152866020838501011115610eb857600080fd5b8160208401602083013760006020928201830152969401359450505050565b600060e08284031215610ee957600080fd5b610ef1610cb4565b90508135610efe81610d4f565b81526020820135610f0e81610d4f565b60208201526040820135610f2181610d4f565b60408201526060820135610f3481610d4f565b6060820152610f4560808301610d64565b6080820152610f5660a08301610d6f565b60a0820152610f6760c08301610d6f565b60c082015292915050565b6000806101008385031215610f8657600080fd5b823567ffffffffffffffff811115610f9d57600080fd5b610fa985828601610c20565b925050610fb98460208501610ed7565b90509250929050565b803560ff8116811461052c57600080fd5b6000808284036101e0811215610fe857600080fd5b833567ffffffffffffffff811115610fff57600080fd5b61100b86828701610c20565b9350506101c0601f198201121561102157600080fd5b5061102a610cd7565b61103660208501610d64565b815261104460408501610d64565b602082015261105560608501610d64565b604082015261106660808501610d64565b606082015261107760a08501610d64565b608082015261108860c08501610d64565b60a082015261109960e08501610d64565b60c08201526110ab6101008501610d64565b60e08201526110bd6101208501610d64565b6101008201526110d06101408501610d64565b6101208201526110e36101608501610d64565b6101408201526110f66101808501610fc2565b6101608201526111096101a08501610d6f565b61018082015261111c6101c08501610d6f565b6101a0820152809150509250929050565b60008082840360c081121561114157600080fd5b833567ffffffffffffffff81111561115857600080fd5b61116486828701610c20565b93505060a0601f198201121561117957600080fd5b50611182610c8b565b602084013561119081610d4f565b815260408401356111a081610d4f565b602082015260608401356111b381610d4f565b604082015260808401356111c681610d4f565b606082015260a0939093013560808401525092909150565b60008082840360e08112156111f257600080fd5b833567ffffffffffffffff81111561120957600080fd5b61121586828701610c20565b93505060c0601f198201121561122a57600080fd5b50611233610cfb565b602084013561124181610d4f565b8152604084013561125181610d4f565b6020820152606084013561126481610d4f565b6040820152608084013561127781610d4f565b606082015261128860a08501610d6f565b608082015261129960c08501610d6f565b60a0820152809150509250929050565b6000602082840312156112bb57600080fd5b81356112c681610d4f565b9392505050565b6000808335601e198436030181126112e457600080fd5b83018035915067ffffffffffffffff8211156112ff57600080fd5b60200191503681900382131561131457600080fd5b9250929050565b6000815160005b8181101561133c5760208185018101518683015201611322565b50600093019283525090919050565b6000610c6d61135a838661131b565b8461131b565b6001600160a01b0381511682526001600160a01b0360208201511660208301526001600160a01b0360408201511660408301526001600160a01b0360608201511660608301526001600160a01b03608082015116608083015260a08101516113d060a084018263ffffffff169052565b5060c08101516113e860c084018263ffffffff169052565b505050565b60e0810161065b8284611360565b81516001600160a01b031681526101c08101602083015161142760208401826001600160a01b03169052565b50604083015161144260408401826001600160a01b03169052565b50606083015161145d60608401826001600160a01b03169052565b50608083015161147860808401826001600160a01b03169052565b5060a083015161149360a08401826001600160a01b03169052565b5060c08301516114ae60c08401826001600160a01b03169052565b5060e08301516114c960e08401826001600160a01b03169052565b506101008301516114e66101008401826001600160a01b03169052565b506101208301516115036101208401826001600160a01b03169052565b506101408301516115206101408401826001600160a01b03169052565b5061016083015161153761016084018260ff169052565b5061018083015161155161018084018263ffffffff169052565b506101a083015161156b6101a084018263ffffffff169052565b509291505056fe60806040526040516104f43803806104f4833981016040819052610022916102de565b61002e82826000610035565b5050610401565b61003e83610061565b60008251118061004b5750805b1561005c5761005a83836100a1565b505b505050565b61006a816100cd565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b60606100c683836040518060600160405280602781526020016104cd60279139610180565b9392505050565b6001600160a01b0381163b61013f5760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b6060600080856001600160a01b03168560405161019d91906103b2565b600060405180830381855af49150503d80600081146101d8576040519150601f19603f3d011682016040523d82523d6000602084013e6101dd565b606091505b5090925090506101ef868383876101f9565b9695505050505050565b60608315610268578251600003610261576001600160a01b0385163b6102615760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610136565b5081610272565b610272838361027a565b949350505050565b81511561028a5781518083602001fd5b8060405162461bcd60e51b815260040161013691906103ce565b634e487b7160e01b600052604160045260246000fd5b60005b838110156102d55781810151838201526020016102bd565b50506000910152565b600080604083850312156102f157600080fd5b82516001600160a01b038116811461030857600080fd5b60208401519092506001600160401b0381111561032457600080fd5b8301601f8101851361033557600080fd5b80516001600160401b0381111561034e5761034e6102a4565b604051601f8201601f19908116603f011681016001600160401b038111828210171561037c5761037c6102a4565b60405281815282820160200187101561039457600080fd5b6103a58260208301602086016102ba565b8093505050509250929050565b600082516103c48184602087016102ba565b9190910192915050565b60208152600082518060208401526103ed8160408501602087016102ba565b601f01601f19169190910160400192915050565b60be8061040f6000396000f3fe608060405236601057600e6013565b005b600e5b601f601b6021565b6065565b565b600060607f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5473ffffffffffffffffffffffffffffffffffffffff1690565b905090565b3660008037600080366000845af43d6000803e8080156083573d6000f35b3d6000fdfea2646970667358221220f0e299c966abdb3d24f34350b9a363263e9c84eda8bbb204800c8ad06ead5b7d64736f6c634300081a0033416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220ece09f0720a623f56961b3b9ff176829603b1b2e58313cf5fae0633976c5d75164736f6c634300081a0033
Net Worth in USD
Net Worth in ETH
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.