Verified contractExactMIT
Lens
Address0x088af53a7dc3e2349af506999bb35bcbc984c021
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,137,983
- Creation transaction
- 0x462a0f1de6…e8b2ace1f1
13 files
- src/Lens.solmain3.85 KB
- lib/openzeppelin/interfaces/draft-IERC6093.sol6.56 KB
- lib/openzeppelin/token/ERC20/ERC20.sol10.8 KB
- lib/openzeppelin/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin/utils/Context.sol963 B
- lib/v4-core/libraries/BitMath.sol2.61 KB
- lib/v4-core/libraries/CustomRevert.sol5.17 KB
- lib/v4-core/libraries/TickMath.sol12.38 KB
- src/Base64.sol1.57 KB
- src/FullMath.sol1.73 KB
- src/GatedToken.sol9.15 KB
- src/Launchpad.sol19.27 KB
src/Lens.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {GatedToken, IUniswapV3PoolSlot0} from "./GatedToken.sol";
import {Launchpad, INonfungiblePositionManager} from "./Launchpad.sol";
import {FullMath} from "./FullMath.sol";
/// @title Lens — read-only aggregation for the alleyes site and controller.
contract Lens {
Launchpad public immutable pad;
constructor(Launchpad _pad) {
pad = _pad;
}
struct Quote {
address token;
address pool;
address deployer;
address feeRecipient;
string fomoProfile;
string fomoPfp;
string name;
string symbol;
string imageURI;
string xUrl;
string webUrl;
string tgUrl;
string bio;
uint160 sqrtPriceX96;
int24 tick;
uint256 mcapUsdc; // USD, 6 decimals (name kept for the shared front-end)
uint256 startMcapUsdc; // USD, 6 decimals (the launchpad's configured open)
uint256 gradMcapUsdc; // USD, 6 decimals (configured graduation)
uint256 mcapEth; // ETH wei
uint64 windowEnd;
bool graduated;
bool blinking;
uint256 tokensInPool;
uint256 ethUsd8; // oracle price used
}
function quote(address token) public view returns (Quote memory q) {
(address deployer, address feeRecipient, address pool,, bool exists, string memory fomoProfile, string memory fomoPfp) = pad.launches(token);
require(exists, "unknown token");
GatedToken t = GatedToken(token);
(uint160 sqrtP, int24 tick,,,,,) = IUniswapV3PoolSlot0(pool).slot0();
bool isT0 = t.tokenIsToken0();
uint256 usd = pad.ethPrice();
q.token = token;
q.pool = pool;
q.deployer = deployer;
q.feeRecipient = feeRecipient;
q.fomoProfile = fomoProfile;
q.fomoPfp = fomoPfp;
q.name = t.name();
q.symbol = t.symbol();
q.imageURI = t.imageURI();
q.xUrl = t.xUrl();
q.webUrl = t.webUrl();
q.tgUrl = t.tgUrl();
q.bio = t.bio();
q.sqrtPriceX96 = sqrtP;
q.tick = tick;
q.mcapEth = _mcapEth(sqrtP, isT0);
q.mcapUsdc = FullMath.mulDiv(q.mcapEth, usd, 1e20); // wei * 1e8 / 1e18 -> 1e-6 USD
q.startMcapUsdc = pad.startMcapUsd() * 1e6;
q.gradMcapUsdc = pad.gradMcapUsd() * 1e6;
q.windowEnd = t.windowEnd();
q.graduated = t.graduated();
q.blinking = t.blinking();
q.tokensInPool = t.balanceOf(pool);
q.ethUsd8 = usd;
}
function quoteMany(address[] calldata tokens) external view returns (Quote[] memory qs) {
qs = new Quote[](tokens.length);
for (uint256 i; i < tokens.length; i++) qs[i] = quote(tokens[i]);
}
function positionOf(address token)
external
view
returns (uint256 tokenId, uint128 liquidity, int24 tickLower, int24 tickUpper, uint128 owed0, uint128 owed1)
{
(,,, uint256 id, bool exists,,) = pad.launches(token);
require(exists, "unknown token");
tokenId = id;
(,,,,, tickLower, tickUpper, liquidity,,, owed0, owed1) = pad.nfpm().positions(tokenId);
}
/// @dev mcap in WETH wei = SUPPLY * price (WETH per token). token0: price = sqrtP^2/2^192; token1: 2^192/sqrtP^2.
function _mcapEth(uint160 sqrtP, bool isT0) internal pure returns (uint256) {
uint256 s = uint256(sqrtP);
uint256 supply = 1_000_000_000e18;
if (isT0) {
uint256 p96 = FullMath.mulDiv(s, s, 1 << 96);
return FullMath.mulDiv(p96, supply, 1 << 96);
} else {
uint256 inv96 = FullMath.mulDiv(1 << 96, 1 << 96, s);
uint256 p96 = FullMath.mulDiv(inv96, inv96, 1 << 96);
return FullMath.mulDiv(p96, supply, 1 << 96);
}
}
}
lib/openzeppelin/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 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 ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
* 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 ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 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);
}
lib/openzeppelin/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.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 ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
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;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
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;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
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}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* 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 {
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 sets 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:
*
* ```solidity
* 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 {
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);
}
}
}
}
lib/openzeppelin/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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);
}
lib/openzeppelin/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 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);
}
lib/openzeppelin/utils/Context.sol
// 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;
}
}
lib/v4-core/libraries/BitMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
/// @notice Returns the index of the most significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the most significant bit, must be greater than 0
/// @return r the index of the most significant bit
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020500060203020504000106050205030304010505030400000000))
}
}
/// @notice Returns the index of the least significant bit of the number,
/// where the least significant bit is at index 0 and the most significant bit is at index 255
/// @param x the value for which to compute the least significant bit, must be greater than 0
/// @return r the index of the least significant bit
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0);
assembly ("memory-safe") {
// Isolate the least significant bit.
x := and(x, sub(0, x))
// For the upper 3 bits of the result, use a De Bruijn-like lookup.
// Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
// forgefmt: disable-next-item
r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
0x8040405543005266443200005020610674053026020000107506200176117077)))
// For the lower 5 bits of the result, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
}
}
}
lib/v4-core/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
lib/v4-core/libraries/TickMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
using CustomRevert for bytes4;
/// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
error InvalidTick(int24 tick);
/// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
error InvalidSqrtPrice(uint160 sqrtPriceX96);
/// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
/// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
int24 internal constant MAX_TICK = 887272;
/// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
int24 internal constant MIN_TICK_SPACING = 1;
/// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
int24 internal constant MAX_TICK_SPACING = type(int16).max;
/// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_PRICE = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
/// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
1461446703485210103287273052203988822378723970342 - 4295128739 - 1;
/// @notice Given a tickSpacing, compute the maximum usable tick
function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MAX_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Given a tickSpacing, compute the minimum usable tick
function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
unchecked {
return (MIN_TICK / tickSpacing) * tickSpacing;
}
}
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
/// at the given tick
function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
unchecked {
uint256 absTick;
assembly ("memory-safe") {
tick := signextend(2, tick)
// mask = 0 if tick >= 0 else -1 (all 1s)
let mask := sar(255, tick)
// if tick >= 0, |tick| = tick = 0 ^ tick
// if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
// either way, |tick| = mask ^ (tick + mask)
absTick := xor(mask, add(mask, tick))
}
if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);
// The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
// is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer
// Equivalent to:
// price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
// or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
uint256 price;
assembly ("memory-safe") {
price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
}
if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;
assembly ("memory-safe") {
// if (tick > 0) price = type(uint256).max / price;
if sgt(tick, 0) { price := div(not(0), price) }
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtPrice of the output price is always consistent
// `sub(shl(32, 1), 1)` is `type(uint32).max`
// `price + type(uint32).max` will not overflow because `price` fits in 192 bits
sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
}
}
}
/// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
// second inequality must be >= because the price can never reach the price at the max tick
// if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
// if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
}
uint256 price = uint256(sqrtPriceX96) << 32;
uint256 r = price;
uint256 msb = BitMath.mostSignificantBit(r);
if (msb >= 128) r = price >> (msb - 127);
else r = price << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly ("memory-safe") {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number
// Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
// Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
// sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
// is changed, this may need to be changed too
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
src/Base64.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice Minimal base64 encoder (OpenZeppelin-derived, MIT) for on-chain contractURI JSON.
library Base64 {
string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
string memory table = TABLE;
string memory result = new string(4 * ((data.length + 2) / 3));
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for { let dataPtr := data } lt(dataPtr, add(data, mload(data))) {} {
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1)
}
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 { mstore8(sub(resultPtr, 1), 0x3d) }
}
return result;
}
}
src/FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @notice 512-bit mulDiv (Remco Bloemen, MIT). Used only by the launchpad's read-only lens.
library FullMath {
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
uint256 prod0;
uint256 prod1;
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
require(denominator > prod1);
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
uint256 twos = denominator & (~denominator + 1);
assembly {
denominator := div(denominator, twos)
prod0 := div(prod0, twos)
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
uint256 inverse = (3 * denominator) ^ 2;
inverse *= 2 - denominator * inverse;
inverse *= 2 - denominator * inverse;
inverse *= 2 - denominator * inverse;
inverse *= 2 - denominator * inverse;
inverse *= 2 - denominator * inverse;
inverse *= 2 - denominator * inverse;
result = prod0 * inverse;
return result;
}
}
}
src/GatedToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Base64} from "./Base64.sol";
interface IRelayRegistry {
function isRelayer(address) external view returns (bool);
}
interface IUniswapV3PoolSlot0 {
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint32 feeProtocol, // Uniswap V3 packs two fees here (Uniswap uses uint8; ABI-compatible)
bool unlocked
);
}
/// @title GatedToken (alleyes, Ethereum)
/// @notice Fixed 1B-supply launch token. While the token is "blinking", BUYS (transfers OUT of the canonical
/// v3 pool) only succeed if `tx.origin` is an allowlisted relayer, i.e. the buy came through Fomo
/// (Fomo's relayer fleet sends every user buy; the user never signs), or the transaction was
/// sent by the token's deployer (so the creator can buy their own launch). Sells and plain
/// transfers are always allowed. A 2% max-wallet cap applies to non-exempt recipients.
///
/// The blink ends on the FIRST of:
/// 1. graduation: a buy leaves the pool at/above the graduation price (~$20k mcap). This flips
/// `graduated` permanently (one-way), or
/// 2. the launch window expiring (`block.timestamp >= windowEnd`), a safety valve so a token
/// that never reaches the threshold still opens up eventually.
///
/// @dev Uniswap v3 writes `slot0.sqrtPriceX96` BEFORE it transfers the output token, so inside `_update`
/// (from == pool) the pool price is already the post-swap price. The gate is evaluated against the
/// `graduated` flag captured before this transfer, so the trade that crosses the threshold must itself
/// be a relayer buy; everything after it is open.
contract GatedToken is ERC20 {
error NotLaunchpad();
error AlreadyInitialized();
error BuyLocked();
error MaxWalletExceeded();
event Graduated(uint160 sqrtPriceX96, uint64 timestamp);
uint256 public constant TOTAL_SUPPLY = 1_000_000_000e18;
IRelayRegistry public immutable registry;
address public immutable launchpad;
uint256 public immutable maxWallet;
address public pool; // canonical v3 pool; set once by the launchpad
address public deployer; // the launch creator: their own wallet may buy during the blink
uint64 public windowEnd; // fallback: buys open to everyone after this even if not graduated
bool public tokenIsToken0; // orientation of this token inside the pool
bool public graduated; // one-way flag: pool price reached the graduation threshold
uint160 public gradSqrtPriceX96; // sqrt price at which the token graduates
mapping(address => bool) public exempt; // max-wallet exemptions (launchpad, pool, routers)
bool public rescuing; // set by the launchpad only for the duration of an owner rescue (pool -> wallet)
// On-chain metadata (so the site needs no log history and explorers/aggregators can read it).
string public imageURI;
string public xUrl;
string public webUrl;
string public tgUrl;
string public bio;
constructor(
string memory name_,
string memory symbol_,
address _launchpad,
IRelayRegistry _registry,
uint16 maxWalletBps
) ERC20(name_, symbol_) {
launchpad = _launchpad;
registry = _registry;
maxWallet = (TOTAL_SUPPLY * maxWalletBps) / 10_000;
exempt[_launchpad] = true;
_mint(_launchpad, TOTAL_SUPPLY);
}
/// @notice Launchpad arms the gate (pool, window, graduation price) and seeds cap exemptions.
function initialize(
address _pool,
address _deployer,
uint64 _windowEnd,
bool _tokenIsToken0,
uint160 _gradSqrtPriceX96,
address[] memory exemptions
) external {
if (msg.sender != launchpad) revert NotLaunchpad();
if (pool != address(0)) revert AlreadyInitialized();
pool = _pool;
deployer = _deployer;
windowEnd = _windowEnd;
tokenIsToken0 = _tokenIsToken0;
gradSqrtPriceX96 = _gradSqrtPriceX96;
exempt[_pool] = true;
for (uint256 i; i < exemptions.length; i++) exempt[exemptions[i]] = true;
}
/// @notice Launchpad writes the launch metadata once (called in the same tx as `initialize`).
function setMetadata(
string calldata _imageURI,
string calldata _xUrl,
string calldata _webUrl,
string calldata _tgUrl,
string calldata _bio
) external {
if (msg.sender != launchpad) revert NotLaunchpad();
imageURI = _imageURI;
xUrl = _xUrl;
webUrl = _webUrl;
tgUrl = _tgUrl;
bio = _bio;
}
function setExempt(address a, bool b) external {
if (msg.sender != launchpad) revert NotLaunchpad();
exempt[a] = b;
}
/// @notice Launchpad toggles this around a rescue (pool -> wallet is not a buy) and around the atomic dev buy
/// inside launch() (the creator's opening buy is exempt from the gate and the max wallet). When it is
/// switched off the graduation threshold is re-checked, so a dev buy that crosses it graduates at once.
function setRescuing(bool b) external {
if (msg.sender != launchpad) revert NotLaunchpad();
rescuing = b;
if (!b && !graduated && pool != address(0)) _checkGraduation();
}
function _checkGraduation() internal {
(uint160 sqrtP,,,,,,) = IUniswapV3PoolSlot0(pool).slot0();
if (_pastThreshold(sqrtP)) {
graduated = true;
emit Graduated(sqrtP, uint64(block.timestamp));
}
}
/// @notice True while buys are restricted to relayer-originated transactions.
function blinking() public view returns (bool) {
return pool != address(0) && !graduated && block.timestamp < windowEnd;
}
/// @notice Whether the pool's current price is at/above the graduation threshold.
function atGraduationPrice() public view returns (bool) {
(uint160 sqrtP,,,,,,) = IUniswapV3PoolSlot0(pool).slot0();
return _pastThreshold(sqrtP);
}
/// @notice ERC-7572-style contract metadata as a data URI.
function contractURI() external view returns (string memory) {
bytes memory json = abi.encodePacked(
'{"name":"', _esc(name()), '","symbol":"', _esc(symbol()), '","description":"', _esc(bio),
'","image":"', _esc(imageURI), '","external_link":"', _esc(webUrl),
'","twitter":"', _esc(xUrl), '","telegram":"', _esc(tgUrl), '"}'
);
return string(abi.encodePacked("data:application/json;base64,", Base64.encode(json)));
}
function _pastThreshold(uint160 sqrtP) internal view returns (bool) {
// token0: price = token1/token0 = USDC per token, rises with sqrtP.
// token1: pool price = token per USDC, so the token's USD price rises as sqrtP FALLS.
return tokenIsToken0 ? sqrtP >= gradSqrtPriceX96 : sqrtP <= gradSqrtPriceX96;
}
function _update(address from, address to, uint256 value) internal override {
if (rescuing) {
super._update(from, to, value);
return;
}
bool fromPool = pool != address(0) && from == pool;
// fee collection by the launchpad is not a buy
if (
fromPool && to != launchpad && !graduated && block.timestamp < windowEnd && tx.origin != deployer
&& !registry.isRelayer(tx.origin)
) revert BuyLocked();
super._update(from, to, value);
if (to != address(0) && !exempt[to] && balanceOf(to) > maxWallet) revert MaxWalletExceeded();
if (fromPool && !graduated) _checkGraduation();
}
/// @dev Escape quotes/backslashes/control chars so user strings cannot break the JSON.
function _esc(string memory s) internal pure returns (string memory) {
bytes memory b = bytes(s);
uint256 extra;
for (uint256 i; i < b.length; i++) {
bytes1 c = b[i];
if (c == '"' || c == "\\") extra++;
else if (uint8(c) < 0x20) extra += 5;
}
if (extra == 0) return s;
bytes memory o = new bytes(b.length + extra);
uint256 j;
for (uint256 i; i < b.length; i++) {
bytes1 c = b[i];
if (c == '"' || c == "\\") {
o[j++] = "\\";
o[j++] = c;
} else if (uint8(c) < 0x20) {
o[j++] = "\\";
o[j++] = "u";
o[j++] = "0";
o[j++] = "0";
o[j++] = bytes1(uint8(c) >> 4 > 9 ? uint8(c) / 16 + 87 : uint8(c) / 16 + 48);
o[j++] = bytes1(uint8(c) & 0xf > 9 ? (uint8(c) & 0xf) + 87 : (uint8(c) & 0xf) + 48);
} else {
o[j++] = c;
}
}
return string(o);
}
}
src/Launchpad.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol"; // pure tick math, v3-compatible
import {GatedToken, IRelayRegistry} from "./GatedToken.sol";
import {FullMath} from "./FullMath.sol";
interface INonfungiblePositionManager {
function createAndInitializePoolIfNecessary(address token0, address token1, uint24 fee, uint160 sqrtPriceX96)
external
payable
returns (address pool);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
function mint(MintParams calldata params)
external
payable
returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
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
);
}
interface ISwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
}
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function approve(address, uint256) external returns (bool);
function transfer(address, uint256) external returns (bool);
function balanceOf(address) external view returns (uint256);
}
interface IAggregatorV3 {
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
/// @title Launchpad (alleyes, Ethereum)
/// @notice Fomo-exclusive launchpad on Uniswap V3 (1% tier), every token paired with ETH (WETH).
/// One tx: mint 1B supply, create + seed a single-sided full-range position at a $-denominated start
/// mcap (Chainlink ETH/USD read at launch), and arm the token's gate: buys are Fomo-only (relayer
/// `tx.origin`) until the pool reaches the graduation mcap or the launch window expires.
/// Creator fees (50% of the 1% LP fee) go to a fee recipient the creator picks (e.g. their Fomo
/// account address) and are paid in native ETH; the other 50% goes to the treasury.
/// The position NFT is held by this contract; the owner can `rescue` it (closes that market).
contract Launchpad {
error BadMcaps(); error BadWindowConfig(); error UnknownToken(); error ZeroAddress(); error WethPayFailed(); error PayFailed();
error NotOwner();
error NotDeployer();
error BadWindow();
error BadOracle();
event LaunchCreated(
address indexed token, address indexed deployer, address pool, uint256 tokenId, uint64 windowEnd
);
event LaunchMetadata(address indexed token, string imageURI, string xUrl, string webUrl, string tgUrl, string bio);
event DevBuy(address indexed token, address indexed deployer, uint256 ethIn, uint256 tokensOut);
event FeesClaimed(address indexed token, address indexed feeRecipient, uint256 creatorEth, uint256 treasuryEth, uint256 creatorTokens, uint256 treasuryTokens);
event FeeRecipientSet(address indexed token, address indexed feeRecipient);
event FomoProfileSet(address indexed token, string fomoProfile, string fomoPfp);
event Rescued(address indexed token, address indexed to, uint256 amount0, uint256 amount1);
uint24 public constant FEE = 10_000; // 1% tier
int24 public constant TICK_SPACING = 200;
uint16 public constant MAX_WALLET_BPS = 350; // 3.5%
uint256 public constant SUPPLY = 1_000_000_000e18;
INonfungiblePositionManager public immutable nfpm;
IWETH public immutable weth;
address public immutable swapRouter;
IRelayRegistry public immutable registry;
IAggregatorV3 public immutable ethUsd; // Chainlink, 8 decimals
uint256 public immutable startMcapUsd; // whole dollars
uint256 public immutable gradMcapUsd; // whole dollars
uint32 public immutable minWindow;
uint32 public immutable maxWindow;
address public owner;
address public treasury;
address[] public capExempt;
struct Launch {
address deployer;
address feeRecipient;
address pool;
uint256 tokenId;
bool exists;
string fomoProfile; // link to the Fomo profile that receives the creator fees (display only)
string fomoPfp; // that Fomo account's picture (small data: URI, display only)
}
mapping(address => Launch) public launches; // token => launch
address[] public allTokens;
struct LaunchParams {
string name;
string symbol;
uint32 windowDuration;
string imageURI;
string xUrl;
string webUrl;
string tgUrl;
string bio;
address feeRecipient; // where the creator's fee share goes (e.g. a Fomo account); 0 = msg.sender
string fomoProfile; // optional link to that Fomo profile (https://fomo.family/<handle>)
string fomoPfp; // optional picture of that Fomo account (data: URI, keep it small)
}
constructor(
INonfungiblePositionManager _nfpm,
IWETH _weth,
address _swapRouter,
IRelayRegistry _registry,
IAggregatorV3 _ethUsd,
address _owner,
address _treasury,
uint256 _startMcapUsd,
uint256 _gradMcapUsd,
uint32 _minWindow,
uint32 _maxWindow,
address[] memory _capExempt
) {
if (!(_startMcapUsd > 0 && _gradMcapUsd > _startMcapUsd)) revert BadMcaps();
if (!(_minWindow > 0 && _minWindow <= _maxWindow)) revert BadWindowConfig();
nfpm = _nfpm;
weth = _weth;
swapRouter = _swapRouter;
registry = _registry;
ethUsd = _ethUsd;
owner = _owner;
treasury = _treasury;
startMcapUsd = _startMcapUsd;
gradMcapUsd = _gradMcapUsd;
minWindow = _minWindow;
maxWindow = _maxWindow;
capExempt.push(_swapRouter);
for (uint256 i; i < _capExempt.length; i++) capExempt.push(_capExempt[i]);
}
receive() external payable {}
// ------------------------------------------------------------------ launch
/// @notice Create a token + pool. Send ETH along to make an atomic creator buy in the same tx.
function launch(LaunchParams calldata p) external payable returns (address token, address pool) {
if (p.windowDuration < minWindow || p.windowDuration > maxWindow) revert BadWindow();
GatedToken t = new GatedToken(p.name, p.symbol, address(this), registry, MAX_WALLET_BPS);
token = address(t);
uint64 windowEnd = uint64(block.timestamp) + p.windowDuration;
uint256 tokenId;
(pool, tokenId) = _createAndSeed(t, token, windowEnd);
t.setMetadata(p.imageURI, p.xUrl, p.webUrl, p.tgUrl, p.bio);
address feeTo = p.feeRecipient == address(0) ? msg.sender : p.feeRecipient;
launches[token] = Launch({
deployer: msg.sender, feeRecipient: feeTo, pool: pool, tokenId: tokenId, exists: true, fomoProfile: p.fomoProfile, fomoPfp: p.fomoPfp
});
allTokens.push(token);
emit LaunchCreated(token, msg.sender, pool, tokenId, windowEnd);
emit LaunchMetadata(token, p.imageURI, p.xUrl, p.webUrl, p.tgUrl, p.bio);
emit FeeRecipientSet(token, feeTo);
if (bytes(p.fomoProfile).length > 0 || bytes(p.fomoPfp).length > 0) emit FomoProfileSet(token, p.fomoProfile, p.fomoPfp);
if (msg.value > 0) {
// Atomic dev buy, exempt from the max wallet (and the gate): the token treats it like a rescue transfer.
GatedToken(token).setRescuing(true);
weth.deposit{value: msg.value}();
weth.approve(swapRouter, msg.value);
uint256 out = ISwapRouter(swapRouter).exactInputSingle(
ISwapRouter.ExactInputSingleParams({
tokenIn: address(weth),
tokenOut: token,
fee: FEE,
recipient: msg.sender,
amountIn: msg.value,
amountOutMinimum: 0,
sqrtPriceLimitX96: 0
})
);
emit DevBuy(token, msg.sender, msg.value, out);
GatedToken(token).setRescuing(false);
}
}
/// @dev Pool creation + single-sided mint. Start/graduation prices come from the ETH/USD oracle.
function _createAndSeed(GatedToken t, address token, uint64 windowEnd)
internal
returns (address pool, uint256 tokenId)
{
bool tokenIsToken0 = token < address(weth);
(address token0, address token1) = tokenIsToken0 ? (token, address(weth)) : (address(weth), token);
(uint160 startSqrt, uint160 gradSqrt, int24 startTick) = _prices(tokenIsToken0);
int24 tickLower = tokenIsToken0 ? startTick : TickMath.minUsableTick(TICK_SPACING);
int24 tickUpper = tokenIsToken0 ? TickMath.maxUsableTick(TICK_SPACING) : startTick;
pool = nfpm.createAndInitializePoolIfNecessary(token0, token1, FEE, startSqrt);
t.initialize(pool, msg.sender, windowEnd, tokenIsToken0, gradSqrt, capExempt);
t.approve(address(nfpm), SUPPLY);
(tokenId,,,) = nfpm.mint(
INonfungiblePositionManager.MintParams({
token0: token0,
token1: token1,
fee: FEE,
tickLower: tickLower,
tickUpper: tickUpper,
amount0Desired: tokenIsToken0 ? SUPPLY : 0,
amount1Desired: tokenIsToken0 ? 0 : SUPPLY,
amount0Min: 0,
amount1Min: 0,
recipient: address(this),
deadline: block.timestamp
})
);
}
/// @notice sqrt prices for the start (snapped to the tick grid so the position is exactly one-sided)
/// and the graduation mcap, for the given pool orientation, at the current ETH/USD price.
function _prices(bool tokenIsToken0) internal view returns (uint160 startSqrt, uint160 gradSqrt, int24 startTick) {
uint256 usd = ethPrice();
// WETH-per-token price for a given mcap, as sqrt(price) * 2^96, in the token0 orientation.
uint160 s0 = _sqrtPriceForMcap(startMcapUsd, usd);
uint160 g0 = _sqrtPriceForMcap(gradMcapUsd, usd);
if (tokenIsToken0) {
int24 raw = TickMath.getTickAtSqrtPrice(s0);
startTick = _floorToSpacing(raw); // slightly lower price than target, never higher
startSqrt = TickMath.getSqrtPriceAtTick(startTick);
gradSqrt = g0;
} else {
// pool price = token per WETH = 1/price -> sqrt = 2^192 / s0
uint160 s1 = uint160(FullMath.mulDiv(1 << 96, 1 << 96, s0));
uint160 g1 = uint160(FullMath.mulDiv(1 << 96, 1 << 96, g0));
int24 raw = TickMath.getTickAtSqrtPrice(s1);
startTick = _ceilToSpacing(raw); // higher pool tick = lower token price
startSqrt = TickMath.getSqrtPriceAtTick(startTick);
gradSqrt = g1;
}
}
/// @dev price (WETH wei per token wei) = mcapUsd / (ethUsd * 1e9); sqrt(price) * 2^96.
function _sqrtPriceForMcap(uint256 mcapUsd, uint256 ethUsd8) internal pure returns (uint160) {
// priceX192 = mcapUsd * 1e8 * 2^192 / (ethUsd8 * 1e9)
uint256 priceX192 = FullMath.mulDiv(mcapUsd * 1e8, 1 << 192, ethUsd8 * 1e9);
return uint160(_sqrt(priceX192));
}
function _floorToSpacing(int24 t) internal pure returns (int24) {
int24 r = t / TICK_SPACING * TICK_SPACING;
if (r > t) r -= TICK_SPACING;
return r;
}
function _ceilToSpacing(int24 t) internal pure returns (int24) {
int24 r = t / TICK_SPACING * TICK_SPACING;
if (r < t) r += TICK_SPACING;
return r;
}
function _sqrt(uint256 x) internal pure returns (uint256 y) {
if (x == 0) return 0;
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
/// @notice Chainlink ETH/USD, 8 decimals. Reverts if stale (> 24h) or non-positive.
function ethPrice() public view returns (uint256) {
(, int256 answer,, uint256 updatedAt,) = ethUsd.latestRoundData();
if (answer <= 0 || block.timestamp - updatedAt > 1 days) revert BadOracle();
return uint256(answer);
}
// ------------------------------------------------------------------ fees
/// @notice Permissionless: sweep a token's accrued LP fees. ETH side is unwrapped and paid natively
/// (50% fee recipient / 50% treasury); token side is split the same way (never sold).
function claim(address token) external returns (uint256 ethAmt, uint256 tokAmt) {
Launch memory l = launches[token];
if (!(l.exists)) revert UnknownToken();
(uint256 a0, uint256 a1) = nfpm.collect(
INonfungiblePositionManager.CollectParams({
tokenId: l.tokenId,
recipient: address(this),
amount0Max: type(uint128).max,
amount1Max: type(uint128).max
})
);
bool tokenIsToken0 = token < address(weth);
ethAmt = tokenIsToken0 ? a1 : a0;
tokAmt = tokenIsToken0 ? a0 : a1;
uint256 cb = ethAmt / 2;
uint256 ct = tokAmt / 2;
if (ethAmt > 0) {
weth.withdraw(ethAmt);
_payEth(l.feeRecipient, cb);
_payEth(treasury, ethAmt - cb);
}
if (tokAmt > 0) {
_payToken(token, l.feeRecipient, ct);
_payToken(token, treasury, tokAmt - ct);
}
emit FeesClaimed(token, l.feeRecipient, cb, ethAmt - cb, ct, tokAmt - ct);
}
/// @notice Creator: redirect future fee payouts (e.g. to a Fomo account address).
function setFeeRecipient(address token, address to) external {
Launch storage l = launches[token];
if (!l.exists || msg.sender != l.deployer) revert NotDeployer();
if (!(to != address(0))) revert ZeroAddress();
l.feeRecipient = to;
emit FeeRecipientSet(token, to);
}
/// @notice Creator: set/replace the Fomo profile link shown next to the fee recipient.
function setFomoProfile(address token, string calldata profile, string calldata pfp) external {
Launch storage l = launches[token];
if (!l.exists || msg.sender != l.deployer) revert NotDeployer();
l.fomoProfile = profile;
l.fomoPfp = pfp;
emit FomoProfileSet(token, profile, pfp);
}
function _payEth(address to, uint256 amount) internal {
if (amount == 0) return;
(bool ok,) = to.call{value: amount, gas: 100_000}("");
if (!ok) {
// recipient cannot take native ETH: hand over WETH instead
weth.deposit{value: amount}();
if (!(weth.transfer(to, amount))) revert WethPayFailed();
}
}
function _payToken(address erc20, address to, uint256 amount) internal {
if (amount == 0) return;
(bool ok, bytes memory ret) = erc20.call(abi.encodeWithSelector(0xa9059cbb, to, amount)); // transfer
if (!(ok && (ret.length == 0 || abi.decode(ret, (bool))))) revert PayFailed();
}
// ------------------------------------------------------------------ owner
/// @notice Owner: pull ALL liquidity + fees of a launch's position to `to` (WETH + token). Closes it.
function rescue(address token, address to, uint256 amount0Min, uint256 amount1Min)
external
returns (uint256 amount0, uint256 amount1)
{
if (msg.sender != owner) revert NotOwner();
Launch memory l = launches[token];
if (!(l.exists)) revert UnknownToken();
GatedToken(token).setRescuing(true);
(,,,,,,, uint128 liq,,,,) = nfpm.positions(l.tokenId);
if (liq > 0) {
nfpm.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: l.tokenId,
liquidity: liq,
amount0Min: amount0Min,
amount1Min: amount1Min,
deadline: block.timestamp
})
);
}
(amount0, amount1) = nfpm.collect(
INonfungiblePositionManager.CollectParams({
tokenId: l.tokenId,
recipient: to,
amount0Max: type(uint128).max,
amount1Max: type(uint128).max
})
);
GatedToken(token).setRescuing(false);
emit Rescued(token, to, amount0, amount1);
}
function exemptToken(address token, address a, bool b) external {
if (msg.sender != owner) revert NotOwner();
GatedToken(token).setExempt(a, b);
}
function addCapExempt(address a) external {
if (msg.sender != owner) revert NotOwner();
capExempt.push(a);
}
function setTreasury(address _t) external {
if (msg.sender != owner) revert NotOwner();
treasury = _t;
}
function transferOwnership(address _o) external {
if (msg.sender != owner) revert NotOwner();
owner = _o;
}
// ------------------------------------------------------------------ views
function totalLaunches() external view returns (uint256) {
return allTokens.length;
}
function tokensPage(uint256 offset, uint256 limit) external view returns (address[] memory out) {
uint256 n = allTokens.length;
if (offset >= n) return out;
uint256 end = offset + limit > n ? n : offset + limit;
out = new address[](end - offset);
for (uint256 i = offset; i < end; i++) out[i - offset] = allTokens[i];
}
function capExemptList() external view returns (address[] memory) {
return capExempt;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin/",
"@uniswap/v4-core/src/=lib/v4-core/",
"forge-std/=lib/forge-std/src/",
"openzeppelin/=lib/openzeppelin/",
"v4-core/=lib/v4-core/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.