Verified contractPartialMIT
D17Token
Address0x7b2260c0dad9e44aa396a7558db5f97bb2f1069f
- Balance
0 ETH
- Transactions
12
- Compiler
solc 0.8.24
- Same code
4 more contracts
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- shanghai
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,579,652
- Creation transaction
- 0xe5894bf129…581b9b258a
- Main copy (most transactions)
- 0x27451088…056bcba8
17 files
- project/contracts/D17Token.solmain10.57 KB
- project/contracts/D17Factory.sol12.81 KB
- project/contracts/D17Launch.sol32.88 KB
- project/contracts/D17LaunchFactory.sol5.22 KB
- project/contracts/D17LiquidityVault.sol8.85 KB
- project/contracts/D17LiquidityVaultFactory.sol1.98 KB
- project/contracts/D17Locker.sol13.07 KB
- project/contracts/D17LockerFactory.sol1.08 KB
- project/contracts/D17TokenFactory.sol1.88 KB
- project/contracts/interfaces/ID17.sol5.26 KB
- project/contracts/interfaces/ID17LaunchFactory.sol1.05 KB
- project/contracts/lib/D17SafeTransfer.sol1.33 KB
- project/contracts/test/TestERC20.sol2.25 KB
- project/contracts/test/TestV2Factory.sol1.03 KB
- project/contracts/test/TestV2Pair.sol3.47 KB
- project/contracts/test/TestV2Router.sol4.17 KB
- project/contracts/test/TestWETH.sol784 B
project/contracts/D17Token.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ID17LaunchFactory} from "./interfaces/ID17LaunchFactory.sol";
interface ID17TokenGateV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address);
}
interface ID17TokenGateLaunch {
function tradingOpen() external view returns (bool);
}
contract D17Token {
bytes32 public constant D17_TOKEN_ID = keccak256("D17_TOKEN_V14_1_REFUND_SCHEDULE_BURN_GATE");
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint256 public immutable maxSupply;
uint256 public totalSupply;
address public owner;
address public launch;
address public d17Factory;
address public weth;
address public routerFactory;
address public liquidityVault;
uint256 public tradingOpenAt;
bool public mintingClosed;
bool public tradingGateConfigured;
bool public metadataConfigured;
string public description;
string public logoSvgUri;
bytes32 public metadataHash;
struct MetadataLink {
string linkType;
string url;
}
MetadataLink[] private metadataLinks;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event MintingClosed();
event TradingGateConfigured(
address indexed launch,
address indexed d17Factory,
address indexed weth,
address routerFactory,
address liquidityVault,
uint256 tradingOpenAt
);
event TokenMetadataConfigured(
bytes32 indexed metadataHash,
string description,
string logoSvgUri,
string[] linkTypes,
string[] linkUrls
);
event ContractURIUpdated();
modifier onlyOwner() {
require(msg.sender == owner, "NOT_OWNER");
_;
}
constructor(address owner_, string memory name_, string memory symbol_, uint256 maxSupply_) {
require(owner_ != address(0), "OWNER_ZERO");
require(bytes(name_).length > 0 && bytes(name_).length <= 64, "NAME");
require(bytes(symbol_).length > 0 && bytes(symbol_).length <= 16, "SYMBOL");
_validateJsonSafe(name_, "NAME_JSON");
_validateJsonSafe(symbol_, "SYMBOL_JSON");
require(maxSupply_ > 0, "SUPPLY_ZERO");
owner = owner_;
name = name_;
symbol = symbol_;
maxSupply = maxSupply_;
emit OwnershipTransferred(address(0), owner_);
}
function configureTradingGate(
address launch_,
address d17Factory_,
address weth_,
address routerFactory_,
address liquidityVault_,
uint256 tradingOpenAt_
) external onlyOwner {
require(!tradingGateConfigured, "TRADING_GATE_CONFIGURED");
require(launch_ != address(0), "LAUNCH_ZERO");
require(d17Factory_ != address(0), "FACTORY_ZERO");
require(weth_ != address(0), "WETH_ZERO");
require(routerFactory_ != address(0), "ROUTER_FACTORY_ZERO");
require(liquidityVault_ != address(0), "VAULT_ZERO");
require(launch_.code.length > 0, "LAUNCH_NO_CODE");
require(d17Factory_.code.length > 0, "FACTORY_NO_CODE");
require(weth_.code.length > 0, "WETH_NO_CODE");
require(routerFactory_.code.length > 0, "ROUTER_FACTORY_NO_CODE");
require(liquidityVault_.code.length > 0, "VAULT_NO_CODE");
require(tradingOpenAt_ > block.timestamp, "TRADING_OPEN_NOW");
launch = launch_;
d17Factory = d17Factory_;
weth = weth_;
routerFactory = routerFactory_;
liquidityVault = liquidityVault_;
tradingOpenAt = tradingOpenAt_;
tradingGateConfigured = true;
emit TradingGateConfigured(launch_, d17Factory_, weth_, routerFactory_, liquidityVault_, tradingOpenAt_);
}
function configureMetadata(
string calldata description_,
string calldata logoSvgUri_,
ID17LaunchFactory.Link[] calldata links_
) external onlyOwner {
require(!metadataConfigured, "METADATA_CONFIGURED");
description = description_;
logoSvgUri = logoSvgUri_;
for (uint256 i; i < links_.length; i++) {
metadataLinks.push(MetadataLink({linkType: links_[i].linkType, url: links_[i].url}));
}
metadataHash = keccak256(abi.encode(name, symbol, description_, logoSvgUri_, links_));
metadataConfigured = true;
emit TokenMetadataConfigured(metadataHash, description_, logoSvgUri_, _metadataLinkTypes(), _metadataLinkUrls());
emit ContractURIUpdated();
}
function tradingOpen() external view returns (bool) {
return _launchTradingOpen();
}
function linkCount() external view returns (uint256) {
return metadataLinks.length;
}
function links(uint256 index) external view returns (string memory linkType, string memory url) {
require(index < metadataLinks.length, "LINK_INDEX");
MetadataLink storage link = metadataLinks[index];
return (link.linkType, link.url);
}
function contractURI() external view returns (string memory) {
return string(abi.encodePacked("data:application/json;charset=utf-8,", _contractMetadataJson()));
}
function canonicalPair() public view returns (address) {
if (!tradingGateConfigured) return address(0);
return ID17TokenGateV2Factory(routerFactory).getPair(address(this), weth);
}
function transfer(address to, uint256 amount) external returns (bool) {
_transfer(msg.sender, to, amount);
return true;
}
function approve(address spender, uint256 amount) external returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount) external returns (bool) {
uint256 allowed = allowance[from][msg.sender];
if (allowed != type(uint256).max) {
require(allowed >= amount, "ALLOWANCE");
unchecked {
allowance[from][msg.sender] = allowed - amount;
}
}
_transfer(from, to, amount);
return true;
}
function burn(uint256 amount) external {
// Pre-open burns are restricted to the launch (unsold sale-token burn at
// finalization). The launch factory mints the manual allocation before trading
// opens; without this gate the creator could change the visible supply/tokenomics
// before the launch outcome is known. After trading opens any holder may burn.
require(msg.sender == launch || _launchTradingOpen(), "BURN_BEFORE_OPEN");
require(balanceOf[msg.sender] >= amount, "BALANCE");
unchecked {
balanceOf[msg.sender] -= amount;
totalSupply -= amount;
}
emit Transfer(msg.sender, address(0), amount);
}
function mint(address to, uint256 amount) external onlyOwner {
require(!mintingClosed, "MINTING_CLOSED");
require(totalSupply + amount <= maxSupply, "CAP");
require(to != address(0), "TO_ZERO");
totalSupply += amount;
balanceOf[to] += amount;
emit Transfer(address(0), to, amount);
}
function closeMinting() external onlyOwner {
require(!mintingClosed, "MINTING_CLOSED");
mintingClosed = true;
emit MintingClosed();
}
function renounceOwnership() external onlyOwner {
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
function _transfer(address from, address to, uint256 amount) internal {
require(to != address(0), "TO_ZERO");
require(_transferAllowedBeforeOpen(from, to), "TRADING_CLOSED");
require(balanceOf[from] >= amount, "BALANCE");
if (amount == 0) {
emit Transfer(from, to, 0);
return;
}
unchecked {
balanceOf[from] -= amount;
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
}
function _transferAllowedBeforeOpen(address from, address to) private view returns (bool) {
if (!tradingGateConfigured) return false;
if (from == launch) return true;
address pair = canonicalPair();
if (pair != address(0) && to == pair && from == liquidityVault) return true;
if (_launchTradingOpen()) return true;
return false;
}
function _launchTradingOpen() private view returns (bool) {
if (!tradingGateConfigured) return false;
try ID17TokenGateLaunch(launch).tradingOpen() returns (bool open) {
return open;
} catch {
return false;
}
}
function _contractMetadataJson() private view returns (bytes memory) {
bytes memory json = abi.encodePacked(
'{"name":"',
name,
'","symbol":"',
symbol,
'","description":"',
description,
'","image":"',
logoSvgUri,
'","links":['
);
for (uint256 i; i < metadataLinks.length; i++) {
MetadataLink storage link = metadataLinks[i];
if (i > 0) json = abi.encodePacked(json, ",");
json = abi.encodePacked(json, '{"type":"', link.linkType, '","url":"', link.url, '"}');
}
return abi.encodePacked(json, "]}");
}
function _metadataLinkTypes() private view returns (string[] memory linkTypes) {
linkTypes = new string[](metadataLinks.length);
for (uint256 i; i < metadataLinks.length; i++) {
linkTypes[i] = metadataLinks[i].linkType;
}
}
function _metadataLinkUrls() private view returns (string[] memory linkUrls) {
linkUrls = new string[](metadataLinks.length);
for (uint256 i; i < metadataLinks.length; i++) {
linkUrls[i] = metadataLinks[i].url;
}
}
function _validateJsonSafe(string memory value, string memory reason) private pure {
bytes memory data = bytes(value);
for (uint256 i; i < data.length; i++) {
bytes1 char = data[i];
if (char == 0x22 || char == 0x5c || char < 0x20) revert(reason);
}
}
}
project/contracts/D17Factory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ID17Launch} from "./interfaces/ID17.sol";
import {ID17LaunchFactory} from "./interfaces/ID17LaunchFactory.sol";
interface IV2RouterView {
function factory() external view returns (address);
}
contract D17Factory {
bytes32 public constant D17_FACTORY_ID = keccak256("D17_FACTORY_V14_1_REFUND_SCHEDULE_BURN_GATE");
uint16 public constant BPS = 10_000;
uint16 public constant MAX_TREASURY_BPS = 2_000;
uint16 public constant MAX_MANUAL_DISTRIBUTION_BPS = 1_000;
uint16 public constant MAX_REFUND_PENALTY_BPS = 5_000;
uint8 public constant ROUND_COUNT = 5;
uint256 public constant MAX_DESCRIPTION_BYTES = 512;
uint256 public constant MAX_LINKS = 8;
uint256 public constant MAX_LINK_TYPE_BYTES = 32;
uint256 public constant MAX_LINK_URL_BYTES = 128;
uint256 public constant MAX_LOGO_SVG_URI_BYTES = 8_192;
string public constant LOGO_SVG_BASE64_PREFIX = "data:image/svg+xml;base64,";
uint256 public constant MIN_COMMIT_WETH = 1e15;
uint256 public constant MIN_LP_TOKENS = 1e18;
uint256 public constant MIN_ROUND_ALLOCATION_TOKENS = 1e18;
uint256 public constant MIN_ANCHOR_PRICE_WAD = 1e6;
uint32 public constant MIN_ROUND_SECONDS = 60;
uint32 public constant MAX_ROUND_SECONDS = 90 days;
uint32 public constant MAX_REFUND_SECONDS = 30 days;
uint32 public constant MAX_SETTLEMENT_SECONDS = 30 days;
uint64 public constant MAX_START_DELAY = 365 days;
address public owner;
address public immutable weth;
address public immutable router;
address public launchFactory;
address public lockerFactory;
bool public launchFactoryPinned;
bool public lockerFactoryPinned;
struct LaunchRecord {
bool canonical;
address creator;
address token;
address liquidityVault;
bytes32 rulesHash;
}
mapping(address => LaunchRecord) public launches;
mapping(address => bool) public isLocker;
mapping(address => address[]) private lockersByOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event LaunchCreated(
address indexed creator,
address indexed launch,
address indexed token,
address liquidityVault,
bytes32 rulesHash
);
event LaunchMetadataPublished(
address indexed launch,
bytes32 indexed metadataHash,
string description,
string logoSvgUri,
string[] linkTypes,
string[] linkUrls
);
event ManualDistributionConfigured(address indexed launch, address indexed recipient, uint256 amount);
event LockerRegistered(address indexed owner, address indexed locker, address indexed manager);
event LaunchFactoryPinned(address indexed launchFactory);
event LockerFactoryPinned(address indexed lockerFactory);
modifier onlyOwner() {
require(msg.sender == owner, "NOT_OWNER");
_;
}
constructor(address owner_, address weth_, address router_) {
require(owner_ != address(0), "OWNER_ZERO");
require(weth_ != address(0), "WETH_ZERO");
require(router_ != address(0), "ROUTER_ZERO");
require(weth_.code.length > 0, "WETH_NO_CODE");
require(router_.code.length > 0, "ROUTER_NO_CODE");
require(IV2RouterView(router_).factory() != address(0), "ROUTER_FACTORY_ZERO");
owner = owner_;
weth = weth_;
router = router_;
emit OwnershipTransferred(address(0), owner_);
}
function registerLockerFor(address lockerOwner, address locker) external {
require(lockerFactoryPinned && msg.sender == lockerFactory, "NOT_LOCKER_FACTORY");
require(lockerOwner != address(0), "LOCKER_OWNER_ZERO");
require(locker != address(0), "LOCKER_ZERO");
require(locker.code.length > 0, "LOCKER_NO_CODE");
require(!isLocker[locker], "LOCKER_REGISTERED");
isLocker[locker] = true;
lockersByOwner[lockerOwner].push(locker);
emit LockerRegistered(lockerOwner, locker, msg.sender);
}
function pinLockerFactory(address lockerFactory_) external onlyOwner {
require(!lockerFactoryPinned, "LOCKER_FACTORY_PINNED");
require(lockerFactory_ != address(0), "LOCKER_FACTORY_ZERO");
require(lockerFactory_.code.length > 0, "LOCKER_FACTORY_NO_CODE");
lockerFactory = lockerFactory_;
lockerFactoryPinned = true;
emit LockerFactoryPinned(lockerFactory_);
}
function pinLaunchFactory(address launchFactory_) external onlyOwner {
require(!launchFactoryPinned, "LAUNCH_FACTORY_PINNED");
require(launchFactory_ != address(0), "LAUNCH_FACTORY_ZERO");
require(launchFactory_.code.length > 0, "LAUNCH_FACTORY_NO_CODE");
launchFactory = launchFactory_;
launchFactoryPinned = true;
emit LaunchFactoryPinned(launchFactory_);
}
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0), "OWNER_ZERO");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership() external onlyOwner {
require(launchFactoryPinned, "LAUNCH_FACTORY_UNLOCKED");
require(lockerFactoryPinned, "LOCKER_FACTORY_UNLOCKED");
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
function lockersOfOwner(address lockerOwner) external view returns (address[] memory) {
return lockersByOwner[lockerOwner];
}
function createLaunch(ID17LaunchFactory.LaunchConfig calldata config)
external
returns (address token, address launch, address liquidityVault)
{
require(launchFactoryPinned, "LAUNCH_FACTORY_UNLOCKED");
require(lockerFactoryPinned, "LOCKER_FACTORY_UNLOCKED");
_validateConfig(config);
(token, launch, liquidityVault) = ID17LaunchFactory(launchFactory).deployLaunch(config, msg.sender);
bytes32 rules = ID17Launch(launch).rulesHash();
launches[launch] = LaunchRecord({
canonical: true,
creator: msg.sender,
token: token,
liquidityVault: liquidityVault,
rulesHash: rules
});
(string[] memory linkTypes, string[] memory linkUrls) = _metadataLinkArrays(config.links);
emit LaunchCreated(msg.sender, launch, token, liquidityVault, rules);
emit ManualDistributionConfigured(launch, msg.sender, config.manualDistributionTokens);
emit LaunchMetadataPublished(
launch,
ID17Launch(launch).metadataHash(),
config.description,
config.logoSvgUri,
linkTypes,
linkUrls
);
}
function isCanonicalLaunch(address launch, bytes32 rulesHash) external view returns (bool) {
LaunchRecord storage record = launches[launch];
return record.canonical && record.rulesHash == rulesHash;
}
function _validateConfig(ID17LaunchFactory.LaunchConfig calldata config) internal view {
require(bytes(config.tokenName).length > 0 && bytes(config.tokenName).length <= 64, "TOKEN_NAME");
require(bytes(config.tokenSymbol).length > 0 && bytes(config.tokenSymbol).length <= 16, "TOKEN_SYMBOL");
_validateJsonSafe(config.tokenName, "TOKEN_NAME_JSON");
_validateJsonSafe(config.tokenSymbol, "TOKEN_SYMBOL_JSON");
_validateMetadata(config);
require(config.tokenSupply > 0, "SUPPLY_ZERO");
require(config.saleTokens > 0, "SALE_ZERO");
require(config.lpTokens >= MIN_LP_TOKENS, "LP_TOO_LOW");
require(
config.saleTokens + config.lpTokens + config.manualDistributionTokens + config.deadTokens
== config.tokenSupply,
"SUPPLY_SPLIT"
);
require(
config.manualDistributionTokens * BPS <= config.tokenSupply * MAX_MANUAL_DISTRIBUTION_BPS,
"MANUAL_ABOVE_CAP"
);
if (config.deadTokens > 0) {
require(config.deadRecipient == 0x000000000000000000000000000000000000dEaD, "DEAD_RECIPIENT");
}
require(config.treasury != address(0), "TREASURY_ZERO");
require(config.startTime >= block.timestamp, "START_PAST");
require(config.startTime <= block.timestamp + MAX_START_DELAY, "START_TOO_FAR");
require(config.refundSeconds > 0 && config.refundSeconds <= MAX_REFUND_SECONDS, "REFUND_SECONDS");
require(config.settlementSeconds > 0 && config.settlementSeconds <= MAX_SETTLEMENT_SECONDS, "SETTLEMENT_SECONDS");
require(config.minCommitWeth >= MIN_COMMIT_WETH, "MIN_COMMIT_TOO_LOW");
require(config.minPhase1Weth >= config.minCommitWeth, "MIN_PHASE1_WETH");
require(config.minAnchorPriceWad >= MIN_ANCHOR_PRICE_WAD, "MIN_ANCHOR_PRICE_TOO_LOW");
require(config.treasuryBps <= MAX_TREASURY_BPS, "TREASURY_BPS");
require(config.refundPenaltyBps <= MAX_REFUND_PENALTY_BPS, "REFUND_PENALTY_BPS");
uint256 shareTotal;
for (uint256 i; i < ROUND_COUNT; i++) {
require(config.roundSeconds[i] >= MIN_ROUND_SECONDS && config.roundSeconds[i] <= MAX_ROUND_SECONDS, "ROUND_SECONDS");
require(config.roundSharesBps[i] > 0, "ROUND_SHARE_ZERO");
require(
config.saleTokens * config.roundSharesBps[i] / BPS >= MIN_ROUND_ALLOCATION_TOKENS,
"ROUND_ALLOCATION_TOO_LOW"
);
shareTotal += config.roundSharesBps[i];
}
require(shareTotal == BPS, "ROUND_SHARE_TOTAL");
}
function _validateMetadata(ID17LaunchFactory.LaunchConfig calldata config) internal pure {
require(bytes(config.description).length <= MAX_DESCRIPTION_BYTES, "DESCRIPTION_BYTES");
_validateJsonSafe(config.description, "DESCRIPTION_JSON");
require(config.links.length <= MAX_LINKS, "LINKS");
for (uint256 i; i < config.links.length; i++) {
_validateLinkType(config.links[i].linkType);
_validateLinkUrl(config.links[i].url);
}
bytes calldata logo = bytes(config.logoSvgUri);
require(logo.length <= MAX_LOGO_SVG_URI_BYTES, "LOGO_BYTES");
if (logo.length > 0) {
bytes memory prefix = bytes(LOGO_SVG_BASE64_PREFIX);
require(_startsWith(config.logoSvgUri, prefix), "LOGO_PREFIX");
require(logo.length > prefix.length, "LOGO_EMPTY");
for (uint256 i = prefix.length; i < logo.length; i++) {
require(_isBase64Byte(logo[i]), "LOGO_BASE64");
}
}
}
function _validateLinkType(string calldata value) internal pure {
bytes calldata data = bytes(value);
require(data.length > 0 && data.length <= MAX_LINK_TYPE_BYTES, "LINK_TYPE");
for (uint256 i; i < data.length; i++) {
bytes1 char = data[i];
bool ok = (char >= 0x61 && char <= 0x7a) || (char >= 0x30 && char <= 0x39) || char == 0x2d;
require(ok, "LINK_TYPE_CHARS");
}
}
function _validateLinkUrl(string calldata value) internal pure {
bytes calldata data = bytes(value);
require(data.length > 0 && data.length <= MAX_LINK_URL_BYTES, "LINK_URL");
require(_startsWith(value, bytes("https://")), "LINK_URL_SCHEME");
_validateJsonSafe(value, "LINK_URL_JSON");
}
function _validateJsonSafe(string calldata value, string memory reason) internal pure {
bytes calldata data = bytes(value);
for (uint256 i; i < data.length; i++) {
bytes1 char = data[i];
if (char == 0x22 || char == 0x5c || char < 0x20) revert(reason);
}
}
function _startsWith(string calldata value, bytes memory prefix) internal pure returns (bool) {
bytes calldata data = bytes(value);
if (data.length < prefix.length) return false;
for (uint256 i; i < prefix.length; i++) {
if (data[i] != prefix[i]) return false;
}
return true;
}
function _isBase64Byte(bytes1 char) internal pure returns (bool) {
return (char >= 0x41 && char <= 0x5a)
|| (char >= 0x61 && char <= 0x7a)
|| (char >= 0x30 && char <= 0x39)
|| char == 0x2b
|| char == 0x2f
|| char == 0x3d;
}
function _metadataLinkArrays(ID17LaunchFactory.Link[] calldata links)
internal
pure
returns (string[] memory linkTypes, string[] memory linkUrls)
{
linkTypes = new string[](links.length);
linkUrls = new string[](links.length);
for (uint256 i; i < links.length; i++) {
linkTypes[i] = links[i].linkType;
linkUrls[i] = links[i].url;
}
}
}
project/contracts/D17Launch.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {D17SafeTransfer} from "./lib/D17SafeTransfer.sol";
import {ID17FactoryView} from "./interfaces/ID17.sol";
contract D17Launch {
using D17SafeTransfer for address;
bytes32 public constant D17_LAUNCH_ID = keccak256("D17_LAUNCH_V14_1_REFUND_SCHEDULE_BURN_GATE");
uint8 public constant ROUND_COUNT = 5;
uint8 public constant FINAL_ROUND = 4;
uint8 public constant REFUND_STAGE_COUNT = 4;
// First N contract rounds refund without penalty; private to stay inside the
// D17LaunchFactory code-size headroom (policy is fixed per launch version ID).
uint8 private constant FREE_REFUND_ROUNDS = 2;
uint8 public constant NO_ROUND = type(uint8).max;
uint8 public constant PHASE_NOT_STARTED = 0;
uint8 public constant PHASE_ROUND_OPEN = 1;
uint8 public constant PHASE_REFUND_OPEN = 2;
uint8 public constant PHASE_READY_TO_FINALIZE = 3;
uint8 public constant PHASE_SETTLEMENT_OPEN = 4;
uint8 public constant PHASE_POOL_READY = 5;
uint8 public constant PHASE_TRADING_OPEN = 6;
uint8 public constant PHASE_FAILED = 7;
uint256 public constant BPS = 10_000;
uint256 public constant MIN_COMMIT_WETH = 1e15;
uint256 public constant MIN_LP_TOKENS = 1e18;
uint256 public constant MIN_ROUND_ALLOCATION_TOKENS = 1e18;
uint256 public constant MIN_ANCHOR_PRICE_WAD = 1e6;
uint256 private constant WAD = 1e18;
address public constant CANONICAL_DEAD_RECIPIENT = 0x000000000000000000000000000000000000dEaD;
address public immutable factory;
address public immutable vaultConfigurator;
address public immutable token;
address public immutable weth;
address public immutable treasury;
uint64 public immutable startTime;
uint32 public immutable refundSeconds;
uint32 public immutable settlementSeconds;
uint256 public immutable tradingOpenAt;
uint256 public immutable minCommitWeth;
uint256 public immutable minPhase1Weth;
uint256 public immutable minAnchorPriceWad;
uint16 public immutable treasuryBps;
uint16 public immutable refundPenaltyBps;
uint256 public immutable saleTokens;
uint256 public immutable lpTokens;
uint256 public immutable deadTokens;
address public immutable deadRecipient;
uint256 public immutable manualDistributionTokens;
address public immutable manualDistributionRecipient;
bool public immutable burnUnsoldSaleTokens;
bytes32 public immutable metadataHash;
address public liquidityVault;
bool public liquidityPoolCreated;
bool public vaultLiquidityClaimed;
address public officialPair;
uint256 public settledLiquidityWeth;
uint256 public finalCommittedWeth;
uint256 public settledCommittedWeth;
uint256 public poolSettledLiquidityWeth;
uint256 public poolSettledCommittedWeth;
uint256 public lateSettledCommittedWeth;
uint256 public lateSettledLiquidityWeth;
uint256 public lateLpTokensReleased;
uint256 public vaultLiquidityTokensClaimed;
uint256 public officialTokenUsedForLp;
uint256 public officialWethUsedForLp;
uint256 public officialLpMinted;
uint256 public poolCreatedAt;
uint32[5] public roundSeconds;
uint16[5] public roundSharesBps;
uint256[5] public roundRaised;
uint256 public retainedPenaltyWeth;
uint256 public penaltyWethPaid;
uint256 public treasuryWethPaid;
uint256 public unsoldSaleTokensSettled;
uint256 public finalRoundTokenPool;
bool public unsoldSaleTokensBurned;
uint256 public finalizedAt;
bool public finalized;
uint256 private entered = 1;
struct Position {
bool finalSaleTokensClaimed;
bool liquidityClaimed;
uint256 refundWeth;
uint256 penaltyWeth;
uint256[5] paid;
bool[5] refunded;
}
mapping(address => Position) private positions;
event LiquidityVaultConfigured(address indexed liquidityVault);
event RoundCommitted(address indexed locker, uint8 indexed round, uint256 amount);
event RoundRefunded(address indexed locker, uint8 indexed refundRound, uint256 refundWeth, uint256 penaltyWeth);
event LaunchFailedRefunded(address indexed locker, uint256 refundWeth);
event VaultSettlementClaimed(
address indexed locker,
uint256 saleTokens,
uint256 wethForVault,
uint256 treasuryWeth,
uint256 grossCommittedWeth
);
event LateVaultSettlementClaimed(
address indexed locker,
uint256 saleTokens,
uint256 wethForVault,
uint256 treasuryWeth,
uint256 lateLpTokens,
uint256 grossCommittedWeth
);
event Finalized(uint256 finalizedAt);
event VaultLiquidityTokensClaimed(
address indexed liquidityVault,
uint256 liquidityTokens,
uint256 wethForPool
);
event LiquidityPoolCreated(
address indexed liquidityVault,
address indexed pair,
uint256 tokenUsed,
uint256 wethUsed,
uint256 lpMinted
);
event UnsoldSaleTokensPaid(address indexed recipient, uint256 amount);
event UnsoldSaleTokensBurned(uint256 amount);
event UnexpectedEthSwept(address indexed recipient, uint256 amount);
modifier onlyLocker() {
require(ID17FactoryView(factory).isLocker(msg.sender), "NOT_D17_LOCKER");
_;
}
modifier onlyVault() {
require(msg.sender == liquidityVault && liquidityVault != address(0), "NOT_LIQUIDITY_VAULT");
_;
}
modifier nonReentrant() {
require(entered == 1, "REENTRANT");
entered = 2;
_;
entered = 1;
}
constructor(
address factory_,
address vaultConfigurator_,
address token_,
address weth_,
address treasury_,
bytes32 metadataHash_,
uint64 startTime_,
uint32[5] memory roundSeconds_,
uint32 refundSeconds_,
uint32 settlementSeconds_,
uint256 minCommitWeth_,
uint256 minPhase1Weth_,
uint256 minAnchorPriceWad_,
uint16[5] memory roundSharesBps_,
uint16 treasuryBps_,
uint16 refundPenaltyBps_,
uint256 saleTokens_,
uint256 lpTokens_,
uint256 deadTokens_,
address deadRecipient_,
uint256 manualDistributionTokens_,
address manualDistributionRecipient_,
bool burnUnsoldSaleTokens_
) {
require(factory_ != address(0), "FACTORY_ZERO");
require(vaultConfigurator_ != address(0), "VAULT_CONFIG_ZERO");
require(token_ != address(0), "TOKEN_ZERO");
require(weth_ != address(0), "WETH_ZERO");
require(treasury_ != address(0), "TREASURY_ZERO");
require(startTime_ >= block.timestamp, "START_PAST");
require(refundSeconds_ > 0, "REFUND_SECONDS_ZERO");
require(settlementSeconds_ > 0, "SETTLEMENT_SECONDS_ZERO");
require(minCommitWeth_ >= MIN_COMMIT_WETH, "MIN_COMMIT_TOO_LOW");
require(minPhase1Weth_ >= minCommitWeth_, "MIN_PHASE1_WETH");
require(minAnchorPriceWad_ >= MIN_ANCHOR_PRICE_WAD, "MIN_ANCHOR_PRICE_TOO_LOW");
require(treasuryBps_ <= 2_000, "TREASURY_BPS");
require(refundPenaltyBps_ <= BPS, "REFUND_PENALTY_BPS");
require(saleTokens_ > 0, "SALE_ZERO");
require(lpTokens_ >= MIN_LP_TOKENS, "LP_TOO_LOW");
if (deadTokens_ > 0) require(deadRecipient_ == CANONICAL_DEAD_RECIPIENT, "DEAD_RECIPIENT");
// The 10% cap and four-way supply split are enforced by D17Factory._validateConfig;
// only canonical-factory launches are registered, so the constructor keeps the
// cheaper recipient check.
if (manualDistributionTokens_ > 0) {
require(manualDistributionRecipient_ != address(0), "MANUAL_RECIPIENT_ZERO");
}
uint256 shareTotal;
for (uint256 i; i < ROUND_COUNT; i++) {
require(roundSeconds_[i] > 0, "ROUND_SECONDS_ZERO");
require(roundSharesBps_[i] > 0, "ROUND_SHARE_ZERO");
require(saleTokens_ * roundSharesBps_[i] / BPS >= MIN_ROUND_ALLOCATION_TOKENS, "ROUND_ALLOCATION_TOO_LOW");
roundSeconds[i] = roundSeconds_[i];
roundSharesBps[i] = roundSharesBps_[i];
shareTotal += roundSharesBps_[i];
}
require(shareTotal == BPS, "ROUND_SHARE_TOTAL");
factory = factory_;
vaultConfigurator = vaultConfigurator_;
token = token_;
weth = weth_;
treasury = treasury_;
metadataHash = metadataHash_;
startTime = startTime_;
refundSeconds = refundSeconds_;
settlementSeconds = settlementSeconds_;
tradingOpenAt = _roundEnd(ROUND_COUNT - 1, startTime_, roundSeconds_, refundSeconds_) + settlementSeconds_;
minCommitWeth = minCommitWeth_;
minPhase1Weth = minPhase1Weth_;
minAnchorPriceWad = minAnchorPriceWad_;
treasuryBps = treasuryBps_;
refundPenaltyBps = refundPenaltyBps_;
saleTokens = saleTokens_;
lpTokens = lpTokens_;
deadTokens = deadTokens_;
deadRecipient = deadRecipient_;
manualDistributionTokens = manualDistributionTokens_;
manualDistributionRecipient = manualDistributionRecipient_;
burnUnsoldSaleTokens = burnUnsoldSaleTokens_;
}
receive() external payable {
revert("DIRECT_ETH_REJECTED");
}
fallback() external payable {
revert("UNSUPPORTED_CALL");
}
function configureLiquidityVault(address liquidityVault_) external {
require(msg.sender == vaultConfigurator, "NOT_VAULT_CONFIGURATOR");
require(liquidityVault == address(0), "VAULT_CONFIGURED");
require(liquidityVault_ != address(0), "VAULT_ZERO");
require(liquidityVault_.code.length > 0, "VAULT_NO_CODE");
liquidityVault = liquidityVault_;
emit LiquidityVaultConfigured(liquidityVault_);
}
function rulesHash() public view returns (bytes32) {
return keccak256(abi.encode(
D17_LAUNCH_ID,
factory,
liquidityVault,
token,
weth,
treasury,
startTime,
refundSeconds,
settlementSeconds,
tradingOpenAt,
minCommitWeth,
minPhase1Weth,
minAnchorPriceWad,
roundSeconds,
roundSharesBps,
treasuryBps,
refundPenaltyBps,
saleTokens,
lpTokens,
deadTokens,
deadRecipient,
manualDistributionTokens,
manualDistributionRecipient,
burnUnsoldSaleTokens,
metadataHash
));
}
function activeRound() public view returns (uint8) {
for (uint8 round; round < ROUND_COUNT; round++) {
uint256 start = roundStart(round);
if (block.timestamp >= start && block.timestamp < start + roundSeconds[round]) {
if (round > 0 && !anchorReady()) return NO_ROUND;
return round;
}
}
return NO_ROUND;
}
function activeRefundWindow() public view returns (uint8) {
for (uint8 round; round < REFUND_STAGE_COUNT; round++) {
uint256 end = roundEnd(round);
if (block.timestamp >= end && block.timestamp < end + refundSeconds) return round;
}
return NO_ROUND;
}
function roundStart(uint8 round) public view returns (uint256) {
require(round < ROUND_COUNT, "ROUND");
uint256 cursor = startTime;
for (uint8 i; i < round; i++) {
cursor += roundSeconds[i];
if (i < REFUND_STAGE_COUNT) cursor += refundSeconds;
}
return cursor;
}
function roundEnd(uint8 round) public view returns (uint256) {
return roundStart(round) + roundSeconds[round];
}
function roundBaseTokenAllocation(uint8 round) public view returns (uint256) {
require(round < ROUND_COUNT, "ROUND");
return saleTokens * roundSharesBps[round] / BPS;
}
function roundTokenAllocation(uint8 round) public view returns (uint256) {
require(round < ROUND_COUNT, "ROUND");
if (round == FINAL_ROUND) {
uint256 finalPool = finalized ? finalRoundTokenPool : roundBaseTokenAllocation(FINAL_ROUND) + rolloverToFinalRound();
return finalPool;
}
return roundBaseTokenAllocation(round);
}
function roundClaimTime(uint8 round) public view returns (uint256) {
require(round < ROUND_COUNT, "ROUND");
if (round < REFUND_STAGE_COUNT) return roundEnd(round) + refundSeconds;
return roundEnd(round);
}
function anchorPriceWad() public view returns (uint256) {
uint256 allocation = roundBaseTokenAllocation(0);
if (allocation == 0 || roundRaised[0] == 0) return 0;
return roundRaised[0] * WAD / allocation;
}
function anchorReady() public view returns (bool) {
return roundRaised[0] >= minPhase1Weth && anchorPriceWad() >= minAnchorPriceWad;
}
function launchFailed() public view returns (bool) {
return !finalized && block.timestamp >= roundEnd(0) + refundSeconds && !anchorReady();
}
function roundAnchorTargetWeth(uint8 round) public view returns (uint256) {
require(round < ROUND_COUNT, "ROUND");
if (round == 0 || round == FINAL_ROUND) return 0;
uint256 anchor = anchorPriceWad();
if (anchor == 0) return 0;
return roundBaseTokenAllocation(round) * anchor / WAD;
}
function roundAnchorUnderfillRemainingWeth(uint8 round) public view returns (uint256) {
require(round < ROUND_COUNT, "ROUND");
if (round == 0 || round == FINAL_ROUND) return 0;
uint256 target = roundAnchorTargetWeth(round);
if (roundRaised[round] >= target) return 0;
return target - roundRaised[round];
}
function roundSoldTokens(uint8 round) public view returns (uint256) {
require(round < ROUND_COUNT, "ROUND");
uint256 raised = roundRaised[round];
if (raised == 0) return 0;
uint256 allocation = roundTokenAllocation(round);
if (round == 0) return anchorReady() ? allocation : 0;
if (round == FINAL_ROUND) return allocation;
uint256 target = roundAnchorTargetWeth(round);
if (target == 0) return 0;
if (raised >= target) return allocation;
return allocation * raised / target;
}
function rolloverToFinalRound() public view returns (uint256 rolloverTokens) {
for (uint8 round = 1; round < FINAL_ROUND; round++) {
uint256 allocation = roundBaseTokenAllocation(round);
uint256 sold = roundSoldTokens(round);
if (allocation > sold) rolloverTokens += allocation - sold;
}
}
function roundDiscoveredPriceWad(uint8 round) public view returns (uint256) {
require(round < ROUND_COUNT, "ROUND");
uint256 soldTokens = roundSoldTokens(round);
if (soldTokens == 0 || roundRaised[round] == 0) return 0;
return roundRaised[round] * WAD / soldTokens;
}
function isRoundClaimable(uint8 round) public view returns (bool) {
return block.timestamp >= roundClaimTime(round);
}
function settlementStartsAt() public view returns (uint256) {
return roundEnd(FINAL_ROUND);
}
function poolCreationOpensAt() public view returns (uint256) {
if (!finalized) return tradingOpenAt;
uint256 finalizedDeadline = finalizedAt + settlementSeconds;
return finalizedDeadline > tradingOpenAt ? finalizedDeadline : tradingOpenAt;
}
function tradingOpen() public view returns (bool) {
return liquidityPoolCreated;
}
function totalCommittedWeth() public view returns (uint256 total) {
for (uint8 round; round < ROUND_COUNT; round++) total += roundRaised[round];
}
function totalLiquidityWeth() public view returns (uint256) {
uint256 committed = finalized ? finalCommittedWeth : totalCommittedWeth();
return committed * (BPS - treasuryBps) / BPS;
}
/// @notice Read-only settlement-progress metric; it never gates lifecycle progress.
/// pool creation and trading open proceed with the settled fraction, and late settlers
/// top up the official pool afterwards.
function allFinalCommitmentsSettled() public view returns (bool) {
return finalized && finalCommittedWeth > 0 && settledCommittedWeth == finalCommittedWeth;
}
// Derivable metrics intentionally have no dedicated getters (code-size limit):
// unsettled committed WETH = finalCommittedWeth - settledCommittedWeth (once finalized);
// reserved LP tokens = lpTokens - vaultLiquidityTokensClaimed - lateLpTokensReleased
// (once the vault liquidity claim has happened).
function contributedBy(address locker, uint8 round) external view returns (uint256) {
require(round < ROUND_COUNT, "ROUND");
return positions[locker].paid[round];
}
function lockerPositionState(address locker)
external
view
returns (
bool liquidityClaimed,
bool finalSaleTokensClaimed,
uint256 refundWeth,
uint256 penaltyWeth,
bool[5] memory refunded
)
{
Position storage position = positions[locker];
return (
position.liquidityClaimed,
position.finalSaleTokensClaimed,
position.refundWeth,
position.penaltyWeth,
position.refunded
);
}
function previewRoundTokens(address locker, uint8 round) public view returns (uint256 saleTokenAmount) {
require(round < ROUND_COUNT, "ROUND");
Position storage position = positions[locker];
if (position.finalSaleTokensClaimed || position.refunded[round]) return 0;
uint256 paid = position.paid[round];
if (paid == 0) return 0;
return _roundTokensForBuyer(round, paid);
}
function previewFinalSaleTokens(address locker) public view returns (uint256 saleTokenAmount) {
Position storage position = positions[locker];
if (position.finalSaleTokensClaimed) return 0;
for (uint8 round; round < ROUND_COUNT; round++) saleTokenAmount += previewRoundTokens(locker, round);
}
function previewVaultSettlement(address locker)
public
view
returns (uint256 saleTokenAmount, uint256 grossCommittedWeth, uint256 wethForVault, uint256 treasuryWeth)
{
Position storage position = positions[locker];
if (position.liquidityClaimed) return (0, 0, 0, 0);
saleTokenAmount = previewFinalSaleTokens(locker);
(grossCommittedWeth, wethForVault, treasuryWeth) = _vaultSettlementAmounts(position);
}
function previewSettlement(address locker)
external
view
returns (uint256 saleTokenAmount, uint256 grossCommittedWeth, uint256 wethForVault, uint256 treasuryWeth)
{
return previewVaultSettlement(locker);
}
function launchPhase()
external
view
returns (uint8 phaseKind, uint8 index, uint256 startsAt, uint256 endsAt)
{
if (finalized && liquidityPoolCreated) {
return (PHASE_TRADING_OPEN, NO_ROUND, poolCreatedAt, type(uint256).max);
}
if (finalized && block.timestamp < poolCreationOpensAt()) {
return (PHASE_SETTLEMENT_OPEN, NO_ROUND, finalizedAt, poolCreationOpensAt());
}
if (finalized) {
return (PHASE_POOL_READY, NO_ROUND, poolCreationOpensAt(), type(uint256).max);
}
if (block.timestamp < startTime) return (PHASE_NOT_STARTED, NO_ROUND, startTime, startTime);
if (launchFailed()) return (PHASE_FAILED, NO_ROUND, roundEnd(0) + refundSeconds, type(uint256).max);
uint8 round = activeRound();
if (round != NO_ROUND) return (PHASE_ROUND_OPEN, round, roundStart(round), roundEnd(round));
uint8 refundWindow = activeRefundWindow();
if (refundWindow != NO_ROUND) {
uint256 refundStart = roundEnd(refundWindow);
return (PHASE_REFUND_OPEN, refundWindow, refundStart, refundStart + refundSeconds);
}
if (block.timestamp >= roundEnd(ROUND_COUNT - 1)) {
uint256 finalRoundEnd = roundEnd(ROUND_COUNT - 1);
return (PHASE_READY_TO_FINALIZE, NO_ROUND, finalRoundEnd, poolCreationOpensAt());
}
return (PHASE_NOT_STARTED, NO_ROUND, startTime, startTime);
}
function recordRoundCommitment(uint8 round, uint256 amount) external onlyLocker nonReentrant {
require(round < ROUND_COUNT, "ROUND");
require(amount >= minCommitWeth, "COMMIT_TOO_SMALL");
require(round == activeRound(), "ROUND_CLOSED");
if (round > 0 && round < FINAL_ROUND) {
require(anchorReady(), "ANCHOR_NOT_READY");
} else if (round == FINAL_ROUND) {
require(anchorReady(), "ANCHOR_NOT_READY");
}
Position storage position = positions[msg.sender];
require(!position.liquidityClaimed, "LIQUIDITY_CLAIMED");
require(!position.refunded[round], "ROUND_REFUNDED");
require(!position.finalSaleTokensClaimed, "SALE_TOKENS_CLAIMED");
position.paid[round] += amount;
roundRaised[round] += amount;
emit RoundCommitted(msg.sender, round, amount);
}
function releaseRoundRefund()
external
onlyLocker
nonReentrant
returns (uint8 round, uint256 refundWeth, uint256 penaltyWeth)
{
round = activeRefundWindow();
require(round != NO_ROUND, "NO_REFUND_STAGE");
Position storage position = positions[msg.sender];
require(!position.liquidityClaimed, "LIQUIDITY_CLAIMED");
require(!position.refunded[round], "ROUND_REFUNDED");
require(!position.finalSaleTokensClaimed, "SALE_TOKENS_CLAIMED");
uint256 gross = position.paid[round];
require(gross > 0, "NO_ROUND_POSITION");
roundRaised[round] -= gross;
position.paid[round] = 0;
position.refunded[round] = true;
// Refund schedule [free, free, penalty, penalty, no-window]: display rounds
// 1-2 (contract rounds 0-1) refund penalty-free, display rounds 3-4 (contract
// rounds 2-3) charge the global refundPenaltyBps, and the final round has no
// normal refund window (REFUND_STAGE_COUNT).
penaltyWeth = round < FREE_REFUND_ROUNDS ? 0 : gross * refundPenaltyBps / BPS;
refundWeth = gross - penaltyWeth;
retainedPenaltyWeth += penaltyWeth;
penaltyWethPaid += penaltyWeth;
treasuryWethPaid += penaltyWeth;
position.refundWeth += refundWeth;
position.penaltyWeth += penaltyWeth;
emit RoundRefunded(msg.sender, round, refundWeth, penaltyWeth);
}
function releaseFailedRefund() external onlyLocker nonReentrant returns (uint256 refundWeth) {
require(launchFailed(), "LAUNCH_NOT_FAILED");
Position storage position = positions[msg.sender];
require(!position.liquidityClaimed, "LIQUIDITY_CLAIMED");
require(!position.finalSaleTokensClaimed, "SALE_TOKENS_CLAIMED");
for (uint8 round; round < ROUND_COUNT; round++) {
uint256 paid = position.paid[round];
if (paid == 0) continue;
roundRaised[round] -= paid;
position.paid[round] = 0;
position.refunded[round] = true;
refundWeth += paid;
}
require(refundWeth > 0, "NO_POSITION");
position.refundWeth += refundWeth;
emit LaunchFailedRefunded(msg.sender, refundWeth);
}
function claimVaultSettlement()
external
onlyLocker
nonReentrant
returns (uint256 saleTokenAmount, uint256 wethForVault, uint256 treasuryWeth)
{
require(!liquidityPoolCreated, "POOL_CREATED");
(saleTokenAmount, wethForVault, treasuryWeth, ) = _settlePosition(false);
}
/// @notice Settlement for lockers that missed pool creation. Outcome-identical to an
/// on-time settlement: the exact finalized sale tokens, the exact same WETH cost, the
/// unchanged treasuryBps fee. The position's LP-share WETH still enters the official
/// pool path: this function releases the position's pro-rata share of the reserved LP
/// tokens (held back at pool creation) to the vault, and the calling locker delivers the
/// LP-share WETH to the vault and triggers the vault's pair top-up in the same
/// transaction. Callable forever; no deadline.
function claimLateSettlement()
external
onlyLocker
nonReentrant
returns (uint256 saleTokenAmount, uint256 wethForVault, uint256 treasuryWeth, uint256 lateLpTokens)
{
require(liquidityPoolCreated, "POOL_NOT_CREATED");
return _settlePosition(true);
}
function _settlePosition(bool late)
internal
returns (uint256 saleTokenAmount, uint256 wethForVault, uint256 treasuryWeth, uint256 lateLpTokens)
{
require(liquidityVault != address(0), "VAULT_NOT_CONFIGURED");
if (!finalized) _finalizeLaunch();
Position storage position = positions[msg.sender];
require(!position.liquidityClaimed, "LIQUIDITY_CLAIMED");
require(!position.finalSaleTokensClaimed, "SALE_TOKENS_CLAIMED");
saleTokenAmount = previewFinalSaleTokens(msg.sender);
uint256 grossCommittedWeth;
(grossCommittedWeth, wethForVault, treasuryWeth) = _vaultSettlementAmounts(position);
require(grossCommittedWeth > 0, "NO_POSITION");
position.liquidityClaimed = true;
position.finalSaleTokensClaimed = true;
settledCommittedWeth += grossCommittedWeth;
treasuryWethPaid += treasuryWeth;
if (late) {
// A zero lateLpTokens (unreachable under factory config bounds) reverts in the
// vault's mintLateLiquidity ("LATE_AMOUNTS_ZERO") within the same transaction.
lateLpTokens = lpTokens * wethForVault / totalLiquidityWeth();
require(
vaultLiquidityTokensClaimed + lateLpTokensReleased + lateLpTokens <= lpTokens,
"LP_RESERVE_EXCEEDED"
);
lateSettledCommittedWeth += grossCommittedWeth;
lateSettledLiquidityWeth += wethForVault;
lateLpTokensReleased += lateLpTokens;
token.safeTransfer(liquidityVault, lateLpTokens);
emit LateVaultSettlementClaimed(
msg.sender,
saleTokenAmount,
wethForVault,
treasuryWeth,
lateLpTokens,
grossCommittedWeth
);
} else {
settledLiquidityWeth += wethForVault;
emit VaultSettlementClaimed(msg.sender, saleTokenAmount, wethForVault, treasuryWeth, grossCommittedWeth);
}
if (saleTokenAmount > 0) token.safeTransfer(msg.sender, saleTokenAmount);
}
function finalizeLaunch() external nonReentrant {
_finalizeLaunch();
}
function claimVaultLiquidityTokens()
external
onlyVault
nonReentrant
returns (uint256 liquidityTokens, uint256 wethForPool)
{
if (!finalized) _finalizeLaunch();
require(!liquidityPoolCreated, "POOL_CREATED");
require(!vaultLiquidityClaimed, "VAULT_LIQUIDITY_CLAIMED");
require(block.timestamp >= poolCreationOpensAt(), "POOL_CREATION_NOT_OPEN");
require(settledLiquidityWeth > 0, "NO_SETTLED_LIQUIDITY");
// The initial pool pairs the WETH settled so far with the
// proportional share of the LP token allocation, so the pool always opens at the
// canonical launch ratio (lpTokens : totalLiquidityWeth). The remaining LP tokens
// stay reserved in this contract for late settlers, whose top-ups enter the pair at
// the same ratio through claimLateSettlement().
wethForPool = settledLiquidityWeth;
liquidityTokens = lpTokens * settledLiquidityWeth / totalLiquidityWeth();
require(liquidityTokens > 0, "NO_LIQUIDITY_TOKENS");
vaultLiquidityClaimed = true;
vaultLiquidityTokensClaimed = liquidityTokens;
poolSettledLiquidityWeth = settledLiquidityWeth;
poolSettledCommittedWeth = settledCommittedWeth;
token.safeTransfer(liquidityVault, liquidityTokens);
emit VaultLiquidityTokensClaimed(liquidityVault, liquidityTokens, wethForPool);
}
function markLiquidityPoolCreated(address pair, uint256 tokenUsed, uint256 wethUsed, uint256 lpMinted)
external
onlyVault
nonReentrant
{
require(!liquidityPoolCreated, "POOL_CREATED");
require(vaultLiquidityClaimed, "VAULT_LIQUIDITY_NOT_CLAIMED");
require(pair != address(0), "PAIR_ZERO");
require(tokenUsed == vaultLiquidityTokensClaimed, "TOKEN_USED_MISMATCH");
require(wethUsed == poolSettledLiquidityWeth, "WETH_USED_MISMATCH");
require(lpMinted > 0, "LP_ZERO");
liquidityPoolCreated = true;
officialPair = pair;
officialTokenUsedForLp = tokenUsed;
officialWethUsedForLp = wethUsed;
officialLpMinted = lpMinted;
poolCreatedAt = block.timestamp;
emit LiquidityPoolCreated(liquidityVault, pair, tokenUsed, wethUsed, lpMinted);
}
function sweepUnexpectedEthToTreasury() external nonReentrant returns (uint256 amount) {
amount = address(this).balance;
require(amount > 0, "NO_ETH_BALANCE");
(bool ok, ) = treasury.call{value: amount}("");
require(ok, "ETH_SWEEP_FAILED");
emit UnexpectedEthSwept(treasury, amount);
}
function _finalizeLaunch() internal {
require(!finalized, "FINALIZED");
require(!launchFailed(), "LAUNCH_FAILED");
require(block.timestamp >= roundEnd(ROUND_COUNT - 1), "NOT_OVER");
finalized = true;
finalizedAt = block.timestamp;
finalRoundTokenPool = roundBaseTokenAllocation(FINAL_ROUND) + rolloverToFinalRound();
finalCommittedWeth = totalCommittedWeth();
// Belt-and-braces guard: canonical launches should only reach finalization after the phase-one
// anchor made total commitments nonzero. Keep this explicit so future refund logic cannot
// accidentally finalize an empty launch.
require(finalCommittedWeth > 0, "NO_FINAL_COMMITMENTS");
uint256 soldSaleTokens = _soldSaleTokenAmount();
unsoldSaleTokensSettled = saleTokens > soldSaleTokens ? saleTokens - soldSaleTokens : 0;
if (unsoldSaleTokensSettled > 0) {
if (burnUnsoldSaleTokens) {
unsoldSaleTokensBurned = true;
token.safeBurn(unsoldSaleTokensSettled);
emit UnsoldSaleTokensBurned(unsoldSaleTokensSettled);
} else {
token.safeTransfer(treasury, unsoldSaleTokensSettled);
emit UnsoldSaleTokensPaid(treasury, unsoldSaleTokensSettled);
}
}
emit Finalized(finalizedAt);
}
function _vaultSettlementAmounts(Position storage position)
internal
view
returns (uint256 grossCommittedWeth, uint256 wethForVault, uint256 treasuryWeth)
{
for (uint8 round; round < ROUND_COUNT; round++) grossCommittedWeth += position.paid[round];
if (grossCommittedWeth == 0) return (0, 0, 0);
wethForVault = grossCommittedWeth * (BPS - treasuryBps) / BPS;
treasuryWeth = grossCommittedWeth - wethForVault;
}
function _roundTokensForBuyer(uint8 round, uint256 paid) internal view returns (uint256) {
if (paid == 0) return 0;
if (roundRaised[round] == 0) return 0;
if (round == 0) {
if (!anchorReady()) return 0;
return roundBaseTokenAllocation(0) * paid / roundRaised[round];
}
uint256 sold = roundSoldTokens(round);
if (sold == 0) return 0;
return sold * paid / roundRaised[round];
}
function _soldSaleTokenAmount() internal view returns (uint256 soldSaleTokens) {
for (uint8 round; round < ROUND_COUNT; round++) soldSaleTokens += roundSoldTokens(round);
if (soldSaleTokens > saleTokens) return saleTokens;
}
function _roundEnd(uint8 round, uint256 start, uint32[5] memory durations, uint32 refundDuration)
private
pure
returns (uint256)
{
uint256 cursor = start;
for (uint8 i; i < round; i++) {
cursor += durations[i];
if (i < REFUND_STAGE_COUNT) cursor += refundDuration;
}
return cursor + durations[round];
}
}
project/contracts/D17LaunchFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {D17Launch} from "./D17Launch.sol";
import {ID17LaunchFactory} from "./interfaces/ID17LaunchFactory.sol";
interface ID17FactoryConfigView {
function weth() external view returns (address);
function router() external view returns (address);
}
interface IV2RouterFactoryView {
function factory() external view returns (address);
}
interface ID17LiquidityVaultFactory {
function deployVault(address launch, address token, address weth, address router, address treasury)
external
returns (address liquidityVault);
}
interface ID17TokenFactory {
function deployToken(address tokenOwner, string calldata name, string calldata symbol, uint256 maxSupply)
external
returns (address token);
}
interface ID17LaunchToken {
function configureTradingGate(
address launch,
address d17Factory,
address weth,
address routerFactory,
address liquidityVault,
uint256 tradingOpenAt
) external;
function configureMetadata(
string calldata description,
string calldata logoSvgUri,
ID17LaunchFactory.Link[] calldata links
) external;
function mint(address to, uint256 amount) external;
function closeMinting() external;
function renounceOwnership() external;
}
contract D17LaunchFactory is ID17LaunchFactory {
address public constant CANONICAL_DEAD_RECIPIENT = 0x000000000000000000000000000000000000dEaD;
address public immutable d17Factory;
address public immutable tokenFactory;
address public immutable liquidityVaultFactory;
modifier onlyD17Factory() {
require(msg.sender == d17Factory, "NOT_D17_FACTORY");
_;
}
constructor(address d17Factory_, address tokenFactory_, address liquidityVaultFactory_) {
require(d17Factory_ != address(0), "FACTORY_ZERO");
require(tokenFactory_ != address(0), "TOKEN_FACTORY_ZERO");
require(liquidityVaultFactory_ != address(0), "VAULT_FACTORY_ZERO");
require(d17Factory_.code.length > 0, "FACTORY_NO_CODE");
require(tokenFactory_.code.length > 0, "TOKEN_FACTORY_NO_CODE");
require(liquidityVaultFactory_.code.length > 0, "VAULT_FACTORY_NO_CODE");
d17Factory = d17Factory_;
tokenFactory = tokenFactory_;
liquidityVaultFactory = liquidityVaultFactory_;
}
function deployLaunch(LaunchConfig calldata config, address creator)
external
onlyD17Factory
returns (address token, address launch, address liquidityVault)
{
require(creator != address(0), "CREATOR_ZERO");
token = ID17TokenFactory(tokenFactory).deployToken(
address(this),
config.tokenName,
config.tokenSymbol,
config.tokenSupply
);
D17Launch deployedLaunch = new D17Launch(
d17Factory,
address(this),
token,
ID17FactoryConfigView(d17Factory).weth(),
config.treasury,
_metadataHash(config),
config.startTime,
config.roundSeconds,
config.refundSeconds,
config.settlementSeconds,
config.minCommitWeth,
config.minPhase1Weth,
config.minAnchorPriceWad,
config.roundSharesBps,
config.treasuryBps,
config.refundPenaltyBps,
config.saleTokens,
config.lpTokens,
config.deadTokens,
config.deadRecipient,
config.manualDistributionTokens,
creator,
config.burnUnsoldSaleTokens
);
launch = address(deployedLaunch);
address weth = ID17FactoryConfigView(d17Factory).weth();
address router = ID17FactoryConfigView(d17Factory).router();
address routerFactory = IV2RouterFactoryView(router).factory();
liquidityVault =
ID17LiquidityVaultFactory(liquidityVaultFactory).deployVault(launch, token, weth, router, config.treasury);
deployedLaunch.configureLiquidityVault(liquidityVault);
ID17LaunchToken(token).configureTradingGate(
launch,
d17Factory,
weth,
routerFactory,
liquidityVault,
deployedLaunch.tradingOpenAt()
);
ID17LaunchToken(token).configureMetadata(config.description, config.logoSvgUri, config.links);
ID17LaunchToken(token).mint(launch, config.saleTokens + config.lpTokens);
if (config.manualDistributionTokens > 0) ID17LaunchToken(token).mint(creator, config.manualDistributionTokens);
if (config.deadTokens > 0) ID17LaunchToken(token).mint(CANONICAL_DEAD_RECIPIENT, config.deadTokens);
ID17LaunchToken(token).closeMinting();
ID17LaunchToken(token).renounceOwnership();
}
function _metadataHash(LaunchConfig calldata config) internal pure returns (bytes32) {
return keccak256(
abi.encode(
config.tokenName,
config.tokenSymbol,
config.description,
config.logoSvgUri,
config.links
)
);
}
}
project/contracts/D17LiquidityVault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {D17SafeTransfer} from "./lib/D17SafeTransfer.sol";
import {ID17FactoryView, ID17Launch, IERC20BalanceView, IV2Factory, IV2PairView, IV2Router} from "./interfaces/ID17.sol";
contract D17LiquidityVault {
using D17SafeTransfer for address;
bytes32 public constant D17_LIQUIDITY_VAULT_ID = keccak256("D17_LIQUIDITY_VAULT_V14_1_REFUND_SCHEDULE_BURN_GATE");
address public immutable launch;
address public immutable token;
address public immutable weth;
address public immutable router;
address public immutable routerFactory;
address public immutable treasury;
bool public poolCreated;
address public officialPair;
uint256 public tokenUsedForPool;
uint256 public wethUsedForPool;
uint256 public lpMinted;
uint256 public lateTokenUsedForLp;
uint256 public lateWethUsedForLp;
uint256 public lateLpMinted;
uint256 public preseededTokenReserve;
uint256 public preseededWethReserve;
uint256 private entered = 1;
event OfficialPoolCreated(
address indexed pair,
uint256 tokenUsed,
uint256 wethUsed,
uint256 lpMinted,
uint256 preseededTokenReserve,
uint256 preseededWethReserve
);
event LateLiquidityAdded(
address indexed locker,
address indexed pair,
uint256 tokenUsed,
uint256 wethUsed,
uint256 lpMinted
);
event ExcessWethSwept(address indexed recipient, uint256 amount);
event UnsupportedTokenRecovered(address indexed token, address indexed recipient, uint256 amount);
event UnexpectedEthSwept(address indexed recipient, uint256 amount);
modifier nonReentrant() {
require(entered == 1, "REENTRANT");
entered = 2;
_;
entered = 1;
}
constructor(address launch_, address token_, address weth_, address router_, address treasury_) {
require(launch_ != address(0), "LAUNCH_ZERO");
require(token_ != address(0), "TOKEN_ZERO");
require(weth_ != address(0), "WETH_ZERO");
require(router_ != address(0), "ROUTER_ZERO");
require(treasury_ != address(0), "TREASURY_ZERO");
require(launch_.code.length > 0, "LAUNCH_NO_CODE");
require(token_.code.length > 0, "TOKEN_NO_CODE");
require(weth_.code.length > 0, "WETH_NO_CODE");
require(router_.code.length > 0, "ROUTER_NO_CODE");
address routerFactory_ = IV2Router(router_).factory();
require(routerFactory_ != address(0), "ROUTER_FACTORY_ZERO");
require(routerFactory_.code.length > 0, "ROUTER_FACTORY_NO_CODE");
launch = launch_;
token = token_;
weth = weth_;
router = router_;
routerFactory = routerFactory_;
treasury = treasury_;
}
receive() external payable {
revert("DIRECT_ETH_REJECTED");
}
fallback() external payable {
revert("UNSUPPORTED_CALL");
}
function createOfficialPool(uint256 minLpMinted, uint256 deadline)
external
nonReentrant
returns (address pair, uint256 liquidityTokens, uint256 wethForPool, uint256 liquidity)
{
require(!poolCreated, "POOL_CREATED");
require(block.timestamp <= deadline, "DEADLINE");
// The launch pairs settled WETH with the proportional LP
// token share at the canonical launch ratio; late settlers top up through
// mintLateLiquidity() afterwards.
require(block.timestamp >= ID17Launch(launch).poolCreationOpensAt(), "POOL_CREATION_NOT_OPEN");
pair = IV2Factory(routerFactory).getPair(token, weth);
if (pair == address(0)) {
pair = IV2Factory(routerFactory).createPair(token, weth);
}
require(pair.code.length > 0, "PAIR_NO_CODE");
require(IV2PairView(pair).totalSupply() == 0, "PAIR_ALREADY_LIVE");
(uint256 tokenReserve, uint256 wethReserve) = _pairReserves(pair);
uint256 tokenBalanceBefore = IERC20BalanceView(token).balanceOf(pair);
uint256 wethBalanceBefore = IERC20BalanceView(weth).balanceOf(pair);
uint256 preseededWeth = wethBalanceBefore > wethReserve ? wethBalanceBefore : wethReserve;
require(tokenBalanceBefore == 0, "PAIR_PRESEEDED_TOKEN");
(uint256 claimedLiquidityTokens, uint256 claimedWethForPool) = ID17Launch(launch).claimVaultLiquidityTokens();
wethForPool = claimedWethForPool;
liquidityTokens = IERC20BalanceView(token).balanceOf(address(this));
require(liquidityTokens == claimedLiquidityTokens, "VAULT_TOKEN_BALANCE");
require(liquidityTokens > 0, "NO_TOKEN_BALANCE");
require(wethForPool > 0, "NO_WETH_FOR_POOL");
require(IERC20BalanceView(weth).balanceOf(address(this)) >= wethForPool, "VAULT_WETH_BALANCE");
token.safeTransfer(pair, liquidityTokens);
weth.safeTransfer(pair, wethForPool);
liquidity = IV2PairView(pair).mint(address(this));
require(liquidity >= minLpMinted, "LP_SLIPPAGE");
poolCreated = true;
officialPair = pair;
tokenUsedForPool = liquidityTokens;
wethUsedForPool = wethForPool;
lpMinted = liquidity;
preseededTokenReserve = tokenReserve;
preseededWethReserve = preseededWeth;
ID17Launch(launch).markLiquidityPoolCreated(pair, liquidityTokens, wethForPool, liquidity);
emit OfficialPoolCreated(pair, liquidityTokens, wethForPool, liquidity, tokenBalanceBefore, preseededWethReserve);
}
/// @notice Adds a late settler's LP-share WETH plus its reserved LP-token share to the
/// official pair at the canonical launch ratio, minting the resulting LP to this vault
/// (permanently locked, like the original position). Called by the settling locker in
/// the same transaction as claimLateSettlement(): the launch has just transferred the
/// reserved tokens here and the locker has just transferred the WETH here, so the exact
/// amounts are always available and never linger in the vault.
function mintLateLiquidity(uint256 tokenAmount, uint256 wethAmount)
external
nonReentrant
returns (uint256 liquidity)
{
require(poolCreated, "POOL_NOT_CREATED");
require(
ID17FactoryView(ID17Launch(launch).factory()).isLocker(msg.sender),
"NOT_D17_LOCKER"
);
require(tokenAmount > 0 && wethAmount > 0, "LATE_AMOUNTS_ZERO");
require(IERC20BalanceView(token).balanceOf(address(this)) >= tokenAmount, "VAULT_TOKEN_BALANCE");
require(IERC20BalanceView(weth).balanceOf(address(this)) >= wethAmount, "VAULT_WETH_BALANCE");
token.safeTransfer(officialPair, tokenAmount);
weth.safeTransfer(officialPair, wethAmount);
liquidity = IV2PairView(officialPair).mint(address(this));
require(liquidity > 0, "LATE_LP_ZERO");
lateTokenUsedForLp += tokenAmount;
lateWethUsedForLp += wethAmount;
lateLpMinted += liquidity;
emit LateLiquidityAdded(msg.sender, officialPair, tokenAmount, wethAmount, liquidity);
}
function sweepExcessWethToTreasury() external nonReentrant returns (uint256 amount) {
require(poolCreated, "POOL_NOT_CREATED");
amount = IERC20BalanceView(weth).balanceOf(address(this));
require(amount > 0, "NO_EXCESS_WETH");
weth.safeTransfer(treasury, amount);
emit ExcessWethSwept(treasury, amount);
}
function recoverUnsupportedTokenToTreasury(address tokenAddress, uint256 amount) external nonReentrant {
require(amount > 0, "AMOUNT_ZERO");
require(tokenAddress != address(0), "TOKEN_ZERO");
require(tokenAddress != token, "D17_TOKEN_PROTECTED");
require(tokenAddress != weth, "WETH_PROTECTED");
require(tokenAddress != officialPair, "LP_PROTECTED");
tokenAddress.safeTransfer(treasury, amount);
emit UnsupportedTokenRecovered(tokenAddress, treasury, amount);
}
function sweepUnexpectedEthToTreasury() external nonReentrant returns (uint256 amount) {
amount = address(this).balance;
require(amount > 0, "NO_ETH_BALANCE");
(bool ok, ) = treasury.call{value: amount}("");
require(ok, "ETH_SWEEP_FAILED");
emit UnexpectedEthSwept(treasury, amount);
}
function _pairReserves(address pair) internal view returns (uint256 tokenReserve, uint256 wethReserve) {
(uint112 reserve0, uint112 reserve1, ) = IV2PairView(pair).getReserves();
address token0 = IV2PairView(pair).token0();
if (token0 == token) {
tokenReserve = uint256(reserve0);
wethReserve = uint256(reserve1);
} else {
tokenReserve = uint256(reserve1);
wethReserve = uint256(reserve0);
}
}
}
project/contracts/D17LiquidityVaultFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {D17LiquidityVault} from "./D17LiquidityVault.sol";
contract D17LiquidityVaultFactory {
bytes32 public constant D17_LIQUIDITY_VAULT_FACTORY_ID = keccak256("D17_LIQUIDITY_VAULT_FACTORY_V14_1_REFUND_SCHEDULE_BURN_GATE");
address public owner;
address public launchFactory;
bool public launchFactoryPinned;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event LaunchFactoryPinned(address indexed launchFactory);
event LiquidityVaultCreated(address indexed launch, address indexed token, address indexed liquidityVault);
modifier onlyOwner() {
require(msg.sender == owner, "NOT_OWNER");
_;
}
constructor(address owner_) {
require(owner_ != address(0), "OWNER_ZERO");
owner = owner_;
emit OwnershipTransferred(address(0), owner_);
}
function pinLaunchFactory(address launchFactory_) external onlyOwner {
require(!launchFactoryPinned, "LAUNCH_FACTORY_PINNED");
require(launchFactory_ != address(0), "LAUNCH_FACTORY_ZERO");
require(launchFactory_.code.length > 0, "LAUNCH_FACTORY_NO_CODE");
launchFactory = launchFactory_;
launchFactoryPinned = true;
emit LaunchFactoryPinned(launchFactory_);
}
function renounceOwnership() external onlyOwner {
require(launchFactoryPinned, "LAUNCH_FACTORY_UNLOCKED");
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
function deployVault(address launch, address token, address weth, address router, address treasury)
external
returns (address liquidityVault)
{
require(launchFactoryPinned && msg.sender == launchFactory, "NOT_LAUNCH_FACTORY");
liquidityVault = address(new D17LiquidityVault(launch, token, weth, router, treasury));
emit LiquidityVaultCreated(launch, token, liquidityVault);
}
}
project/contracts/D17Locker.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {D17SafeTransfer} from "./lib/D17SafeTransfer.sol";
import {ID17FactoryView, ID17Launch, ID17VaultLateLiquidity, IWETH} from "./interfaces/ID17.sol";
contract D17Locker {
using D17SafeTransfer for address;
bytes32 public constant EXPECTED_LAUNCH_ID = keccak256("D17_LAUNCH_V14_1_REFUND_SCHEDULE_BURN_GATE");
uint8 public constant ROUND_COUNT = 5;
address public immutable owner;
address public immutable factory;
address public immutable weth;
uint256 public withdrawableWeth;
uint256 public accountedWeth;
uint256 private entered = 1;
struct LockerPosition {
bool known;
bool liquiditySettled;
address token;
address liquidityVault;
bytes32 rulesHash;
uint256 ethCommitted;
uint256 wethCommitted;
uint256 wethRefunded;
uint256 penaltyPaid;
uint256 claimedSaleTokens;
uint256 wethSentToVault;
uint256 wethForLp;
uint256 treasuryWeth;
uint256 withdrawableTokens;
uint256 residualWeth;
bool finalSaleTokensClaimed;
uint256[5] roundWeth;
uint256[5] roundSaleTokens;
bool[5] roundRefunded;
bool[5] roundTokensClaimed;
}
mapping(address => LockerPosition) public positions;
event RoundCommitted(address indexed launch, uint8 indexed round, uint256 amount);
event RoundRefunded(address indexed launch, uint8 indexed round, uint256 refundWeth, uint256 penaltyWeth);
event WethWithdrawn(address indexed launch, uint256 amount);
event VaultSettlementCompleted(
address indexed launch,
address indexed liquidityVault,
address indexed settler,
address owner,
uint256 saleTokens,
uint256 wethSentToVault,
uint256 treasuryWeth,
uint256 grossCommittedWeth,
uint256 residualWeth
);
event ClaimedTokensWithdrawn(address indexed launch, uint256 amount);
event FailedLaunchRefunded(address indexed launch, uint256 refundWeth);
event NativeEthRecovered(address indexed recipient, uint256 amount);
event ExcessWethRecovered(address indexed recipient, uint256 amount);
modifier onlyOwner() {
require(msg.sender == owner, "NOT_OWNER");
_;
}
modifier nonReentrant() {
require(entered == 1, "REENTRANT");
entered = 2;
_;
entered = 1;
}
constructor(address owner_, address factory_, address weth_) {
require(owner_ != address(0), "OWNER_ZERO");
require(factory_ != address(0), "FACTORY_ZERO");
require(weth_ != address(0), "WETH_ZERO");
owner = owner_;
factory = factory_;
weth = weth_;
}
receive() external payable {
revert("DIRECT_ETH_REJECTED");
}
fallback() external payable {
revert("UNSUPPORTED_CALL");
}
function verifyLaunch(address launch, bytes32 expectedRulesHash) public view returns (bool) {
require(launch.code.length > 0, "NO_CODE");
ID17Launch candidate = ID17Launch(launch);
require(candidate.D17_LAUNCH_ID() == EXPECTED_LAUNCH_ID, "BAD_LAUNCH_ID");
require(candidate.weth() == weth, "BAD_WETH");
require(candidate.rulesHash() == expectedRulesHash, "BAD_RULES");
require(ID17FactoryView(factory).isCanonicalLaunch(launch, expectedRulesHash), "NOT_CANONICAL");
return true;
}
function lockedWeth(address launch) external view returns (uint256) {
return positions[launch].wethCommitted;
}
function roundPosition(address launch, uint8 round)
external
view
returns (uint256 roundWeth, uint256 roundSaleTokens, bool refunded, bool tokensClaimed)
{
require(round < ROUND_COUNT, "ROUND");
LockerPosition storage position = positions[launch];
return (
position.roundWeth[round],
position.roundSaleTokens[round],
position.roundRefunded[round],
position.roundTokensClaimed[round]
);
}
function commitToRound(address launch, uint8 round, bytes32 expectedRulesHash)
public
payable
onlyOwner
nonReentrant
{
require(msg.value > 0, "NO_ETH");
require(round < ROUND_COUNT, "ROUND");
verifyLaunch(launch, expectedRulesHash);
LockerPosition storage position = positions[launch];
require(!position.liquiditySettled, "LIQUIDITY_SETTLED");
IWETH(weth).deposit{value: msg.value}();
accountedWeth += msg.value;
position.known = true;
position.rulesHash = expectedRulesHash;
position.token = ID17Launch(launch).token();
position.ethCommitted += msg.value;
position.wethCommitted += msg.value;
position.roundWeth[round] += msg.value;
ID17Launch(launch).recordRoundCommitment(round, msg.value);
emit RoundCommitted(launch, round, msg.value);
}
function refundCurrentRound(address launch) public onlyOwner nonReentrant {
LockerPosition storage position = positions[launch];
require(position.known, "UNKNOWN_LAUNCH");
require(!position.liquiditySettled, "LIQUIDITY_SETTLED");
(uint8 round, uint256 refundWeth, uint256 penaltyWeth) = ID17Launch(launch).releaseRoundRefund();
uint256 gross = refundWeth + penaltyWeth;
require(gross > 0, "NO_REFUND");
require(position.roundWeth[round] >= gross, "ROUND_WETH_BALANCE");
require(position.wethCommitted >= gross, "LOCKED_WETH_BALANCE");
position.roundWeth[round] -= gross;
position.wethCommitted -= gross;
position.roundRefunded[round] = true;
position.wethRefunded += refundWeth;
position.penaltyPaid += penaltyWeth;
position.residualWeth += refundWeth;
withdrawableWeth += refundWeth;
if (penaltyWeth > 0) accountedWeth -= penaltyWeth;
if (penaltyWeth > 0) weth.safeTransfer(ID17Launch(launch).treasury(), penaltyWeth);
emit RoundRefunded(launch, round, refundWeth, penaltyWeth);
}
function withdrawUnlockedWeth(address launch, uint256 amount) public onlyOwner nonReentrant {
require(amount > 0, "AMOUNT_ZERO");
LockerPosition storage position = positions[launch];
require(amount <= position.residualWeth, "POSITION_WETH_BALANCE");
require(amount <= withdrawableWeth, "WETH_BALANCE");
position.residualWeth -= amount;
withdrawableWeth -= amount;
accountedWeth -= amount;
weth.safeTransfer(owner, amount);
emit WethWithdrawn(launch, amount);
}
function refundFailedLaunch(address launch, bytes32 expectedRulesHash) public onlyOwner nonReentrant {
verifyLaunch(launch, expectedRulesHash);
LockerPosition storage position = positions[launch];
require(position.known, "UNKNOWN_LAUNCH");
require(!position.liquiditySettled, "LIQUIDITY_SETTLED");
uint256 localRefund;
for (uint8 round; round < ROUND_COUNT; round++) localRefund += position.roundWeth[round];
uint256 refundWeth = ID17Launch(launch).releaseFailedRefund();
require(refundWeth == localRefund, "FAILED_REFUND_MISMATCH");
require(position.wethCommitted >= refundWeth, "LOCKED_WETH_BALANCE");
for (uint8 round; round < ROUND_COUNT; round++) {
if (position.roundWeth[round] > 0) {
position.roundWeth[round] = 0;
position.roundRefunded[round] = true;
}
}
position.wethCommitted -= refundWeth;
position.wethRefunded += refundWeth;
position.residualWeth += refundWeth;
withdrawableWeth += refundWeth;
emit FailedLaunchRefunded(launch, refundWeth);
}
function settleAndClaim(address launch, bytes32 expectedRulesHash) public onlyOwner nonReentrant returns (uint256 claimedSaleTokens) {
verifyLaunch(launch, expectedRulesHash);
claimedSaleTokens = _settleVaultPosition(launch);
}
function settleAfterGrace(address launch) public nonReentrant returns (uint256 claimedSaleTokens) {
LockerPosition storage position = positions[launch];
require(position.known, "UNKNOWN_LAUNCH");
verifyLaunch(launch, position.rulesHash);
require(ID17Launch(launch).finalized(), "NOT_FINALIZED");
require(block.timestamp >= ID17Launch(launch).poolCreationOpensAt(), "GRACE_OPEN");
claimedSaleTokens = _settleVaultPosition(launch);
}
function _settleVaultPosition(address launch) internal returns (uint256 claimedSaleTokens) {
LockerPosition storage position = positions[launch];
require(position.known, "UNKNOWN_LAUNCH");
require(!position.liquiditySettled, "LIQUIDITY_SETTLED");
uint256 previewTotal;
uint256 grossCommittedWeth;
for (uint8 round; round < ROUND_COUNT; round++) {
uint256 roundAmount = ID17Launch(launch).previewRoundTokens(address(this), round);
position.roundSaleTokens[round] = roundAmount;
if (roundAmount > 0) position.roundTokensClaimed[round] = true;
previewTotal += roundAmount;
grossCommittedWeth += position.roundWeth[round];
}
// After pool creation the launch routes settlement through the late top-up path:
// identical sale tokens, WETH cost, and fee, with the LP-share WETH still entering
// the official pool alongside the position's reserved LP-token share.
bool late = ID17Launch(launch).liquidityPoolCreated();
uint256 wethForVault;
uint256 treasuryWeth;
uint256 lateLpTokens;
if (late) {
(claimedSaleTokens, wethForVault, treasuryWeth, lateLpTokens) = ID17Launch(launch).claimLateSettlement();
} else {
(claimedSaleTokens, wethForVault, treasuryWeth) = ID17Launch(launch).claimVaultSettlement();
}
require(claimedSaleTokens == previewTotal, "FINAL_CLAIM_MISMATCH");
require(position.wethCommitted >= wethForVault + treasuryWeth, "LOCKED_WETH_BALANCE");
position.liquiditySettled = true;
position.finalSaleTokensClaimed = true;
position.claimedSaleTokens += claimedSaleTokens;
position.withdrawableTokens += claimedSaleTokens;
position.liquidityVault = ID17Launch(launch).liquidityVault();
position.wethSentToVault = wethForVault;
position.wethForLp = wethForVault;
position.treasuryWeth = treasuryWeth;
position.token = ID17Launch(launch).token();
position.wethCommitted -= wethForVault + treasuryWeth;
if (wethForVault > 0) weth.safeTransfer(position.liquidityVault, wethForVault);
if (treasuryWeth > 0) weth.safeTransfer(ID17Launch(launch).treasury(), treasuryWeth);
accountedWeth -= wethForVault + treasuryWeth;
if (late) {
ID17VaultLateLiquidity(position.liquidityVault).mintLateLiquidity(lateLpTokens, wethForVault);
}
position.residualWeth += position.wethCommitted;
withdrawableWeth += position.wethCommitted;
position.wethCommitted = 0;
emit VaultSettlementCompleted(
launch,
position.liquidityVault,
msg.sender,
owner,
claimedSaleTokens,
wethForVault,
treasuryWeth,
grossCommittedWeth,
position.residualWeth
);
}
function withdrawUnlockedTokens(address launch, uint256 amount) public onlyOwner nonReentrant {
require(amount > 0, "AMOUNT_ZERO");
LockerPosition storage position = positions[launch];
require(position.token != address(0), "TOKEN_MISSING");
require(ID17Launch(launch).tradingOpen(), "TOKEN_WITHDRAW_LOCKED");
require(amount <= position.withdrawableTokens, "TOKEN_BALANCE");
position.withdrawableTokens -= amount;
position.token.safeTransfer(owner, amount);
emit ClaimedTokensWithdrawn(launch, amount);
}
function recoverNativeEth(address recipient, uint256 amount) external onlyOwner nonReentrant {
require(recipient != address(0), "RECIPIENT_ZERO");
require(amount > 0, "AMOUNT_ZERO");
require(amount <= address(this).balance, "ETH_BALANCE");
(bool ok, ) = recipient.call{value: amount}("");
require(ok, "ETH_TRANSFER_FAILED");
emit NativeEthRecovered(recipient, amount);
}
function recoverExcessWeth(address recipient, uint256 amount) public onlyOwner nonReentrant {
require(recipient != address(0), "RECIPIENT_ZERO");
require(amount > 0, "AMOUNT_ZERO");
uint256 balance = IWETH(weth).balanceOf(address(this));
require(balance > accountedWeth, "NO_EXCESS_WETH");
require(amount <= balance - accountedWeth, "EXCESS_WETH_BALANCE");
weth.safeTransfer(recipient, amount);
emit ExcessWethRecovered(recipient, amount);
}
}
project/contracts/D17LockerFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {D17Locker} from "./D17Locker.sol";
interface ID17LockerRegistry {
function weth() external view returns (address);
function registerLockerFor(address lockerOwner, address locker) external;
}
contract D17LockerFactory {
address public immutable d17Factory;
event LockerCreated(address indexed owner, address indexed locker);
constructor(address d17Factory_) {
require(d17Factory_ != address(0), "FACTORY_ZERO");
require(d17Factory_.code.length > 0, "FACTORY_NO_CODE");
d17Factory = d17Factory_;
}
function createLockerFor(address lockerOwner) external returns (address locker) {
require(lockerOwner != address(0), "OWNER_ZERO");
require(msg.sender == lockerOwner, "ONLY_SELF");
ID17LockerRegistry registry = ID17LockerRegistry(d17Factory);
locker = address(new D17Locker(lockerOwner, d17Factory, registry.weth()));
registry.registerLockerFor(lockerOwner, locker);
emit LockerCreated(lockerOwner, locker);
}
}
project/contracts/D17TokenFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {D17Token} from "./D17Token.sol";
contract D17TokenFactory {
bytes32 public constant D17_TOKEN_FACTORY_ID = keccak256("D17_TOKEN_FACTORY_V14_1_REFUND_SCHEDULE_BURN_GATE");
address public owner;
address public launchFactory;
bool public launchFactoryPinned;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event LaunchFactoryPinned(address indexed launchFactory);
event TokenCreated(address indexed token, string name, string symbol, uint256 maxSupply);
modifier onlyOwner() {
require(msg.sender == owner, "NOT_OWNER");
_;
}
constructor(address owner_) {
require(owner_ != address(0), "OWNER_ZERO");
owner = owner_;
emit OwnershipTransferred(address(0), owner_);
}
function pinLaunchFactory(address launchFactory_) external onlyOwner {
require(!launchFactoryPinned, "LAUNCH_FACTORY_PINNED");
require(launchFactory_ != address(0), "LAUNCH_FACTORY_ZERO");
require(launchFactory_.code.length > 0, "LAUNCH_FACTORY_NO_CODE");
launchFactory = launchFactory_;
launchFactoryPinned = true;
emit LaunchFactoryPinned(launchFactory_);
}
function renounceOwnership() external onlyOwner {
require(launchFactoryPinned, "LAUNCH_FACTORY_UNLOCKED");
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
function deployToken(address tokenOwner, string calldata name, string calldata symbol, uint256 maxSupply)
external
returns (address token)
{
require(launchFactoryPinned && msg.sender == launchFactory, "NOT_LAUNCH_FACTORY");
token = address(new D17Token(tokenOwner, name, symbol, maxSupply));
emit TokenCreated(token, name, symbol, maxSupply);
}
}
project/contracts/interfaces/ID17.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface ID17Launch {
function D17_LAUNCH_ID() external view returns (bytes32);
function rulesHash() external view returns (bytes32);
function metadataHash() external view returns (bytes32);
function token() external view returns (address);
function weth() external view returns (address);
function treasury() external view returns (address);
function factory() external view returns (address);
function liquidityVault() external view returns (address);
function tradingOpenAt() external view returns (uint256);
function tradingOpen() external view returns (bool);
function liquidityPoolCreated() external view returns (bool);
function settlementStartsAt() external view returns (uint256);
function settlementSeconds() external view returns (uint32);
function poolCreationOpensAt() external view returns (uint256);
function settledLiquidityWeth() external view returns (uint256);
function poolSettledLiquidityWeth() external view returns (uint256);
function poolSettledCommittedWeth() external view returns (uint256);
function lateSettledCommittedWeth() external view returns (uint256);
function lateSettledLiquidityWeth() external view returns (uint256);
function manualDistributionTokens() external view returns (uint256);
function manualDistributionRecipient() external view returns (address);
function activeRound() external view returns (uint8);
function activeRefundWindow() external view returns (uint8);
function finalized() external view returns (bool);
function allFinalCommitmentsSettled() external view returns (bool);
function anchorPriceWad() external view returns (uint256);
function roundBaseTokenAllocation(uint8 round) external view returns (uint256);
function roundTokenAllocation(uint8 round) external view returns (uint256);
function roundSoldTokens(uint8 round) external view returns (uint256);
function roundAnchorTargetWeth(uint8 round) external view returns (uint256);
function roundAnchorUnderfillRemainingWeth(uint8 round) external view returns (uint256);
function recordRoundCommitment(uint8 round, uint256 amount) external;
function releaseRoundRefund() external returns (uint8 round, uint256 refundWeth, uint256 penaltyWeth);
function releaseFailedRefund() external returns (uint256 refundWeth);
function claimVaultSettlement() external returns (uint256 saleTokens, uint256 wethForVault, uint256 treasuryWeth);
function claimLateSettlement()
external
returns (uint256 saleTokens, uint256 wethForVault, uint256 treasuryWeth, uint256 lateLpTokens);
function finalizeLaunch() external;
function claimVaultLiquidityTokens() external returns (uint256 liquidityTokens, uint256 wethForPool);
function markLiquidityPoolCreated(address pair, uint256 tokenUsed, uint256 wethUsed, uint256 lpMinted) external;
function previewRoundTokens(address locker, uint8 round) external view returns (uint256 saleTokens);
function previewFinalSaleTokens(address locker) external view returns (uint256 saleTokens);
function previewVaultSettlement(address locker)
external
view
returns (uint256 saleTokens, uint256 grossCommittedWeth, uint256 wethForVault, uint256 treasuryWeth);
}
interface ID17VaultLateLiquidity {
function mintLateLiquidity(uint256 tokenAmount, uint256 wethAmount) external returns (uint256 liquidity);
}
interface ID17FactoryView {
function isLocker(address locker) external view returns (bool);
function isCanonicalLaunch(address launch, bytes32 rulesHash) external view returns (bool);
}
interface IWETH {
function deposit() external payable;
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
interface IERC20BalanceView {
function balanceOf(address account) external view returns (uint256);
}
interface IV2Router {
function factory() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);
}
interface IV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IV2PairView {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function token0() external view returns (address);
function token1() external view returns (address);
function totalSupply() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function balanceOf(address account) external view returns (uint256);
}
interface ID17TokenTradingGateLaunch {
function tradingOpen() external view returns (bool);
}
project/contracts/interfaces/ID17LaunchFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface ID17LaunchFactory {
struct Link {
string linkType;
string url;
}
struct LaunchConfig {
string tokenName;
string tokenSymbol;
string description;
string logoSvgUri;
Link[] links;
uint256 tokenSupply;
uint256 saleTokens;
uint256 lpTokens;
uint256 manualDistributionTokens;
uint256 deadTokens;
address deadRecipient;
address treasury;
uint64 startTime;
uint32[5] roundSeconds;
uint32 refundSeconds;
uint32 settlementSeconds;
uint256 minCommitWeth;
uint256 minPhase1Weth;
uint256 minAnchorPriceWad;
uint16[5] roundSharesBps;
uint16 treasuryBps;
uint16 refundPenaltyBps;
bool burnUnsoldSaleTokens;
}
function deployLaunch(LaunchConfig calldata config, address creator)
external
returns (address token, address launch, address liquidityVault);
}
project/contracts/lib/D17SafeTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
library D17SafeTransfer {
error TransferFailed();
error TransferFromFailed();
error ApproveFailed();
error BurnFailed();
function safeTransfer(address token, address to, uint256 amount) internal {
(bool ok, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, amount));
if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
}
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
(bool ok, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, amount));
if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFromFailed();
}
function safeApprove(address token, address spender, uint256 amount) internal {
(bool ok, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, spender, amount));
if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert ApproveFailed();
}
function safeBurn(address token, uint256 amount) internal {
(bool ok, bytes memory data) = token.call(abi.encodeWithSignature("burn(uint256)", amount));
if (!ok || (data.length != 0 && !abi.decode(data, (bool)))) revert BurnFailed();
}
}
project/contracts/test/TestERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract TestERC20 {
string public name;
string public symbol;
uint8 public immutable decimals;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(string memory name_, string memory symbol_, uint8 decimals_) {
name = name_;
symbol = symbol_;
decimals = decimals_;
}
function transfer(address to, uint256 amount) external returns (bool) {
_transfer(msg.sender, to, amount);
return true;
}
function approve(address spender, uint256 amount) external returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount) external returns (bool) {
uint256 allowed = allowance[from][msg.sender];
if (allowed != type(uint256).max) {
require(allowed >= amount, "ALLOWANCE");
unchecked {
allowance[from][msg.sender] = allowed - amount;
}
}
_transfer(from, to, amount);
return true;
}
function _mint(address to, uint256 amount) internal {
require(to != address(0), "TO_ZERO");
totalSupply += amount;
balanceOf[to] += amount;
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal {
require(balanceOf[from] >= amount, "BALANCE");
unchecked {
balanceOf[from] -= amount;
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
function _transfer(address from, address to, uint256 amount) internal {
require(to != address(0), "TO_ZERO");
require(balanceOf[from] >= amount, "BALANCE");
unchecked {
balanceOf[from] -= amount;
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
}
}
project/contracts/test/TestV2Factory.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {TestV2Pair} from "./TestV2Pair.sol";
contract TestV2Factory {
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
event PairCreated(address indexed token0, address indexed token1, address pair, uint256 allPairsLength);
function allPairsLength() external view returns (uint256) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) public returns (address pair) {
require(tokenA != tokenB, "IDENTICAL");
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "ZERO");
require(getPair[token0][token1] == address(0), "PAIR_EXISTS");
pair = address(new TestV2Pair(token0, token1));
getPair[token0][token1] = pair;
getPair[token1][token0] = pair;
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
}
project/contracts/test/TestV2Pair.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {TestERC20} from "./TestERC20.sol";
interface ITestPairToken {
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
}
contract TestV2Pair is TestERC20 {
address public immutable token0;
address public immutable token1;
uint256 private reserve0;
uint256 private reserve1;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Swap(address indexed sender, uint256 amount0Out, uint256 amount1Out, address indexed to);
event Sync(uint256 reserve0, uint256 reserve1);
constructor(address token0_, address token1_) TestERC20("Test V2 LP", "TV2-LP", 18) {
require(token0_ != token1_, "IDENTICAL");
require(token0_ != address(0), "ZERO");
token0 = token0_;
token1 = token1_;
}
function getReserves() external view returns (uint112, uint112, uint32) {
require(reserve0 <= type(uint112).max && reserve1 <= type(uint112).max, "RESERVE_OVERFLOW");
return (uint112(reserve0), uint112(reserve1), uint32(block.timestamp));
}
function mint(address to) external returns (uint256 liquidity) {
uint256 balance0 = ITestPairToken(token0).balanceOf(address(this));
uint256 balance1 = ITestPairToken(token1).balanceOf(address(this));
uint256 amount0 = balance0 - reserve0;
uint256 amount1 = balance1 - reserve1;
if (totalSupply == 0) {
liquidity = _sqrt(amount0 * amount1);
} else {
liquidity = _min(amount0 * totalSupply / reserve0, amount1 * totalSupply / reserve1);
}
require(liquidity > 0, "INSUFFICIENT_LIQUIDITY");
_mint(to, liquidity);
reserve0 = balance0;
reserve1 = balance1;
emit Mint(msg.sender, amount0, amount1);
emit Sync(balance0, balance1);
}
function swap(uint256 amount0Out, uint256 amount1Out, address to) external {
require(amount0Out > 0 || amount1Out > 0, "NO_OUTPUT");
require(amount0Out < reserve0 && amount1Out < reserve1, "LIQUIDITY");
if (amount0Out > 0) require(ITestPairToken(token0).transfer(to, amount0Out), "TOKEN0_OUT");
if (amount1Out > 0) require(ITestPairToken(token1).transfer(to, amount1Out), "TOKEN1_OUT");
uint256 balance0 = ITestPairToken(token0).balanceOf(address(this));
uint256 balance1 = ITestPairToken(token1).balanceOf(address(this));
reserve0 = balance0;
reserve1 = balance1;
emit Swap(msg.sender, amount0Out, amount1Out, to);
emit Sync(balance0, balance1);
}
function skim(address to) external {
uint256 balance0 = ITestPairToken(token0).balanceOf(address(this));
uint256 balance1 = ITestPairToken(token1).balanceOf(address(this));
if (balance0 > reserve0) require(ITestPairToken(token0).transfer(to, balance0 - reserve0), "TOKEN0_SKIM");
if (balance1 > reserve1) require(ITestPairToken(token1).transfer(to, balance1 - reserve1), "TOKEN1_SKIM");
}
function _sqrt(uint256 y) private pure returns (uint256 z) {
if (y == 0) return 0;
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
}
function _min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
}
project/contracts/test/TestV2Router.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {TestV2Factory} from "./TestV2Factory.sol";
import {TestV2Pair} from "./TestV2Pair.sol";
interface ITestRouterToken {
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
contract TestV2Router {
address public immutable factory;
constructor(address factory_) {
require(factory_ != address(0), "FACTORY_ZERO");
factory = factory_;
}
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB, uint256 liquidity) {
require(block.timestamp <= deadline, "EXPIRED");
address pair = TestV2Factory(factory).getPair(tokenA, tokenB);
if (pair == address(0)) pair = TestV2Factory(factory).createPair(tokenA, tokenB);
(uint256 reserveA, uint256 reserveB) = getReserves(tokenA, tokenB);
(amountA, amountB) = _quoteAddLiquidity(amountADesired, amountBDesired, amountAMin, amountBMin, reserveA, reserveB);
require(ITestRouterToken(tokenA).transferFrom(msg.sender, pair, amountA), "TOKEN_A_TRANSFER");
require(ITestRouterToken(tokenB).transferFrom(msg.sender, pair, amountB), "TOKEN_B_TRANSFER");
liquidity = TestV2Pair(pair).mint(to);
}
function getReserves(address tokenA, address tokenB) public view returns (uint256 reserveA, uint256 reserveB) {
address pair = TestV2Factory(factory).getPair(tokenA, tokenB);
if (pair == address(0)) return (0, 0);
(uint112 reserve0, uint112 reserve1, ) = TestV2Pair(pair).getReserves();
(address token0, ) = _sortTokens(tokenA, tokenB);
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function swapExactTokensForTokens(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOut,
address to
) external {
address pair = TestV2Factory(factory).getPair(tokenIn, tokenOut);
require(pair != address(0), "PAIR");
require(ITestRouterToken(tokenIn).transferFrom(msg.sender, pair, amountIn), "TOKEN_IN_TRANSFER");
address token0 = TestV2Pair(pair).token0();
if (tokenOut == token0) {
TestV2Pair(pair).swap(amountOut, 0, to);
} else {
TestV2Pair(pair).swap(0, amountOut, to);
}
}
function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) public pure returns (uint256) {
require(amountA > 0, "AMOUNT");
require(reserveA > 0 && reserveB > 0, "RESERVES");
return amountA * reserveB / reserveA;
}
function _quoteAddLiquidity(
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
uint256 reserveA,
uint256 reserveB
) private pure returns (uint256 amountA, uint256 amountB) {
if (reserveA == 0 && reserveB == 0) {
amountA = amountADesired;
amountB = amountBDesired;
} else {
uint256 amountBOptimal = quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, "B_MIN");
amountA = amountADesired;
amountB = amountBOptimal;
} else {
uint256 amountAOptimal = quote(amountBDesired, reserveB, reserveA);
require(amountAOptimal >= amountAMin, "A_MIN");
amountA = amountAOptimal;
amountB = amountBDesired;
}
}
require(amountA >= amountAMin && amountB >= amountBMin, "MIN");
}
function _sortTokens(address tokenA, address tokenB) private pure returns (address token0, address token1) {
require(tokenA != tokenB, "IDENTICAL");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "ZERO");
}
}
project/contracts/test/TestWETH.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {TestERC20} from "./TestERC20.sol";
contract TestWETH is TestERC20 {
event Deposit(address indexed account, uint256 amount);
event Withdrawal(address indexed account, uint256 amount);
constructor() TestERC20("Wrapped Test Ether", "WETH", 18) {}
receive() external payable {
deposit();
}
function deposit() public payable {
require(msg.value > 0, "NO_ETH");
_mint(msg.sender, msg.value);
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 amount) external {
_burn(msg.sender, amount);
(bool ok, ) = msg.sender.call{value: amount}("");
require(ok, "ETH_SEND");
emit Withdrawal(msg.sender, amount);
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "none"
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.