// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Clones.sol)
pragma solidity ^0.8.20;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*/
library Clones {
/**
* @dev A clone instance deployment failed.
*/
error ERC1167FailedCreateClone();
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create(0, 0x09, 0x37)
}
if (instance == address(0)) {
revert ERC1167FailedCreateClone();
}
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create2(0, 0x09, 0x37, salt)
}
if (instance == address(0)) {
revert ERC1167FailedCreateClone();
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(add(ptr, 0x38), deployer)
mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
mstore(add(ptr, 0x14), implementation)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
mstore(add(ptr, 0x58), salt)
mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
predicted := keccak256(add(ptr, 0x43), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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 (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @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 ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile 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 {MessageHashUtils-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]
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
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, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile 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 {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
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]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
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.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError, bytes32) {
// 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, s);
}
// 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, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @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, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.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 scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its 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 order to
* produce the hash of their typed data 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.
*/
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @custom:storage-location erc7201:openzeppelin.storage.EIP712
struct EIP712Storage {
/// @custom:oz-renamed-from _HASHED_NAME
bytes32 _hashedName;
/// @custom:oz-renamed-from _HASHED_VERSION
bytes32 _hashedVersion;
string _name;
string _version;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;
function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
assembly {
$.slot := EIP712StorageLocation
}
}
/**
* @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 {
EIP712Storage storage $ = _getEIP712Storage();
$._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 MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {IERC-5267}.
*/
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
EIP712Storage storage $ = _getEIP712Storage();
// 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 view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
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 view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
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) {
EIP712Storage storage $ = _getEIP712Storage();
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) {
EIP712Storage storage $ = _getEIP712Storage();
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("");
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.20;
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {EIP712Upgradeable} from "../../../utils/cryptography/EIP712Upgradeable.sol";
import {NoncesUpgradeable} from "../../../utils/NoncesUpgradeable.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation 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.
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20Permit, EIP712Upgradeable, NoncesUpgradeable {
bytes32 private constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Permit deadline has expired.
*/
error ERC2612ExpiredSignature(uint256 deadline);
/**
* @dev Mismatched signature.
*/
error ERC2612InvalidSigner(address signer, address owner);
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {}
/**
* @inheritdoc IERC20Permit
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > deadline) {
revert ERC2612ExpiredSignature(deadline);
}
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
if (signer != owner) {
revert ERC2612InvalidSigner(signer, owner);
}
_approve(owner, spender, value);
}
/**
* @inheritdoc IERC20Permit
*/
function nonces(address owner) public view virtual override(IERC20Permit, NoncesUpgradeable) returns (uint256) {
return super.nonces(owner);
}
/**
* @inheritdoc IERC20Permit
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
return _domainSeparatorV4();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
struct ERC20Storage {
mapping(address account => uint256) _balances;
mapping(address account => mapping(address spender => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
assembly {
$.slot := ERC20StorageLocation
}
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC20Storage storage $ = _getERC20Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
$._totalSupply += value;
} else {
uint256 fromBalance = $._balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
$._balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
$._totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
$._balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
$._allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { INonfungiblePositionManager } from "./external/INonfungiblePositionManager.sol";
import { IWETH } from "./external/IWETH.sol";
import { LaunchpadToken } from "./LaunchpadToken.sol";
import { ReferralHandler } from "./ReferralHandler.sol";
import { ICurve } from "./curves/ICurve.sol";
/**
MMMMMMMMMMMMMMMMMMMMMMMMWX0kol:,... ...,:cox0XWMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMWKkl;.. ..;lxKNMMMMMMMONLYMMMMMMMMM
MMMMCMMMMMMMMMMMMNOo,. .,lkXWMMMMMAPESMMMMMMM
MMMMMMMMMMMMMMNOl' .cONMMMMMMMMMMMMMM
MMMMMMMMMMMMXx;. ,dKWMMMMMMMMMMM
MMMMMMMMMWXd' .oKWMMMMMMMMM
MMMMMMMMNd' .oXMMMMMMMM
MMMMMMWO; ,kWMMMMMM
MMMMMNd. .lXMMMMM
MMMMKc ';cooollc:,. ;KMMMM
MMMK; .ckKNNNXKKKKKKOo, ,0MMM
MMK; .c0NNNNNNXKKKKKKKK0d' ,0MM
MXc .oXNNNNNNNXKKKKKKKKKKk; :KM
Wd. .oXNNNNNNNNXKKKKKKKKKKKk, oN
0, lXNNNNNNNNNXKKKKKKKKKKKKx. .O
o :KNNNNNNNNNNXKKKKKKKKKKKK0l. c
, ;0NNNNNNNNNNNXKKKKKKKKKKKKKk; '
. ,0WNNNNNNNNNNNXKKKKKKKKKKKKKOx, .
,OWWNNNNNNNNNNNXKKKKKKKKKKKKKOOd'
;0WWWNNNNNNNNNNNXKKKKKKKKKKKKK0OOd'
.cKMMMWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOd;
. .lXMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOxc.
. .'ckWMMMMWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxo;. .
: .,cllkWMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxddo:' ,
x. .';clnightMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxdddddc,.. .d
X: ..';:ccmonkexXNNNXXKKKKKKKKKKK000OOOOOOOOOOOkxxxxxdooooolcc:,'.. ;K
MO' ............................................................... .kW
MWx. .oNM
MMNd. lNMM
MMMNd. .oNMMM
MMMMWk' .xNMMMM
MMMMMW0: ;OWMMMMM
MMMMMMMNx' .dXMMMMMMM
MMMMMMMMWKo. .lKWMMMMMMMM
MMMMMMMMMMWKo' .l0WMMMMMMMMMM
MMMMMMMMMMMMWXx;. .,dKWMMMMMMMMMMMM
MMMMMMMMMMMMMMMW0o;. .,oONMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWKxc'. .':d0NMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMWN0xo:,.. ..':lx0NWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMWN0xo:'.. ..';lx0XWMMMMMMMMMMMMMMMMMMMMMMMMMM
*/
/**
* --------------------------------------------------------------------------------
*
* LIVE LIFE ON THE LEFT CURVE
*
* WEBSITE: https://memecoinmonitor.com/
* TWITTER: https://twitter.com/MemecoinMonitor
* TELEGRAM: https://t.me/OnlyApes
*
* --------------------------------------------------------------------------------
*
* @title Gauge
* @notice Trades a token along a bonding curve, with the ability to launch a Uniswap V3 pool
* @dev Intended for minimal proxy cloning
* @author BowTiedPickle
*
* --------------------------------------------------------------------------------
*/
contract Gauge is Initializable {
////////////////////////////////////////////////////////////////////////////////
// CONSTANTS AND IMMUTABLES
////////////////////////////////////////////////////////////////////////////////
/// @dev Minimum token purchase amount
uint256 public constant MIN_BUY = 1e18; // 1 token
/// @dev Fraction denominator
uint256 public constant FRACTION_DENOMINATOR = 1e18;
/// @dev Maximum buy fee (1e18 = 100%)
uint256 public constant MAX_BUY_FEE = 0.05e18; // 5%
/// @dev Maximum sell fee (1e18 = 100%)
uint256 public constant MAX_SELL_FEE = 0.05e18; // 5%
INonfungiblePositionManager public immutable UNISWAP_V3_NFT_MANAGER;
IWETH public immutable weth;
ReferralHandler public immutable referralHandler;
////////////////////////////////////////////////////////////////////////////////
// STATE
////////////////////////////////////////////////////////////////////////////////
LaunchpadToken public token;
ICurve public curve;
address public lpReceiver;
address public pool;
struct CurveParameters {
uint128 yMin;
uint128 yMax;
}
CurveParameters public curveParameters;
struct FeeParameters {
uint128 buyFee;
uint128 sellFee;
}
FeeParameters public feeParameters;
/// @notice Amount of token purchased
uint256 public tokenPurchased;
/// @notice Total ETH paid into the curve
uint256 public ethPaid;
/// @notice Target amount of tokens to purchase during the curve
uint256 public tokenTarget;
/// @notice Total supply of the token
uint256 public totalSupply;
////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTION AND INITIALIZATION
////////////////////////////////////////////////////////////////////////////////
constructor(INonfungiblePositionManager _nftManager, IWETH _weth, ReferralHandler _referralHandler) {
if (address(_nftManager) == address(0) || address(_weth) == address(0) || address(_referralHandler) == address(0))
revert Gauge__ZeroAddress();
UNISWAP_V3_NFT_MANAGER = _nftManager;
weth = _weth;
referralHandler = _referralHandler;
_disableInitializers();
}
function initialize(
LaunchpadToken _token,
ICurve _curve,
address _lpReceiver,
uint256 _amount,
uint256 _tokenTarget,
CurveParameters memory _curveParameters,
FeeParameters memory _feeParameters
) public initializer {
if (address(_token) == address(0) || address(_curve) == address(0) || _lpReceiver == address(0)) {
revert Gauge__ZeroAddress();
}
if (_amount == 0 || _amount < _tokenTarget) revert Gauge__InvalidAmount();
if (_tokenTarget == 0) revert Gauge__InvalidTokenTarget();
uint256 cachedTotalSupply = _token.totalSupply();
if (!_curve.checkCompatability(_curveParameters.yMin, _curveParameters.yMax, _tokenTarget, cachedTotalSupply)) {
revert Gauge__InvalidCurveParameters();
}
if (_feeParameters.buyFee > MAX_BUY_FEE || _feeParameters.sellFee > MAX_SELL_FEE) revert Gauge__ExcessiveFee();
token = _token;
curve = _curve;
lpReceiver = _lpReceiver;
tokenTarget = _tokenTarget;
curveParameters = _curveParameters;
feeParameters = _feeParameters;
totalSupply = cachedTotalSupply;
token.transferFrom(msg.sender, address(this), _amount);
}
////////////////////////////////////////////////////////////////////////////////
// TRADING
////////////////////////////////////////////////////////////////////////////////
/**
* @notice Buy exactly `_amount` of tokens, paying whatever cost is necessary
* @dev If less than `_amount` of tokens remain in the curve, the user will receive the remaining tokens
* @dev Any msg.value in excess of the actual cost will be forwarded to `_recipient`
* @dev Maximum input amount is defined by msg.value
* @param _recipient Address to receive the tokens
* @param _amount Amount of tokens to buy
*/
function buyExactTokens(address _recipient, uint256 _amount) public payable {
if (!gaugeActive()) revert Gauge__GaugeClosed();
uint256 amountToPurchase = _amount > tokenTarget - tokenPurchased ? tokenTarget - tokenPurchased : _amount;
if (amountToPurchase < MIN_BUY) revert Gauge__MinBuy();
(uint256 cost, uint256 fee) = quoteBuyExactTokens(amountToPurchase);
if (msg.value < cost) revert Gauge__InsufficientPayment();
uint256 startingPrice = getCurrentPrice();
tokenPurchased += amountToPurchase;
ethPaid += cost - fee;
token.transfer(_recipient, amountToPurchase);
if (fee > 0) {
referralHandler.handleFees{ value: fee }(_recipient, address(token), cost - fee);
}
if (msg.value > cost) payable(_recipient).transfer(msg.value - cost);
emit Buy(_recipient, amountToPurchase, cost, startingPrice);
}
/**
* @notice Sell exactly `_amountIn` of tokens to ETH
* @param _recipient Address to receive the proceeds
* @param _amountIn Amount of tokens to sell
* @param _minAmountOut Minimum amount of ETH to receive
*/
function sellExactTokens(address _recipient, uint256 _amountIn, uint256 _minAmountOut) public {
if (!gaugeActive()) revert Gauge__GaugeClosed();
if (_amountIn == 0 || _amountIn > tokenPurchased) revert Gauge__InvalidAmount();
(uint256 proceeds, uint256 fee) = quoteSellExactTokens(_amountIn);
if (proceeds < _minAmountOut) revert Gauge__InsufficientOutput();
uint256 startingPrice = getCurrentPrice();
tokenPurchased -= _amountIn;
ethPaid -= proceeds + fee;
token.transferFrom(msg.sender, address(this), _amountIn);
if (fee > 0) {
referralHandler.handleFees{ value: fee }(_recipient, address(token), proceeds + fee);
}
payable(_recipient).transfer(proceeds);
emit Sell(_recipient, _amountIn, proceeds, startingPrice);
}
/**
* @notice Buy tokens with an exact amount of ETH, receiving as many tokens as possible
* @dev If less than `_minAmount` of tokens remain in the curve, the user will receive the remaining tokens
* @param _recipient Address to receive the tokens
* @param _minAmountOut Minimum amount of tokens to receive
*/
function buyExactEth(address _recipient, uint256 _minAmountOut) public payable {
if (!gaugeActive()) revert Gauge__GaugeClosed();
uint256 cost = msg.value;
(uint256 tokensOut, uint256 fee) = quoteBuyExactEth(cost);
if (tokensOut < _minAmountOut) revert Gauge__InsufficientOutput();
// Handle case where less than max is available
if (tokensOut > tokenTarget - tokenPurchased) {
tokensOut = tokenTarget - tokenPurchased;
(cost, fee) = quoteBuyExactTokens(tokensOut);
if (msg.value < cost) revert Gauge__InsufficientPayment();
}
if (tokensOut < MIN_BUY) revert Gauge__MinBuy();
uint256 startingPrice = getCurrentPrice();
tokenPurchased += tokensOut;
ethPaid += cost - fee;
token.transfer(_recipient, tokensOut);
if (fee > 0) {
referralHandler.handleFees{ value: fee }(_recipient, address(token), cost - fee);
}
if (msg.value > cost) payable(_recipient).transfer(msg.value - cost);
emit Buy(_recipient, tokensOut, cost, startingPrice);
}
/**
* @notice Sell tokens for an exact amount of ETH, selling as few tokens as possible
* @param _recipient Address to receive the proceeds
* @param _amountOut Amount of ETH to receive
* @param _maxInput Maximum amount of tokens to sell
*/
function sellExactEth(address _recipient, uint256 _amountOut, uint256 _maxInput) public {
if (!gaugeActive()) revert Gauge__GaugeClosed();
if (_amountOut == 0) revert Gauge__InvalidAmount();
(uint256 tokensIn, uint256 fee) = quoteSellExactEth(_amountOut);
if (tokensIn > _maxInput) revert Gauge__MaxInputExceeded();
uint256 startingPrice = getCurrentPrice();
tokenPurchased -= tokensIn;
ethPaid -= _amountOut + fee;
token.transferFrom(msg.sender, address(this), tokensIn);
if (fee > 0) {
referralHandler.handleFees{ value: fee }(_recipient, address(token), _amountOut + fee);
}
payable(_recipient).transfer(_amountOut);
emit Sell(_recipient, tokensIn, _amountOut, startingPrice);
}
////////////////////////////////////////////////////////////////////////////////
// BONDING CURVE COMPLETION
////////////////////////////////////////////////////////////////////////////////
function launchPool() external returns (address, uint256) {
if (!gaugeActive()) revert Gauge__GaugeClosed();
if (!gaugeClosable()) revert Gauge__BondingCurveNotMature();
// Close the gauge
tokenPurchased = 0;
tokenTarget = 0;
ethPaid = 0;
// Convert native token to WETH
weth.deposit{ value: address(this).balance }();
// Make approvals
token.approve(address(UNISWAP_V3_NFT_MANAGER), type(uint256).max);
weth.approve(address(UNISWAP_V3_NFT_MANAGER), type(uint256).max);
// Sort tokens
address token0;
address token1;
uint256 amount0;
uint256 amount1;
if (address(token) < address(weth)) {
token0 = address(token);
token1 = address(weth);
amount0 = token.balanceOf(address(this));
amount1 = weth.balanceOf(address(this));
} else {
token0 = address(weth);
token1 = address(token);
amount0 = weth.balanceOf(address(this));
amount1 = token.balanceOf(address(this));
}
// Calculate sqrtprice, accounting for rounding in cases where amount1 < amount0
uint256 sqrtPriceX96 = (Math.sqrt((amount1 * 1e18) / amount0) * 2 ** 96) / 1e9;
// Create and initialize a pool on Uniswap V3
address _pool = UNISWAP_V3_NFT_MANAGER.createAndInitializePoolIfNecessary(token0, token1, 10_000, uint160(sqrtPriceX96));
pool = _pool;
// Create the LP
(uint256 tokenId, , , ) = UNISWAP_V3_NFT_MANAGER.mint(
INonfungiblePositionManager.MintParams({
token0: token0,
token1: token1,
fee: 10_000,
tickLower: -887_200,
tickUpper: 887_200,
amount0Desired: amount0,
amount1Desired: amount1,
amount0Min: 1,
amount1Min: 1,
recipient: lpReceiver,
deadline: block.timestamp
})
);
// Sweep any dust to the LP receiver
if (weth.balanceOf(address(this)) > 0) weth.transfer(lpReceiver, weth.balanceOf(address(this)));
if (token.balanceOf(address(this)) > 0) token.transfer(lpReceiver, token.balanceOf(address(this)));
emit PoolLaunched(address(token), _pool, tokenId);
return (_pool, tokenId);
}
////////////////////////////////////////////////////////////////////////////////
// VIEW
////////////////////////////////////////////////////////////////////////////////
/// @notice True if gauge is active
function gaugeActive() public view returns (bool) {
return tokenTarget != 0;
}
function gaugeClosable() public view returns (bool) {
return (tokenTarget - tokenPurchased) < MIN_BUY;
}
/**
* @notice Get the current price of the token
* @return Current price of the token, in wei of ETH per 1e18 wei of token
*/
function getCurrentPrice() public view returns (uint256) {
if (!gaugeActive()) {
return 0;
} else {
return curve.fPrimeX(tokenPurchased, curveParameters.yMin, curveParameters.yMax, tokenTarget, totalSupply);
}
}
/**
* @notice Get the current statistics of the gauge
* @return active True if the gauge is active
* @return closable True if the gauge is closable
* @return tokens Amount of tokens purchased
* @return target Target amount of tokens to purchase
* @return supply Total supply of the token
* @return eth Total ETH paid into the curve
* @return currentPrice Current price of the token, in wei of ETH per 1e18 wei of token
*/
function getGaugeStatistics()
external
view
returns (bool active, bool closable, uint256 tokens, uint256 target, uint256 supply, uint256 eth, uint256 currentPrice)
{
active = gaugeActive();
closable = gaugeClosable();
tokens = tokenPurchased;
target = tokenTarget;
supply = totalSupply;
eth = ethPaid;
currentPrice = getCurrentPrice();
}
/**
* @notice Get the ETH cost of buying `_amount` of tokens, inclusive of any fees
* @param _amount Amount of tokens to buy
* @return total cost: Amount the user pays, in wei of ETH
* @return fee: Fee that was added to the raw cost, in wei of ETH
*/
function quoteBuyExactTokens(uint256 _amount) public view returns (uint256, uint256) {
uint256 rawCost = curve.evaluateDx(
tokenPurchased,
tokenPurchased + _amount,
curveParameters.yMin,
curveParameters.yMax,
tokenTarget,
totalSupply
);
uint256 fee = (rawCost * feeParameters.buyFee) / FRACTION_DENOMINATOR;
return (rawCost + fee, fee);
}
/**
* @notice Get the ETH proceeds of selling `_amount` of tokens, inclusive of any fees
* @param _amount Amount of tokens to sell
* @return total proceeds: Amount the user receives, in wei of ETH
* @return fee: Fee that was subtracted from the raw proceeds, in wei of ETH
*/
function quoteSellExactTokens(uint256 _amount) public view returns (uint256, uint256) {
if (_amount > tokenPurchased) revert Gauge__DesiredExceedsAvailable();
uint256 rawProceeds = curve.evaluateDx(
tokenPurchased - _amount,
tokenPurchased,
curveParameters.yMin,
curveParameters.yMax,
tokenTarget,
totalSupply
);
uint256 fee = (rawProceeds * feeParameters.sellFee) / FRACTION_DENOMINATOR;
return (rawProceeds - fee, fee);
}
/**
* @notice Get the number of tokens which will cost `_amount` of ETH, inclusive of any fees
* @param _amount Amount of ETH to spend
* @return tokensOut: Amount of tokens the user will receive
* @return fee: Fee that was subtracted from the user's purchasing power, in wei of ETH
*/
function quoteBuyExactEth(uint256 _amount) public view returns (uint256, uint256) {
uint256 fee = (_amount * feeParameters.buyFee) / FRACTION_DENOMINATOR;
uint256 tokensOut = curve.evaluateDy(
ethPaid,
(ethPaid + _amount - fee),
curveParameters.yMin,
curveParameters.yMax,
tokenTarget,
totalSupply
);
return (tokensOut, fee);
}
/**
* @notice Get the number of tokens which must be sold to receive `_amount` of ETH, inclusive of any fees
* @param _amount Amount of ETH to receive
* @return tokensIn: Amount of tokens the user will pay
* @return fee: Fee that was added to the raw desired amount, in wei of ETH
*/
function quoteSellExactEth(uint256 _amount) public view returns (uint256, uint256) {
uint256 fee = (_amount * feeParameters.sellFee) / FRACTION_DENOMINATOR;
if (_amount + fee > ethPaid) revert Gauge__DesiredExceedsAvailable();
uint256 tokensIn = curve.evaluateDy(
(ethPaid - _amount - fee),
ethPaid,
curveParameters.yMin,
curveParameters.yMax,
tokenTarget,
totalSupply
);
return (tokensIn, fee);
}
////////////////////////////////////////////////////////////////////////////////
// ERRORS
////////////////////////////////////////////////////////////////////////////////
error Gauge__ZeroAddress();
error Gauge__InvalidAmount();
error Gauge__InvalidTokenTarget();
error Gauge__InvalidCurveParameters();
error Gauge__InsufficientPayment();
error Gauge__MinBuy();
error Gauge__BondingCurveNotMature();
error Gauge__GaugeClosed();
error Gauge__ExcessiveFee();
error Gauge__InsufficientOutput();
error Gauge__MaxInputExceeded();
error Gauge__DesiredExceedsAvailable();
error Gauge__TransferFailure();
////////////////////////////////////////////////////////////////////////////////
// EVENTS
////////////////////////////////////////////////////////////////////////////////
event Buy(address indexed recipient, uint256 amount, uint256 cost, uint256 startingPrice);
event Sell(address indexed recipient, uint256 amount, uint256 proceeds, uint256 startingPrice);
event PoolLaunched(address indexed token, address indexed pool, uint256 tokenId);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface ICurve {
function checkCompatability(uint256 yMin, uint256 yMax, uint256 xMax, uint256 xTotal) external pure returns (bool);
function fPrimeX(uint256 x, uint256 yMin, uint256 yMax, uint256 xMax, uint256 xTotal) external pure returns (uint256);
function fX(uint256 x, uint256 yMin, uint256 yMax, uint256 xMax, uint256 xTotal) external pure returns (uint256);
function fY(uint256 y, uint256 yMin, uint256 yMax, uint256 xMax, uint256 xTotal) external pure returns (uint256);
function evaluateDx(uint256 x1, uint256 x2, uint256 yMin, uint256 yMax, uint256 xMax, uint256 xTotal) external pure returns (uint256);
function evaluateDy(uint256 y1, uint256 y2, uint256 yMin, uint256 yMax, uint256 xMax, uint256 xTotal) external pure returns (uint256);
error ICurve__InvalidInput();
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @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 v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.20;
interface IERC5267 {
/**
* @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 (last updated v5.0.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../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 address zero.
*
* 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 v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../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 (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.20;
import { IERC721 } from "../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: 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.8.20;
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-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: MIT
pragma solidity ^0.8.20;
interface IWETH {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
function balanceOf(address account) external view returns (uint256);
function allowance(address src, address guy) external view returns (uint);
function deposit() external payable;
function withdraw(uint wad) external;
function totalSupply() external view returns (uint);
function approve(address guy, uint wad) external returns (bool);
function transfer(address dst, uint wad) external returns (bool);
function transferFrom(address src, address dst, uint wad) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { Gauge } from "./Gauge.sol";
import { LaunchpadToken } from "./LaunchpadToken.sol";
import { ICurve } from "./curves/ICurve.sol";
/**
MMMMMMMMMMMMMMMMMMMMMMMMWX0kol:,... ...,:cox0XWMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMWKkl;.. ..;lxKNMMMMMMMONLYMMMMMMMMM
MMMMCMMMMMMMMMMMMNOo,. .,lkXWMMMMMAPESMMMMMMM
MMMMMMMMMMMMMMNOl' .cONMMMMMMMMMMMMMM
MMMMMMMMMMMMXx;. ,dKWMMMMMMMMMMM
MMMMMMMMMWXd' .oKWMMMMMMMMM
MMMMMMMMNd' .oXMMMMMMMM
MMMMMMWO; ,kWMMMMMM
MMMMMNd. .lXMMMMM
MMMMKc ';cooollc:,. ;KMMMM
MMMK; .ckKNNNXKKKKKKOo, ,0MMM
MMK; .c0NNNNNNXKKKKKKKK0d' ,0MM
MXc .oXNNNNNNNXKKKKKKKKKKk; :KM
Wd. .oXNNNNNNNNXKKKKKKKKKKKk, oN
0, lXNNNNNNNNNXKKKKKKKKKKKKx. .O
o :KNNNNNNNNNNXKKKKKKKKKKKK0l. c
, ;0NNNNNNNNNNNXKKKKKKKKKKKKKk; '
. ,0WNNNNNNNNNNNXKKKKKKKKKKKKKOx, .
,OWWNNNNNNNNNNNXKKKKKKKKKKKKKOOd'
;0WWWNNNNNNNNNNNXKKKKKKKKKKKKK0OOd'
.cKMMMWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOd;
. .lXMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOxc.
. .'ckWMMMMWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxo;. .
: .,cllkWMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxddo:' ,
x. .';clnightMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxdddddc,.. .d
X: ..';:ccmonkexXNNNXXKKKKKKKKKKK000OOOOOOOOOOOkxxxxxdooooolcc:,'.. ;K
MO' ............................................................... .kW
MWx. .oNM
MMNd. lNMM
MMMNd. .oNMMM
MMMMWk' .xNMMMM
MMMMMW0: ;OWMMMMM
MMMMMMMNx' .dXMMMMMMM
MMMMMMMMWKo. .lKWMMMMMMMM
MMMMMMMMMMWKo' .l0WMMMMMMMMMM
MMMMMMMMMMMMWXx;. .,dKWMMMMMMMMMMMM
MMMMMMMMMMMMMMMW0o;. .,oONMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWKxc'. .':d0NMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMWN0xo:,.. ..':lx0NWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMWN0xo:'.. ..';lx0XWMMMMMMMMMMMMMMMMMMMMMMMMMM
*/
/**
* --------------------------------------------------------------------------------
*
* LIVE LIFE ON THE LEFT CURVE
*
* WEBSITE: https://memecoinmonitor.com/
* TWITTER: https://twitter.com/MemecoinMonitor
* TELEGRAM: https://t.me/OnlyApes
*
* --------------------------------------------------------------------------------
*
* @title Launchpad
* @notice Platform entry point for creating and trading tokens
* @author BowTiedPickle
*
* --------------------------------------------------------------------------------
*/
contract Launchpad is Ownable {
////////////////////////////////////////////////////////////////////////////////
// LIBRARIES
////////////////////////////////////////////////////////////////////////////////
using EnumerableSet for EnumerableSet.AddressSet;
////////////////////////////////////////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////////////////////////////////////////
/// @notice Maximum fraction of supply of a new token which can be reserved for booster program (1e18 = 100%)
uint256 public constant MAX_BOOSTER_FRACTION = 0.02e18; // 2%
/// @notice Maximum fraction of supply of a new token which can be used in the bonding curve (1e18 = 100%)
uint256 public constant MAX_BONDING_FRACTION = 0.98e18; // 98%
uint256 public constant FRACTION_DENOMINATOR = 1e18;
/// @notice Maximum creation cost which can be charged (wei of ETH)
uint256 public constant MAX_CREATION_COST = 0.1 ether;
/// @notice Maximum buy/sell fee which is allowed in a gauge
uint256 public constant MAX_GAUGE_FEE = 2.5e16; // 2.5%
/// @notice Minimum initial supply allowed for a token
uint256 public constant MIN_INITIAL_SUPPLY = 100 ether;
////////////////////////////////////////////////////////////////////////////////
// CONFIGURATION
////////////////////////////////////////////////////////////////////////////////
/// @notice Address of the token implementation
address public tokenImplementation;
/// @notice Fraction of the initial token supply reserved for booster program
uint64 public boosterFraction;
/// @notice Address of the gauge implementation
address public gaugeImplementation;
/// @notice Fraction of the initial token supply used in the bonding curve
uint64 public bondingCurveFraction = 0.8e18; // 80%
/// @notice Address of the bonding curve math implementation
address public curve;
/// @notice ETH-denominated cost to create a new token
uint64 public creationCost;
/// @notice Protocol treasury address
address public treasury;
/// @notice Address which will receive LP tokens when pools are created from a gauge
address public lpReceiver;
/// @notice Fee parameters applied to new gauges
Gauge.FeeParameters public gaugeFees;
////////////////////////////////////////////////////////////////////////////////
// TRACKING
////////////////////////////////////////////////////////////////////////////////
/// @notice Mapping of token address to gauge address
mapping(address token => address gauge) public tokenToGauge;
/// @notice Mapping of token address to creator address
mapping(address token => address creator) public tokenToCreator;
/// @dev Set of all created tokens
EnumerableSet.AddressSet internal tokens;
/// @dev Mapping of creator address to created tokens
mapping(address creator => EnumerableSet.AddressSet tokens) internal creatorToTokens;
////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
////////////////////////////////////////////////////////////////////////////////
constructor(
address _tokenImplementation,
address _gaugeImplementation,
address _curve,
address _treasury,
address _lpReceiver,
uint64 _creationCost,
uint64 _boosterFraction
) Ownable(msg.sender) {
if (
_tokenImplementation == address(0) ||
_gaugeImplementation == address(0) ||
_curve == address(0) ||
_treasury == address(0) ||
_lpReceiver == address(0)
) revert Launchpad__ZeroAddress();
if (_creationCost > MAX_CREATION_COST) revert Launchpad__ExcessiveCreationCost();
if (_boosterFraction > MAX_BOOSTER_FRACTION) revert Launchpad__ExcessiveBoosterFraction();
tokenImplementation = _tokenImplementation;
gaugeImplementation = _gaugeImplementation;
curve = _curve;
treasury = _treasury;
lpReceiver = _lpReceiver;
creationCost = _creationCost;
boosterFraction = _boosterFraction;
}
////////////////////////////////////////////////////////////////////////////////
// CREATE TOKENS
////////////////////////////////////////////////////////////////////////////////
struct AutoSnipeConfig {
uint256 minAmountOut;
}
/**
* @notice Create a new token and gauge
* @param tokenConfig Token configuration
* @param metadataConfig Token metadata configuration
* @param snipeConfig Autosnipe configuration
* @param curveParameters Bonding curve price parameters
* @dev Send more ETH than the creation cost to trigger an autosnipe with the excess
* @return token Token address
* @return gauge Gauge address
*/
function createLaunchpadToken(
LaunchpadToken.TokenConfig memory tokenConfig,
LaunchpadToken.TokenMetadataConfig memory metadataConfig,
AutoSnipeConfig memory snipeConfig,
Gauge.CurveParameters memory curveParameters
) external payable returns (LaunchpadToken, Gauge) {
if (msg.value < creationCost) revert Launchpad__InsufficientValue();
// Create token and gauge
(LaunchpadToken token, Gauge gauge) = _createTokenAndGauge(tokenConfig, metadataConfig);
gauge.initialize(
token,
ICurve(curve),
lpReceiver,
tokenConfig.initialSupply - (tokenConfig.initialSupply * boosterFraction) / FRACTION_DENOMINATOR,
(tokenConfig.initialSupply * bondingCurveFraction) / FRACTION_DENOMINATOR,
curveParameters,
gaugeFees
);
// Take creation cost - call used due to multisig recipient
(bool success, ) = payable(treasury).call{ value: creationCost }("");
if (!success) revert Launchpad__TransferFailure();
// Autosnipe
if (msg.value > creationCost) {
gauge.buyExactEth{ value: msg.value - creationCost }(msg.sender, snipeConfig.minAmountOut);
}
emit NewToken(msg.sender, address(token), address(gauge), curve);
return (token, gauge);
}
/**
* @dev Internal function to create a token and gauge, and initialize the token.
* @dev Avoids stack too deep
*/
function _createTokenAndGauge(
LaunchpadToken.TokenConfig memory tokenConfig,
LaunchpadToken.TokenMetadataConfig memory metadataConfig
) internal returns (LaunchpadToken, Gauge) {
if (tokenConfig.initialSupply < MIN_INITIAL_SUPPLY) revert Launchpad__InvalidTotalSupply();
LaunchpadToken token = LaunchpadToken(Clones.clone(tokenImplementation));
Gauge gauge = Gauge(Clones.clone(gaugeImplementation));
tokenToGauge[address(token)] = address(gauge);
tokens.add(address(token));
creatorToTokens[msg.sender].add(address(token));
tokenToCreator[address(token)] = msg.sender;
token.initialize(tokenConfig, metadataConfig, address(gauge));
uint256 boosterFractionAmount = (tokenConfig.initialSupply * boosterFraction) / FRACTION_DENOMINATOR;
token.transfer(treasury, boosterFractionAmount);
// Max approval to enable router functions later
token.approve(address(gauge), type(uint256).max);
return (token, gauge);
}
////////////////////////////////////////////////////////////////////////////////
// TRADE TOKENS
////////////////////////////////////////////////////////////////////////////////
/**
* @notice Buy an exact amount of tokens
* @dev Allowable slippage is defined by msg.value
* @param token Token address
* @param amountOut Amount of tokens to buy
*/
function buyExactTokens(address token, uint256 amountOut) external payable {
Gauge gauge = Gauge(tokenToGauge[token]);
if (address(gauge) == address(0)) revert Launchpad__InvalidToken();
gauge.buyExactTokens{ value: msg.value }(msg.sender, amountOut);
}
/**
* @notice Sell an exact amount of tokens
* @param token Token address
* @param amountIn Amount of tokens to sell
* @param minAmountOut Minimum amount of ETH to receive
*/
function sellExactTokens(address token, uint256 amountIn, uint256 minAmountOut) external {
Gauge gauge = Gauge(tokenToGauge[token]);
if (address(gauge) == address(0)) revert Launchpad__InvalidToken();
LaunchpadToken(token).transferFrom(msg.sender, address(this), amountIn);
gauge.sellExactTokens(msg.sender, amountIn, minAmountOut);
}
/**
* @notice Buy the maximum amount of tokens for an exact ETH input
* @param token Token address
* @param minAmountOut Minimum amount of tokens to receive
*/
function buyExactEth(address token, uint256 minAmountOut) external payable {
Gauge gauge = Gauge(tokenToGauge[token]);
if (address(gauge) == address(0)) revert Launchpad__InvalidToken();
gauge.buyExactEth{ value: msg.value }(msg.sender, minAmountOut);
}
/**
* @notice Sell the minimum amount of tokens for an exact ETH output
* @param token Token address
* @param amountOut Amount of ETH to receive
* @param maxInput Maximum amount of tokens to sell
*/
function sellExactEth(address token, uint256 amountOut, uint256 maxInput) external {
Gauge gauge = Gauge(tokenToGauge[token]);
if (address(gauge) == address(0)) revert Launchpad__InvalidToken();
(uint256 amountIn, ) = gauge.quoteSellExactEth(amountOut);
LaunchpadToken(token).transferFrom(msg.sender, address(this), amountIn);
gauge.sellExactEth(msg.sender, amountOut, maxInput);
}
////////////////////////////////////////////////////////////////////////////////
// VIEWS
////////////////////////////////////////////////////////////////////////////////
// ---------- Quotes ----------
enum QuoteType {
BUY_EXACT_TOKENS,
SELL_EXACT_TOKENS,
BUY_EXACT_ETH,
SELL_EXACT_ETH
}
struct Quote {
// Wei of ETH the user will pay for the action
uint256 amountInEth;
// Wei of tokens the user will pay for the action
uint256 amountInToken;
// Wei of ETH the user will receive
uint256 amountOutEth;
// Wei of tokens the user will receive
uint256 amountOutToken;
}
/**
* @notice Get a quote for a trade at the prevailing conditions
* @dev The price may change from this value, set slippage accordingly
* @param token Token address
* @param amount Amount of tokens to buy/sell
* @param quoteType Type of trade to quote
* @return quote Quote struct
*/
function quote(address token, uint256 amount, QuoteType quoteType) external view returns (Quote memory) {
Quote memory result = Quote(0, 0, 0, 0);
uint256 value;
if (quoteType == QuoteType.BUY_EXACT_TOKENS) {
(amount, value) = quoteBuyExactTokens(token, amount);
result.amountInEth = value;
result.amountOutToken = amount;
} else if (quoteType == QuoteType.SELL_EXACT_TOKENS) {
(amount, value) = quoteSellExactTokens(token, amount);
result.amountInToken = amount;
result.amountOutEth = value;
} else if (quoteType == QuoteType.BUY_EXACT_ETH) {
(amount, value) = quoteBuyExactEth(token, amount);
result.amountInEth = amount;
result.amountOutToken = value;
} else if (quoteType == QuoteType.SELL_EXACT_ETH) {
(amount, value) = quoteSellExactEth(token, amount);
result.amountInToken = value;
result.amountOutEth = amount;
}
return result;
}
/**
* @notice Get the ETH cost of buying `amount` of tokens, inclusive of any fees
* @dev If `amount` exceeds the amount available to purchase, it will be clamped to the available amount
* @param token Token address
* @param amount Amount of tokens to buy
* @return amount: Amount of tokens being purchased
* @return total cost: Amount the user pays, in wei of ETH
*/
function quoteBuyExactTokens(address token, uint256 amount) public view returns (uint256, uint256) {
Gauge gauge = Gauge(tokenToGauge[token]);
if (address(gauge) == address(0)) revert Launchpad__InvalidToken();
uint256 remaining = gauge.tokenTarget() - gauge.tokenPurchased();
amount = amount > remaining ? remaining : amount;
(uint256 result, ) = gauge.quoteBuyExactTokens(amount);
return (amount, result);
}
/**
* @notice Get the ETH proceeds of selling `amount` of tokens, inclusive of any fees
* @dev If `amount` exceeds the amount of tokens purchased, it will be clamped to the available amount
* @param token Token address
* @param amount Amount of tokens to sell
* @return total proceeds: Amount the user receives, in wei of ETH
*/
function quoteSellExactTokens(address token, uint256 amount) public view returns (uint256, uint256) {
Gauge gauge = Gauge(tokenToGauge[token]);
if (address(gauge) == address(0)) revert Launchpad__InvalidToken();
uint256 available = gauge.tokenPurchased();
amount = amount > available ? available : amount;
(uint256 result, ) = gauge.quoteSellExactTokens(amount);
return (amount, result);
}
/**
* @notice Get the number of tokens which will cost `amount` of ETH, inclusive of any fees
* @param token Token address
* @param amount Amount of ETH to spend
* @return tokensOut: Amount of tokens the user will receive
*/
function quoteBuyExactEth(address token, uint256 amount) public view returns (uint256, uint256) {
Gauge gauge = Gauge(tokenToGauge[token]);
if (address(gauge) == address(0)) revert Launchpad__InvalidToken();
(uint256 result, ) = gauge.quoteBuyExactEth(amount);
uint256 remaining = gauge.tokenTarget() - gauge.tokenPurchased();
if (result > remaining) {
result = remaining;
(amount, ) = gauge.quoteBuyExactTokens(remaining);
}
return (amount, result);
}
/**
* @notice Get the number of tokens which must be sold to receive `amount` of ETH, inclusive of any fees
* @param token Token address
* @param amount Amount of ETH to receive
* @return tokensIn: Amount of tokens the user will pay
*/
function quoteSellExactEth(address token, uint256 amount) public view returns (uint256, uint256) {
Gauge gauge = Gauge(tokenToGauge[token]);
if (address(gauge) == address(0)) revert Launchpad__InvalidToken();
(, uint256 sellFee) = gauge.feeParameters();
uint256 available = (gauge.ethPaid() * (FRACTION_DENOMINATOR - sellFee)) / FRACTION_DENOMINATOR;
amount = amount > available ? available : amount;
(uint256 result, ) = gauge.quoteSellExactEth(amount);
return (amount, result);
}
// ---------- Tokens and Token Info ----------
struct TokenInfo {
// Token address
address token;
// Gauge address
address gauge;
// Token name
string name;
// Token symbol
string symbol;
// True if gauge is active
bool gaugeActive;
// True if gauge is closable
bool gaugeClosable;
// Number of tokens purchased in the gauge
uint256 tokenPurchased;
// Target number of tokens in the gauge
uint256 tokenTarget;
// Total supply of the token
uint256 totalSupply;
// Current price in wei of ETH per 1e18 wei of token
uint256 currentPrice;
// ETH paid into the gauge
uint256 ethPaid;
// Fractional fee charged on buy (1e18 = 100%)
uint128 buyFee;
// Fractional fee charged on sell (1e18 = 100%)
uint128 sellFee;
// Metadata
LaunchpadToken.TokenMetadataConfig metadata;
// Token creator address
address creator;
// Pool address
address pool;
}
/**
* @notice Get the current information of a given token and its gauge
* @param token Token address
* @return tokenInfo TokenInfo struct
*/
function getTokenInfo(address token) public view returns (TokenInfo memory) {
Gauge gauge = Gauge(tokenToGauge[token]);
if (address(gauge) == address(0)) revert Launchpad__InvalidToken();
(
bool active,
bool closable,
uint256 tokenPurchased,
uint256 tokenTarget,
uint256 totalSupply,
uint256 ethPaid,
uint256 currentPrice
) = gauge.getGaugeStatistics();
(uint128 buyFee, uint128 sellFee) = gauge.feeParameters();
return
TokenInfo({
token: token,
gauge: address(gauge),
name: LaunchpadToken(token).name(),
symbol: LaunchpadToken(token).symbol(),
gaugeActive: active,
gaugeClosable: closable,
tokenPurchased: tokenPurchased,
tokenTarget: tokenTarget,
totalSupply: totalSupply,
ethPaid: ethPaid,
currentPrice: currentPrice,
buyFee: buyFee,
sellFee: sellFee,
metadata: LaunchpadToken(token).getAllMetadata(),
creator: tokenToCreator[token],
pool: gauge.pool()
});
}
/**
* @notice Get current number of tokens deployed from this launchpad
* @return Number of tokens
*/
function getTokensCount() external view returns (uint256) {
return tokens.length();
}
/**
* @notice Get all tokens deployed from this launchpad
* @return Array of token addresses
*/
function getAllTokens() external view returns (address[] memory) {
return tokens.values();
}
/**
* @notice Get all tokens deployed from this launchpad and their corresponding gauges
* @return Array of token addresses
* @return Array of gauge addresses
*/
function getAllTokensAndGauges() external view returns (address[] memory, address[] memory) {
address[] memory _tokens = new address[](tokens.length());
address[] memory _gauges = new address[](tokens.length());
for (uint256 i; i < tokens.length(); ) {
address token = tokens.at(i);
_tokens[i] = token;
_gauges[i] = tokenToGauge[token];
unchecked {
++i;
}
}
return (_tokens, _gauges);
}
/**
* @notice Get all tokens deployed from this launchpad and their corresponding information
* @return Array of TokenInfo structs
*/
function getAllTokensInfo() external view returns (TokenInfo[] memory) {
TokenInfo[] memory data = new TokenInfo[](tokens.length());
for (uint256 i; i < tokens.length(); ) {
address token = tokens.at(i);
data[i] = getTokenInfo(token);
unchecked {
++i;
}
}
return data;
}
/**
* @notice Get a range of tokens deployed from this launchpad
* @param start Start index
* @param end End index (inclusive)
* @return Array of token addresses
*/
function getTokens(uint256 start, uint256 end) public view returns (address[] memory) {
if (start > end || end > tokens.length() - 1) revert Launchpad__InvalidIndex();
address[] memory _tokens = new address[](end - start + 1);
for (uint256 i = start; i <= end; ) {
_tokens[i - start] = tokens.at(i);
unchecked {
++i;
}
}
return _tokens;
}
/**
* @notice Get a range of tokens deployed from this launchpad and their corresponding gauges
* @param start Start index
* @param end End index
* @return Array of token addresses
* @return Array of gauge addresses
*/
function getTokensAndGauges(uint256 start, uint256 end) external view returns (address[] memory, address[] memory) {
address[] memory _tokens = getTokens(start, end);
address[] memory _gauges = new address[](_tokens.length);
for (uint256 i; i < _tokens.length; ) {
_gauges[i] = tokenToGauge[_tokens[i]];
unchecked {
++i;
}
}
return (_tokens, _gauges);
}
/**
* @notice Get a range of tokens deployed from this launchpad and their corresponding information
* @param start Start index
* @param end End index
* @return Array of TokenInfo structs
*/
function getTokensInfo(uint256 start, uint256 end) external view returns (TokenInfo[] memory) {
address[] memory _tokens = getTokens(start, end);
TokenInfo[] memory data = new TokenInfo[](_tokens.length);
for (uint256 i; i < _tokens.length; ) {
data[i] = getTokenInfo(_tokens[i]);
unchecked {
++i;
}
}
return data;
}
/**
* @notice Get `num` most recent tokens deployed from this launchpad
* @param num Number of tokens to return
* @return Array of token addresses
*/
function getMostRecentTokens(uint256 num) public view returns (address[] memory) {
if (num > tokens.length()) {
num = tokens.length();
}
address[] memory _tokens = new address[](num);
for (uint256 i; i < num; ) {
_tokens[i] = tokens.at(tokens.length() - 1 - i);
unchecked {
++i;
}
}
return _tokens;
}
/**
* @notice Get `num` most recent tokens deployed from this launchpad and their corresponding gauges
* @param num Number of tokens to return
* @return Array of token addresses
* @return Array of gauge addresses
*/
function getMostRecentTokensAndGauges(uint256 num) external view returns (address[] memory, address[] memory) {
if (num > tokens.length()) {
num = tokens.length();
}
address[] memory _tokens = getMostRecentTokens(num);
address[] memory _gauges = new address[](num);
for (uint256 i; i < num; ) {
_gauges[i] = tokenToGauge[_tokens[i]];
unchecked {
++i;
}
}
return (_tokens, _gauges);
}
/**
* @notice Get `num` most recent tokens deployed from this launchpad and their corresponding information
* @param num Number of tokens to return
* @return Array of TokenInfo structs
*/
function getMostRecentTokensInfo(uint256 num) external view returns (TokenInfo[] memory) {
if (num > tokens.length()) {
num = tokens.length();
}
address[] memory _tokens = getMostRecentTokens(num);
TokenInfo[] memory data = new TokenInfo[](num);
for (uint256 i; i < num; ) {
data[i] = getTokenInfo(_tokens[i]);
unchecked {
++i;
}
}
return data;
}
/**
* @notice Get the number of tokens deployed by a creator
* @param creator Creator address
* @return Number of tokens
*/
function getTokensCountByCreator(address creator) external view returns (uint256) {
return creatorToTokens[creator].length();
}
/**
* @notice Get all tokens deployed by a creator
* @param creator Creator address
* @return Array of token addresses
*/
function getTokensByCreator(address creator) public view returns (address[] memory) {
return creatorToTokens[creator].values();
}
/**
* @notice Get all tokens deployed by a creator and their corresponding gauges
* @param creator Creator address
* @return Array of token addresses
* @return Array of gauge addresses
*/
function getTokensAndGaugesByCreator(address creator) external view returns (address[] memory, address[] memory) {
address[] memory _tokens = getTokensByCreator(creator);
address[] memory _gauges = new address[](_tokens.length);
for (uint256 i; i < _tokens.length; ) {
_gauges[i] = tokenToGauge[_tokens[i]];
unchecked {
++i;
}
}
return (_tokens, _gauges);
}
/**
* @notice Get all tokens deployed by a creator and their corresponding information
* @param creator Creator address
* @return Array of TokenInfo structs
*/
function getTokensInfoByCreator(address creator) external view returns (TokenInfo[] memory) {
address[] memory _tokens = getTokensByCreator(creator);
TokenInfo[] memory data = new TokenInfo[](_tokens.length);
for (uint256 i; i < _tokens.length; ) {
data[i] = getTokenInfo(_tokens[i]);
unchecked {
++i;
}
}
return data;
}
////////////////////////////////////////////////////////////////////////////////
// ADMINISTRATION
////////////////////////////////////////////////////////////////////////////////
/**
* @notice Set the token implementation
* @param _tokenImplementation New token implementation address
*/
function setTokenImplementation(address _tokenImplementation) external onlyOwner {
if (_tokenImplementation == address(0)) revert Launchpad__ZeroAddress();
emit TokenImplementationSet(_tokenImplementation, tokenImplementation);
tokenImplementation = _tokenImplementation;
}
/**
* @notice Set the gauge implementation
* @param _gaugeImplementation New gauge implementation address
*/
function setGaugeImplementation(address _gaugeImplementation) external onlyOwner {
if (_gaugeImplementation == address(0)) revert Launchpad__ZeroAddress();
emit GaugeImplementationSet(_gaugeImplementation, gaugeImplementation);
gaugeImplementation = _gaugeImplementation;
}
/**
* @notice Set the bonding curve math implementation
* @param _curve New curve implementation address
*/
function setCurve(address _curve) external onlyOwner {
if (_curve == address(0)) revert Launchpad__ZeroAddress();
emit CurveSet(_curve, curve);
curve = _curve;
}
/**
* @notice Set the treasury address
* @param _treasury The new treasury address
*/
function setTreasury(address _treasury) external onlyOwner {
if (_treasury == address(0)) revert Launchpad__ZeroAddress();
emit TreasurySet(_treasury, treasury);
treasury = _treasury;
}
/**
* @notice Set the LP receiver address
* @param _lpReceiver The new LP receiver address
*/
function setLpReceiver(address _lpReceiver) external onlyOwner {
if (_lpReceiver == address(0)) revert Launchpad__ZeroAddress();
emit LpReceiverSet(_lpReceiver, lpReceiver);
lpReceiver = _lpReceiver;
}
/**
* @notice Set the creation cost
* @param _creationCost The new creation cost
*/
function setCreationCost(uint64 _creationCost) external onlyOwner {
if (_creationCost > MAX_CREATION_COST) revert Launchpad__ExcessiveCreationCost();
emit CreationCostSet(_creationCost, creationCost);
creationCost = _creationCost;
}
/**
* @notice Set the booster fraction
* @param _boosterFraction The new booster fraction
*/
function setBoosterFraction(uint64 _boosterFraction) external onlyOwner {
if (_boosterFraction > MAX_BOOSTER_FRACTION) revert Launchpad__ExcessiveBoosterFraction();
emit BoosterFractionSet(_boosterFraction, boosterFraction);
boosterFraction = _boosterFraction;
}
/**
* @notice Set the gauge fees
* @param _gaugeFees The new gauge fees
*/
function setGaugeFees(Gauge.FeeParameters calldata _gaugeFees) external onlyOwner {
if (_gaugeFees.buyFee > MAX_GAUGE_FEE || _gaugeFees.sellFee > MAX_GAUGE_FEE) {
revert Launchpad__ExcessiveGaugeFee();
}
emit GaugeFeesSet(_gaugeFees.buyFee, gaugeFees.buyFee, _gaugeFees.sellFee, gaugeFees.sellFee);
gaugeFees = _gaugeFees;
}
/**
* @notice Set the bonding curve fraction
* @param _bondingCurveFraction The new bonding curve fraction
*/
function setBondingCurveFraction(uint64 _bondingCurveFraction) external onlyOwner {
if (_bondingCurveFraction > MAX_BONDING_FRACTION) revert Launchpad__ExcessiveBondingFraction();
emit BondingCurveFractionSet(_bondingCurveFraction, bondingCurveFraction);
bondingCurveFraction = _bondingCurveFraction;
}
////////////////////////////////////////////////////////////////////////////////
// ERRORS
////////////////////////////////////////////////////////////////////////////////
error Launchpad__ZeroAddress();
error Launchpad__InvalidTotalSupply();
error Launchpad__InsufficientValue();
error Launchpad__InvalidToken();
error Launchpad__ExcessiveCreationCost();
error Launchpad__ExcessiveBoosterFraction();
error Launchpad__ExcessiveGaugeFee();
error Launchpad__ExcessiveBondingFraction();
error Launchpad__InvalidIndex();
error Launchpad__TransferFailure();
////////////////////////////////////////////////////////////////////////////////
// EVENTS
////////////////////////////////////////////////////////////////////////////////
event NewToken(address indexed creator, address indexed token, address indexed gauge, address curve);
event TokenImplementationSet(address indexed newImpl, address indexed oldImpl);
event GaugeImplementationSet(address indexed newImpl, address indexed oldImpl);
event CurveSet(address indexed newCurve, address indexed oldCurve);
event TreasurySet(address indexed newTreasury, address indexed oldTreasury);
event LpReceiverSet(address indexed newReceiver, address indexed oldReceiver);
event CreationCostSet(uint256 newAmount, uint256 oldAmount);
event BoosterFractionSet(uint256 newFraction, uint256 oldFraction);
event GaugeFeesSet(uint256 newBuyFee, uint256 oldBuyFee, uint256 newSellFee, uint256 oldSellFee);
event BondingCurveFractionSet(uint256 newFraction, uint256 oldFraction);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import { ERC20PermitUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
import { Gauge } from "./Gauge.sol";
/**
MMMMMMMMMMMMMMMMMMMMMMMMWX0kol:,... ...,:cox0XWMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMWKkl;.. ..;lxKNMMMMMMMONLYMMMMMMMMM
MMMMCMMMMMMMMMMMMNOo,. .,lkXWMMMMMAPESMMMMMMM
MMMMMMMMMMMMMMNOl' .cONMMMMMMMMMMMMMM
MMMMMMMMMMMMXx;. ,dKWMMMMMMMMMMM
MMMMMMMMMWXd' .oKWMMMMMMMMM
MMMMMMMMNd' .oXMMMMMMMM
MMMMMMWO; ,kWMMMMMM
MMMMMNd. .lXMMMMM
MMMMKc ';cooollc:,. ;KMMMM
MMMK; .ckKNNNXKKKKKKOo, ,0MMM
MMK; .c0NNNNNNXKKKKKKKK0d' ,0MM
MXc .oXNNNNNNNXKKKKKKKKKKk; :KM
Wd. .oXNNNNNNNNXKKKKKKKKKKKk, oN
0, lXNNNNNNNNNXKKKKKKKKKKKKx. .O
o :KNNNNNNNNNNXKKKKKKKKKKKK0l. c
, ;0NNNNNNNNNNNXKKKKKKKKKKKKKk; '
. ,0WNNNNNNNNNNNXKKKKKKKKKKKKKOx, .
,OWWNNNNNNNNNNNXKKKKKKKKKKKKKOOd'
;0WWWNNNNNNNNNNNXKKKKKKKKKKKKK0OOd'
.cKMMMWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOd;
. .lXMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOxc.
. .'ckWMMMMWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxo;. .
: .,cllkWMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxddo:' ,
x. .';clnightMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxdddddc,.. .d
X: ..';:ccmonkexXNNNXXKKKKKKKKKKK000OOOOOOOOOOOkxxxxxdooooolcc:,'.. ;K
MO' ............................................................... .kW
MWx. .oNM
MMNd. lNMM
MMMNd. .oNMMM
MMMMWk' .xNMMMM
MMMMMW0: ;OWMMMMM
MMMMMMMNx' .dXMMMMMMM
MMMMMMMMWKo. .lKWMMMMMMMM
MMMMMMMMMMWKo' .l0WMMMMMMMMMM
MMMMMMMMMMMMWXx;. .,dKWMMMMMMMMMMMM
MMMMMMMMMMMMMMMW0o;. .,oONMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWKxc'. .':d0NMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMWN0xo:,.. ..':lx0NWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMWN0xo:'.. ..';lx0XWMMMMMMMMMMMMMMMMMMMMMMMMMM
*/
/**
* --------------------------------------------------------------------------------
*
* LIVE LIFE ON THE LEFT CURVE
*
* WEBSITE: https://memecoinmonitor.com/
* TWITTER: https://twitter.com/MemecoinMonitor
* TELEGRAM: https://t.me/OnlyApes
*
* --------------------------------------------------------------------------------
*
* @title LaunchpadToken
* @notice ERC20 token with transfer restricted when a linked gauge is active
* @dev Compatible with OpenZeppelin Contracts ^5.0.0
* @dev Intended for minimal proxy cloning
* @author BowTiedPickle
*
* --------------------------------------------------------------------------------
*/
contract LaunchpadToken is Initializable, ERC20Upgradeable, ERC20PermitUpgradeable {
////////////////////////////////////////////////////////////////////////////////
// STATE
////////////////////////////////////////////////////////////////////////////////
/// @notice Address of the gauge responsible for managing the token
Gauge public gauge;
/// @notice Address of the router allowed to transfer tokens while the gauge is active
address public router;
/// @notice Token image IPFS hash
string public ipfsHash;
/// @notice Project website
string public website;
/// @notice Project Twitter handle
string public twitter;
/// @notice Project Telegram link
string public telegram;
/// @notice Description of the token
string public description;
/// @notice Assorted metadata for the token
string public metadata;
////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTION AND INITIALIZATION
////////////////////////////////////////////////////////////////////////////////
constructor() {
_disableInitializers();
}
struct TokenConfig {
string name;
string symbol;
uint256 initialSupply;
}
struct TokenMetadataConfig {
string ipfsHash;
string website;
string twitter;
string telegram;
string description;
string metadata;
}
function initialize(TokenConfig memory _tokenConfig, TokenMetadataConfig memory _metadataConfig, address _gauge) external initializer {
__ERC20_init(_tokenConfig.name, _tokenConfig.symbol);
__ERC20Permit_init(_tokenConfig.name);
if (_gauge == address(0)) revert LaunchpadToken__ZeroAddress();
gauge = Gauge(_gauge);
router = msg.sender;
ipfsHash = _metadataConfig.ipfsHash;
website = _metadataConfig.website;
twitter = _metadataConfig.twitter;
telegram = _metadataConfig.telegram;
description = _metadataConfig.description;
metadata = _metadataConfig.metadata;
_mint(msg.sender, _tokenConfig.initialSupply);
}
////////////////////////////////////////////////////////////////////////////////
// METADATA
////////////////////////////////////////////////////////////////////////////////
function getAllMetadata() external view returns (TokenMetadataConfig memory) {
return
TokenMetadataConfig({
ipfsHash: ipfsHash,
website: website,
twitter: twitter,
telegram: telegram,
description: description,
metadata: metadata
});
}
////////////////////////////////////////////////////////////////////////////////
// ERRORS
////////////////////////////////////////////////////////////////////////////////
error LaunchpadToken__ZeroAddress();
error LaunchpadToken__TransferForbidden();
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @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 towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (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 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
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.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 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.
uint256 twos = denominator & (0 - denominator);
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 (unsignedRoundsUp(rounding) && 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
* towards zero.
*
* 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* 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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* 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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* 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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides tracking nonces for addresses. Nonces will only increment.
*/
abstract contract NoncesUpgradeable is Initializable {
/**
* @dev The nonce used for an `account` is not the expected current nonce.
*/
error InvalidAccountNonce(address account, uint256 currentNonce);
/// @custom:storage-location erc7201:openzeppelin.storage.Nonces
struct NoncesStorage {
mapping(address account => uint256) _nonces;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Nonces")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant NoncesStorageLocation = 0x5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00;
function _getNoncesStorage() private pure returns (NoncesStorage storage $) {
assembly {
$.slot := NoncesStorageLocation
}
}
function __Nonces_init() internal onlyInitializing {
}
function __Nonces_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the next unused nonce for an address.
*/
function nonces(address owner) public view virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
return $._nonces[owner];
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
// decremented or reset. This guarantees that the nonce never overflows.
unchecked {
// It is important to do x++ and not ++x here.
return $._nonces[owner]++;
}
}
/**
* @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
*/
function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
uint256 current = _useNonce(owner);
if (nonce != current) {
revert InvalidAccountNonce(owner, current);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../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.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Launchpad } from "./Launchpad.sol";
import { ReferralRouter } from "./ReferralRouter.sol";
/**
MMMMMMMMMMMMMMMMMMMMMMMMWX0kol:,... ...,:cox0XWMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMWKkl;.. ..;lxKNMMMMMMMONLYMMMMMMMMM
MMMMCMMMMMMMMMMMMNOo,. .,lkXWMMMMMAPESMMMMMMM
MMMMMMMMMMMMMMNOl' .cONMMMMMMMMMMMMMM
MMMMMMMMMMMMXx;. ,dKWMMMMMMMMMMM
MMMMMMMMMWXd' .oKWMMMMMMMMM
MMMMMMMMNd' .oXMMMMMMMM
MMMMMMWO; ,kWMMMMMM
MMMMMNd. .lXMMMMM
MMMMKc ';cooollc:,. ;KMMMM
MMMK; .ckKNNNXKKKKKKOo, ,0MMM
MMK; .c0NNNNNNXKKKKKKKK0d' ,0MM
MXc .oXNNNNNNNXKKKKKKKKKKk; :KM
Wd. .oXNNNNNNNNXKKKKKKKKKKKk, oN
0, lXNNNNNNNNNXKKKKKKKKKKKKx. .O
o :KNNNNNNNNNNXKKKKKKKKKKKK0l. c
, ;0NNNNNNNNNNNXKKKKKKKKKKKKKk; '
. ,0WNNNNNNNNNNNXKKKKKKKKKKKKKOx, .
,OWWNNNNNNNNNNNXKKKKKKKKKKKKKOOd'
;0WWWNNNNNNNNNNNXKKKKKKKKKKKKK0OOd'
.cKMMMWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOd;
. .lXMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOxc.
. .'ckWMMMMWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxo;. .
: .,cllkWMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxddo:' ,
x. .';clnightMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxdddddc,.. .d
X: ..';:ccmonkexXNNNXXKKKKKKKKKKK000OOOOOOOOOOOkxxxxxdooooolcc:,'.. ;K
MO' ............................................................... .kW
MWx. .oNM
MMNd. lNMM
MMMNd. .oNMMM
MMMMWk' .xNMMMM
MMMMMW0: ;OWMMMMM
MMMMMMMNx' .dXMMMMMMM
MMMMMMMMWKo. .lKWMMMMMMMM
MMMMMMMMMMWKo' .l0WMMMMMMMMMM
MMMMMMMMMMMMWXx;. .,dKWMMMMMMMMMMMM
MMMMMMMMMMMMMMMW0o;. .,oONMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWKxc'. .':d0NMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMWN0xo:,.. ..':lx0NWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMWN0xo:'.. ..';lx0XWMMMMMMMMMMMMMMMMMMMMMMMMMM
*/
/**
* --------------------------------------------------------------------------------
*
* LIVE LIFE ON THE LEFT CURVE
*
* WEBSITE: https://onlyapes.xyz/
* TWITTER: https://twitter.com/OnlyApesxyz
* TELEGRAM: https://t.me/OnlyApes
*
* --------------------------------------------------------------------------------
*
* @title Referral Handler
* @notice Register and manage referrals, receive and attribute swap fees from Gauge instances
* @author BowTiedPickle
*
* --------------------------------------------------------------------------------
*/
contract ReferralHandler is Ownable {
////////////////////////////////////////////////////////////////////////////////
// CONSTANTS AND IMMUTABLES
////////////////////////////////////////////////////////////////////////////////
/// @notice Fraction denominator
uint256 public constant FRACTION_DENOMINATOR = 1e18;
/// @dev The zero referral code is reserved for referral nonexistence
bytes32 public constant ZERO_REFERRAL_CODE = bytes32(0);
/// @dev The protocol referral code is reserved for protocol fees
bytes32 public constant PROTOCOL_REFERRAL_CODE = ~bytes32(0);
/// @notice Launchpad contract
Launchpad public immutable LAUNCHPAD;
/// @notice Referral router contract
ReferralRouter public immutable REFERRAL_ROUTER;
////////////////////////////////////////////////////////////////////////////////
// CONFIGURATION
////////////////////////////////////////////////////////////////////////////////
/// @notice Default duration for referrals, 0 for no expiration
uint256 public defaultDuration;
/// @notice Fraction of fees given to referrer for volume tier 1 (1e18 = 100%)
uint256 public tier1ReferralFraction = 0.2e18; // 20%
/// @notice Volume threshold for volume tier 2, wei of ETH
uint256 public tier2Volume = 30 ether;
/// @notice Fraction of fees given to referrer for volume tier 2 (1e18 = 100%)
uint256 public tier2ReferralFraction = 0.3e18; // 30%
/// @notice Volume beyond which no referral fees are awarded, wei of ETH
uint256 public cutoffVolume = type(uint256).max;
/// @notice Treasury address
address public treasury;
////////////////////////////////////////////////////////////////////////////////
// STATE
////////////////////////////////////////////////////////////////////////////////
struct Referral {
// Referral code
bytes32 code;
// Unix epoch timestamp of expiration, 0 = no expiration
uint256 expiry;
}
/// @dev Referral mapping
mapping(address user => Referral referral) internal _referrals;
struct CodeInfo {
// ETH volume referred by this code
uint256 volume;
// Custom duration for this code, 0 to use the default
uint256 customDuration;
// Accumulated fees for this code
uint256 accumulatedFees;
// Payout address for this code
address payoutAddress;
}
mapping(bytes32 code => CodeInfo codeInfo) public codes;
mapping(address referrer => bytes32 code) public referrerToCode;
////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
////////////////////////////////////////////////////////////////////////////////
constructor(Launchpad _launchpad, ReferralRouter _referralRouter, address _treasury) Ownable(msg.sender) {
if (address(_launchpad) == address(0) || address(_referralRouter) == address(0) || address(_treasury) == address(0))
revert ReferralHandler__ZeroAddress();
LAUNCHPAD = _launchpad;
REFERRAL_ROUTER = _referralRouter;
treasury = _treasury;
// TODO set initial fee and volume params
}
////////////////////////////////////////////////////////////////////////////////
// REFERRERS
////////////////////////////////////////////////////////////////////////////////
/**
* @notice Register a referral code
* @param code Referral code
*/
function registerReferralCode(bytes32 code) external {
if (code == ZERO_REFERRAL_CODE || code == PROTOCOL_REFERRAL_CODE) revert ReferralHandler__InvalidCode();
if (codes[code].payoutAddress != address(0)) revert ReferralHandler__CodeAlreadyRegistered();
if (referrerToCode[msg.sender] != ZERO_REFERRAL_CODE) revert ReferralHandler__ReferrerAlreadyHasCode();
// If the user does not themselves have a referral code set, set to the protocol code
if (_referrals[msg.sender].code == ZERO_REFERRAL_CODE) {
_referrals[msg.sender] = Referral(PROTOCOL_REFERRAL_CODE, 0);
}
codes[code].payoutAddress = msg.sender;
referrerToCode[msg.sender] = code;
emit ReferralCodeRegistered(code, msg.sender);
}
/**
* @notice Withdraw fees for a referral code
* @param code Referral code
* @return fees Amount withdrawn
*/
function withdrawFees(bytes32 code) external returns (uint256) {
if (msg.sender != codes[code].payoutAddress) revert ReferralHandler__CallerNotCodeOwner();
uint256 fees = codes[code].accumulatedFees;
codes[code].accumulatedFees = 0;
if (fees > 0) {
payable(msg.sender).transfer(fees);
}
emit FeeWithdraw(code, msg.sender, fees);
return fees;
}
/**
* @notice Set the payout address for a referral code
* @param code Referral code
* @param payout New payout address
*/
function setPayoutAddress(bytes32 code, address payout) external onlyOwner {
if (code == ZERO_REFERRAL_CODE || code == PROTOCOL_REFERRAL_CODE) revert ReferralHandler__InvalidCode();
if (msg.sender != codes[code].payoutAddress) revert ReferralHandler__CallerNotCodeOwner();
if (payout == address(0)) revert ReferralHandler__ZeroAddress();
if (referrerToCode[payout] != ZERO_REFERRAL_CODE) revert ReferralHandler__ReferrerAlreadyHasCode();
referrerToCode[msg.sender] = ZERO_REFERRAL_CODE;
referrerToCode[payout] = code;
codes[code].payoutAddress = payout;
emit PayoutAddressSet(code, payout, msg.sender);
}
////////////////////////////////////////////////////////////////////////////////
// USERS
////////////////////////////////////////////////////////////////////////////////
/**
* @notice Set the referral code for the caller
* @param code Referral code
* @return expiry Expiry timestamp
*/
function setReferral(address user, bytes32 code) external returns (uint256) {
if (code == ZERO_REFERRAL_CODE) revert ReferralHandler__InvalidCode();
if (msg.sender != user && msg.sender != address(REFERRAL_ROUTER)) revert ReferralHandler__CallerIsNotUserOrRouter();
if (_referrals[user].code != ZERO_REFERRAL_CODE) revert ReferralHandler__ReferralAlreadySet();
uint256 duration = codes[code].customDuration > 0 ? codes[code].customDuration : defaultDuration;
uint256 expiry = duration > 0 ? block.timestamp + duration : 0;
_referrals[user] = Referral(code, expiry);
emit ReferralSet(user, code, expiry);
return expiry;
}
////////////////////////////////////////////////////////////////////////////////
// VIEWS
////////////////////////////////////////////////////////////////////////////////
/**
* @notice Get the referral info for a user
* @param user User address
* @return referral Referral info
*/
function getReferralInfo(address user) external view returns (Referral memory) {
return _referrals[user];
}
/**
* @notice Get the referral code used by a user
* @param user User address
* @return code Referral code
*/
function getReferralCode(address user) external view returns (bytes32) {
return _referrals[user].code;
}
/**
* @notice Get the volume referred by a referral code
* @param code Referral code
* @return volume Referred swap volume, wei of ETH
*/
function referredVolume(bytes32 code) external view returns (uint256) {
return codes[code].volume;
}
/**
* @notice Get the custom duration for a referral code
* @param code Referral code
* @return duration Custom duration, seconds, 0 for default
*/
function customDuration(bytes32 code) external view returns (uint256) {
return codes[code].customDuration;
}
/**
* @notice Get the payout address for a referral code
* @param code Referral code
* @return payoutAddress Payout address
*/
function payoutAddress(bytes32 code) external view returns (address) {
return codes[code].payoutAddress;
}
/**
* @notice Get the accumulated fees for a referral code
* @param code Referral code
* @return accumulatedFees Accumulated fees, wei of ETH
*/
function accumulatedFees(bytes32 code) external view returns (uint256) {
return codes[code].accumulatedFees;
}
////////////////////////////////////////////////////////////////////////////////
// HOOKS
////////////////////////////////////////////////////////////////////////////////
/**
* @notice Handle fees from a swap
* @dev May only be called by Gauge contracts deployed from the Launchpad
* @dev Fees are passed as `msg.value`
* @param user Swap recipient address
* @param token Token address associated with the calling gauge
* @param ethVolume ETH volume of the swap
* @return referredFee Referred fee
*/
function handleFees(address user, address token, uint256 ethVolume) external payable returns (uint256) {
if (msg.sender != LAUNCHPAD.tokenToGauge(token)) revert ReferralHandler__CallerIsNotGauge();
Referral memory referral = _referrals[user];
uint256 referredFee;
if (
ethVolume > 0 &&
msg.value > 0 &&
referral.code != ZERO_REFERRAL_CODE &&
referral.code != PROTOCOL_REFERRAL_CODE &&
(referral.expiry == 0 || referral.expiry >= block.timestamp)
) {
CodeInfo storage codeInfo = codes[referral.code];
uint256 remainingTier1Volume = codeInfo.volume >= tier2Volume ? 0 : tier2Volume - codeInfo.volume;
uint256 remainingTier2Volume = codeInfo.volume >= cutoffVolume ? 0 : cutoffVolume - codeInfo.volume - remainingTier1Volume;
uint256 tier1Amount = ethVolume > remainingTier1Volume ? remainingTier1Volume : ethVolume;
uint256 tier2Amount = ethVolume - tier1Amount > remainingTier2Volume ? remainingTier2Volume : ethVolume - tier1Amount;
// Calculate fees due at each tier
if (tier1Amount > 0) {
referredFee += (msg.value * tier1Amount * tier1ReferralFraction) / (ethVolume * FRACTION_DENOMINATOR);
}
if (tier2Amount > 0) {
referredFee += (msg.value * tier2Amount * tier2ReferralFraction) / (ethVolume * FRACTION_DENOMINATOR);
}
codeInfo.volume += ethVolume;
codeInfo.accumulatedFees += referredFee;
} else {
codes[PROTOCOL_REFERRAL_CODE].volume += ethVolume;
}
if (msg.value > referredFee) {
codes[PROTOCOL_REFERRAL_CODE].accumulatedFees += msg.value - referredFee;
}
emit SwapReferred(user, referral.code, ethVolume, referredFee);
return (referredFee);
}
////////////////////////////////////////////////////////////////////////////////
// ADMINISTRATION
////////////////////////////////////////////////////////////////////////////////
/**
* @notice Withdraw protocol fees
*/
function withdrawProtocolFees() external returns (uint256) {
uint256 fees = codes[PROTOCOL_REFERRAL_CODE].accumulatedFees;
codes[PROTOCOL_REFERRAL_CODE].accumulatedFees = 0;
if (fees > 0) {
(bool success, ) = payable(treasury).call{ value: fees }("");
if (!success) revert ReferralHandler__TransferFailure();
}
emit FeeWithdraw(PROTOCOL_REFERRAL_CODE, treasury, fees);
return fees;
}
/**
* @notice Set the default referral duration
* @param _defaultDuration New default duration
*/
function setDefaultDuration(uint256 _defaultDuration) external onlyOwner {
emit DefaultDurationSet(_defaultDuration, defaultDuration);
defaultDuration = _defaultDuration;
}
/**
* @notice Set the tier volume limits
* @param _tier2Volume New tier 1 volume
* @param _cutoffVolume New tier 2 volume
*/
function setTierVolume(uint256 _tier2Volume, uint256 _cutoffVolume) external onlyOwner {
if (_tier2Volume > _cutoffVolume) revert ReferralHandler__TierOrdering();
emit TierVolumeSet(_tier2Volume, tier2Volume, _cutoffVolume, cutoffVolume);
tier2Volume = _tier2Volume;
cutoffVolume = _cutoffVolume;
}
/**
* @notice Set the tier referral fractions
* @param _tier1ReferralFraction New tier 1 referral fraction
* @param _tier2ReferralFraction New tier 2 referral fraction
*/
function setTierReferralFraction(uint256 _tier1ReferralFraction, uint256 _tier2ReferralFraction) external onlyOwner {
if (_tier1ReferralFraction > FRACTION_DENOMINATOR || _tier2ReferralFraction > FRACTION_DENOMINATOR)
revert ReferralHandler__ExcessiveFraction();
emit TierReferralFractionSet(_tier1ReferralFraction, tier1ReferralFraction, _tier2ReferralFraction, tier2ReferralFraction);
tier1ReferralFraction = _tier1ReferralFraction;
tier2ReferralFraction = _tier2ReferralFraction;
}
/**
* @notice Set the treasury address
* @param _treasury New treasury address
*/
function setTreasury(address _treasury) external onlyOwner {
if (_treasury == address(0)) revert ReferralHandler__ZeroAddress();
emit TreasurySet(_treasury, treasury);
treasury = _treasury;
}
struct DurationInput {
bytes32 code;
uint256 duration;
}
/**
* @notice Set custom durations for referral codes
* @param inputs Array of code-duration pairs
*/
function setCustomDurations(DurationInput[] calldata inputs) external onlyOwner {
for (uint256 i; i < inputs.length; ) {
if (inputs[i].code == ZERO_REFERRAL_CODE || inputs[i].code == PROTOCOL_REFERRAL_CODE) revert ReferralHandler__InvalidCode();
emit CustomDurationSet(inputs[i].code, inputs[i].duration, codes[inputs[i].code].customDuration);
codes[inputs[i].code].customDuration = inputs[i].duration;
unchecked {
++i;
}
}
}
struct ExpiryInput {
address user;
uint256 expiry;
}
/**
* @notice Override referral expiries
* @param inputs Array of user-expiry pairs
*/
function overrideExpiries(ExpiryInput[] calldata inputs) external onlyOwner {
for (uint256 i; i < inputs.length; ) {
Referral storage referral = _referrals[inputs[i].user];
emit ExpiryOverriden(inputs[i].user, inputs[i].expiry, referral.expiry);
referral.expiry = inputs[i].expiry;
unchecked {
++i;
}
}
}
////////////////////////////////////////////////////////////////////////////////
// ERRORS
////////////////////////////////////////////////////////////////////////////////
error ReferralHandler__ZeroAddress();
error ReferralHandler__InvalidCode();
error ReferralHandler__CodeAlreadyRegistered();
error ReferralHandler__CallerNotCodeOwner();
error ReferralHandler__ExcessiveFraction();
error ReferralHandler__TierOrdering();
error ReferralHandler__TransferFailure();
error ReferralHandler__CallerIsNotGauge();
error ReferralHandler__CallerIsNotUserOrRouter();
error ReferralHandler__ReferralAlreadySet();
error ReferralHandler__ReferrerAlreadyHasCode();
////////////////////////////////////////////////////////////////////////////////
// EVENTS
////////////////////////////////////////////////////////////////////////////////
event ReferralCodeRegistered(bytes32 indexed code, address indexed payoutAddress);
event PayoutAddressSet(bytes32 indexed code, address newPayoutAddress, address oldPayoutAddress);
event ReferralSet(address indexed user, bytes32 indexed code, uint256 expiry);
event SwapReferred(address indexed user, bytes32 indexed code, uint256 ethVolume, uint256 referredFees);
event FeeWithdraw(bytes32 indexed code, address indexed payoutAddress, uint256 amount);
event DefaultDurationSet(uint256 newDuration, uint256 oldDuration);
event TierVolumeSet(uint256 tier1newVolume, uint256 tier1oldVolume, uint256 tier2newVolume, uint256 tier2oldVolume);
event TierReferralFractionSet(uint256 tier1newFraction, uint256 tier1oldFraction, uint256 tier2newFraction, uint256 tier2oldFraction);
event TreasurySet(address newTreasury, address oldTreasury);
event CustomDurationSet(bytes32 indexed code, uint256 newDuration, uint256 oldDuration);
event ExpiryOverriden(address user, uint256 newExpiry, uint256 oldExpiry);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Gauge } from "./Gauge.sol";
import { Launchpad } from "./Launchpad.sol";
import { LaunchpadToken } from "./LaunchpadToken.sol";
import { ReferralHandler } from "./ReferralHandler.sol";
/**
MMMMMMMMMMMMMMMMMMMMMMMMWX0kol:,... ...,:cox0XWMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMWKkl;.. ..;lxKNMMMMMMMONLYMMMMMMMMM
MMMMCMMMMMMMMMMMMNOo,. .,lkXWMMMMMAPESMMMMMMM
MMMMMMMMMMMMMMNOl' .cONMMMMMMMMMMMMMM
MMMMMMMMMMMMXx;. ,dKWMMMMMMMMMMM
MMMMMMMMMWXd' .oKWMMMMMMMMM
MMMMMMMMNd' .oXMMMMMMMM
MMMMMMWO; ,kWMMMMMM
MMMMMNd. .lXMMMMM
MMMMKc ';cooollc:,. ;KMMMM
MMMK; .ckKNNNXKKKKKKOo, ,0MMM
MMK; .c0NNNNNNXKKKKKKKK0d' ,0MM
MXc .oXNNNNNNNXKKKKKKKKKKk; :KM
Wd. .oXNNNNNNNNXKKKKKKKKKKKk, oN
0, lXNNNNNNNNNXKKKKKKKKKKKKx. .O
o :KNNNNNNNNNNXKKKKKKKKKKKK0l. c
, ;0NNNNNNNNNNNXKKKKKKKKKKKKKk; '
. ,0WNNNNNNNNNNNXKKKKKKKKKKKKKOx, .
,OWWNNNNNNNNNNNXKKKKKKKKKKKKKOOd'
;0WWWNNNNNNNNNNNXKKKKKKKKKKKKK0OOd'
.cKMMMWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOd;
. .lXMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOxc.
. .'ckWMMMMWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxo;. .
: .,cllkWMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxddo:' ,
x. .';clnightMMMWWNNNNNNNNNNNXKKKKKKKKKKKKKOOOOOkxdddddc,.. .d
X: ..';:ccmonkexXNNNXXKKKKKKKKKKK000OOOOOOOOOOOkxxxxxdooooolcc:,'.. ;K
MO' ............................................................... .kW
MWx. .oNM
MMNd. lNMM
MMMNd. .oNMMM
MMMMWk' .xNMMMM
MMMMMW0: ;OWMMMMM
MMMMMMMNx' .dXMMMMMMM
MMMMMMMMWKo. .lKWMMMMMMMM
MMMMMMMMMMWKo' .l0WMMMMMMMMMM
MMMMMMMMMMMMWXx;. .,dKWMMMMMMMMMMMM
MMMMMMMMMMMMMMMW0o;. .,oONMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWKxc'. .':d0NMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMWN0xo:,.. ..':lx0NWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMWN0xo:'.. ..';lx0XWMMMMMMMMMMMMMMMMMMMMMMMMMM
*/
/**
* --------------------------------------------------------------------------------
*
* LIVE LIFE ON THE LEFT CURVE
*
* WEBSITE: https://onlyapes.xyz/
* TWITTER: https://twitter.com/OnlyApesxyz
* TELEGRAM: https://t.me/OnlyApes
*
* --------------------------------------------------------------------------------
*
* @title Referral Router
* @notice Atomically set referral and trade tokens
* @author BowTiedPickle
*
* --------------------------------------------------------------------------------
*/
contract ReferralRouter is Ownable {
////////////////////////////////////////////////////////////////////////////////
// CONSTANTS AND IMMUTABLES
////////////////////////////////////////////////////////////////////////////////
/// @dev The zero referral code is reserved for referral nonexistence
bytes32 public constant ZERO_REFERRAL_CODE = bytes32(0);
/// @dev The protocol referral code is reserved for protocol fees
bytes32 public constant PROTOCOL_REFERRAL_CODE = ~bytes32(0);
/// @notice Launchpad contract
Launchpad public immutable launchpad;
////////////////////////////////////////////////////////////////////////////////
// CONFIGURATION
////////////////////////////////////////////////////////////////////////////////
/// @notice Referral handler contract
ReferralHandler public referralHandler;
////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
////////////////////////////////////////////////////////////////////////////////
/**
* @param _launchpad Launchpad contract
*/
constructor(Launchpad _launchpad) Ownable(msg.sender) {
if (address(_launchpad) == address(0)) revert ReferralRouter__ZeroAddress();
launchpad = _launchpad;
}
////////////////////////////////////////////////////////////////////////////////
// TRADE TOKENS
////////////////////////////////////////////////////////////////////////////////
/**
* @notice Buy an exact amount of tokens
* @dev Allowable slippage is defined by msg.value
* @param token Token address
* @param amountOut Amount of tokens to buy
* @param code Referral code to set, bytes32(0) to leave unchanged
*/
function buyExactTokens(address token, uint256 amountOut, bytes32 code) external payable {
address gauge = launchpad.tokenToGauge(token);
if (gauge == address(0)) revert ReferralRouter__InvalidToken();
bytes32 existingReferral = referralHandler.getReferralCode(msg.sender);
if (code != ZERO_REFERRAL_CODE && existingReferral == ZERO_REFERRAL_CODE) {
referralHandler.setReferral(msg.sender, code);
} else if (code == ZERO_REFERRAL_CODE && existingReferral == ZERO_REFERRAL_CODE) {
referralHandler.setReferral(msg.sender, PROTOCOL_REFERRAL_CODE);
}
Gauge(gauge).buyExactTokens{ value: msg.value }(msg.sender, amountOut);
}
/**
* @notice Sell an exact amount of tokens
* @param token Token address
* @param amountIn Amount of tokens to sell
* @param minAmountOut Minimum amount of ETH to receive
* @param code Referral code to set, bytes32(0) to leave unchanged
*/
function sellExactTokens(address token, uint256 amountIn, uint256 minAmountOut, bytes32 code) external {
address gauge = launchpad.tokenToGauge(token);
if (gauge == address(0)) revert ReferralRouter__InvalidToken();
bytes32 existingReferral = referralHandler.getReferralCode(msg.sender);
if (code != ZERO_REFERRAL_CODE && existingReferral == ZERO_REFERRAL_CODE) {
referralHandler.setReferral(msg.sender, code);
} else if (code == ZERO_REFERRAL_CODE && existingReferral == ZERO_REFERRAL_CODE) {
referralHandler.setReferral(msg.sender, PROTOCOL_REFERRAL_CODE);
}
LaunchpadToken(token).transferFrom(msg.sender, address(this), amountIn);
LaunchpadToken(token).approve(gauge, amountIn);
Gauge(gauge).sellExactTokens(msg.sender, amountIn, minAmountOut);
}
/**
* @notice Buy the maximum amount of tokens for an exact ETH input
* @param token Token address
* @param minAmountOut Minimum amount of tokens to receive
* @param code Referral code to set, bytes32(0) to leave unchanged
*/
function buyExactEth(address token, uint256 minAmountOut, bytes32 code) external payable {
address gauge = launchpad.tokenToGauge(token);
if (gauge == address(0)) revert ReferralRouter__InvalidToken();
bytes32 existingReferral = referralHandler.getReferralCode(msg.sender);
if (code != ZERO_REFERRAL_CODE && existingReferral == ZERO_REFERRAL_CODE) {
referralHandler.setReferral(msg.sender, code);
} else if (code == ZERO_REFERRAL_CODE && existingReferral == ZERO_REFERRAL_CODE) {
referralHandler.setReferral(msg.sender, PROTOCOL_REFERRAL_CODE);
}
Gauge(gauge).buyExactEth{ value: msg.value }(msg.sender, minAmountOut);
}
/**
* @notice Sell the minimum amount of tokens for an exact ETH output
* @param token Token address
* @param amountOut Amount of ETH to receive
* @param maxInput Maximum amount of tokens to sell
* @param code Referral code to set, bytes32(0) to leave unchanged
*/
function sellExactEth(address token, uint256 amountOut, uint256 maxInput, bytes32 code) external {
address gauge = launchpad.tokenToGauge(token);
if (gauge == address(0)) revert ReferralRouter__InvalidToken();
bytes32 existingReferral = referralHandler.getReferralCode(msg.sender);
if (code != ZERO_REFERRAL_CODE && existingReferral == ZERO_REFERRAL_CODE) {
referralHandler.setReferral(msg.sender, code);
} else if (code == ZERO_REFERRAL_CODE && existingReferral == ZERO_REFERRAL_CODE) {
referralHandler.setReferral(msg.sender, PROTOCOL_REFERRAL_CODE);
}
(uint256 amountIn, ) = Gauge(gauge).quoteSellExactEth(amountOut);
LaunchpadToken(token).transferFrom(msg.sender, address(this), amountIn);
LaunchpadToken(token).approve(gauge, amountIn);
Gauge(gauge).sellExactEth(msg.sender, amountOut, maxInput);
}
////////////////////////////////////////////////////////////////////////////////
// ADMINISTRATION
////////////////////////////////////////////////////////////////////////////////
/**
* @notice Set the referral handler
* @param _referralHandler The new referral handler
*/
function setReferralHandler(ReferralHandler _referralHandler) external onlyOwner {
if (address(_referralHandler) == address(0)) revert ReferralRouter__ZeroAddress();
emit ReferralHandlerSet(address(_referralHandler), address(referralHandler));
referralHandler = _referralHandler;
}
////////////////////////////////////////////////////////////////////////////////
// ERRORS
////////////////////////////////////////////////////////////////////////////////
error ReferralRouter__ZeroAddress();
error ReferralRouter__InvalidToken();
////////////////////////////////////////////////////////////////////////////////
// EVENTS
////////////////////////////////////////////////////////////////////////////////
event ReferralHandlerSet(address newReferralHandler, address oldReferralHandler);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
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 bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
{
"compilationTarget": {
"src/ReferralRouter.sol": "ReferralRouter"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "none"
},
"optimizer": {
"enabled": true,
"runs": 10000
},
"remappings": [
":@chainlink/=node_modules/@chainlink/",
":@eth-optimism/=node_modules/@eth-optimism/",
":@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
":@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
":@prb/test/=node_modules/@prb/test/",
":@scroll-tech/=node_modules/@scroll-tech/",
":@uniswap/v3-core/=node_modules/@uniswap/v3-core/",
":@uniswap/v3-periphery/=node_modules/@uniswap/v3-periphery/",
":base64-sol/=node_modules/base64-sol/",
":forge-std/=node_modules/forge-std/"
]
}
[{"inputs":[{"internalType":"contract Launchpad","name":"_launchpad","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"ReferralRouter__InvalidToken","type":"error"},{"inputs":[],"name":"ReferralRouter__ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newReferralHandler","type":"address"},{"indexed":false,"internalType":"address","name":"oldReferralHandler","type":"address"}],"name":"ReferralHandlerSet","type":"event"},{"inputs":[],"name":"PROTOCOL_REFERRAL_CODE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ZERO_REFERRAL_CODE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"},{"internalType":"bytes32","name":"code","type":"bytes32"}],"name":"buyExactEth","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"bytes32","name":"code","type":"bytes32"}],"name":"buyExactTokens","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"launchpad","outputs":[{"internalType":"contract Launchpad","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"referralHandler","outputs":[{"internalType":"contract ReferralHandler","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"maxInput","type":"uint256"},{"internalType":"bytes32","name":"code","type":"bytes32"}],"name":"sellExactEth","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"},{"internalType":"bytes32","name":"code","type":"bytes32"}],"name":"sellExactTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract ReferralHandler","name":"_referralHandler","type":"address"}],"name":"setReferralHandler","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]