Verified contractPartialMIT
PeddlesStockSwapRouter
Address0x515b57acb914e298ea7bdc6acebbf6df4ae81978
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,374,023
- Creation transaction
- 0x9e622ffd1f…be47ec150e
src/PeddlesStockSwapRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/*
_______ _______ ______ ______ _ _______
( ____ )( ____ \( __ \ ( __ \ ( \ ( ____ \( ____ \
| ( )|| ( \/| ( \ )| ( \ )| ( | ( \/| ( \/
| (____)|| (__ | | ) || | ) || | | (__ | (_____
| _____)| __) | | | || | | || | | __) (_____ )
| ( | ( | | ) || | ) || | | ( ) |
| ) | (____/\| (__/ )| (__/ )| (____/\| (____/\/\____) |
|/ (_______/(______/ (______/ (_______/(_______/\_______)
THE STOCK-PAIRED LAUNCHPAD
Launch tokens and NFTs paired against tokenised stocks.
100% of supply goes to liquidity, locked from block zero.
Holders earn the stock you are paired to.
Website https://peddles.xyz
X https://x.com/PeddlesX
Telegram https://t.me/peddlesnews
*/
interface IStockRouterERC20 {
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function balanceOf(address owner) external view returns (uint256);
}
interface IStockRouterLaunchpad {
function coins(address token)
external
view
returns (
address creator,
address quote,
bytes32 poolId,
uint256 positionId,
uint64 createdAt,
bool tokenIsCurrency0
);
}
struct StockRouterPoolKey {
address currency0;
address currency1;
uint24 fee;
int24 tickSpacing;
address hooks;
}
struct StockRouterSwapParams {
bool zeroForOne;
int256 amountSpecified;
uint160 sqrtPriceLimitX96;
}
interface IStockRouterPoolManager {
function unlock(bytes calldata data) external returns (bytes memory);
function swap(StockRouterPoolKey calldata key, StockRouterSwapParams calldata params, bytes calldata hookData)
external
returns (int256 delta);
function sync(address currency) external;
function settle() external payable returns (uint256 paid);
function take(address currency, address to, uint256 amount) external;
}
/// @title PeddlesStockSwapRouter
/// @notice Fee-charging trading for STOCK-QUOTE-paired Peddles pools (the Fair Stocks product),
/// closing the revenue gap where stock-paired tokens traded through a generic v4 router and the
/// platform earned nothing.
///
/// It mirrors the WETH router's economics with config-driven params:
/// - a trade fee (default 1.5%, hard-capped at 5%) to treasury;
/// - a trade fee, hard-capped at MAX_FEE_BPS (5%), split creator/treasury (default 50/50);
/// - two-sided denomination: fees taken in the QUOTE asset on buys, in the TOKEN on sells;
/// - flywheel routing: a slice of the treasury's QUOTE cut is sent to the flywheel address.
///
/// WHETHER THIS ROUTER CHARGES AT ALL DEPENDS ON `poolHook`.
///
/// This used to say stock pools were created hookless and "stay that way". That is no longer
/// true: PeddlesStockLaunchpad builds its PoolKey with `hooks: feeHook`, so its pools carry
/// PeddlesFeeHook, which charges the protocol fee inside `beforeSwap` on EVERY swap regardless
/// of router — which is the point of having a hook at all.
///
/// * `poolHook == address(0)` (hookless pools): this router is the ONLY collector, so it
/// charges `tradeFeeBps` and records fees out-of-band in its own pull-based ledger,
/// reading the coin's creator from the launchpad. Creators/treasury claim via claim().
/// * `poolHook != address(0)` (hooked pools): the HOOK is the collector, and this router is
/// forbidden from charging anything (`FeeStackingForbidden`, enforced in the constructor
/// and in setFeeConfig). Both charging would bill a trader twice on one trade.
///
/// The ledger, claim() and the flywheel routing below therefore only ever hold funds on the
/// hookless configuration. They remain live and claimable either way — a balance accrued while
/// hookless does not become unreachable.
contract PeddlesStockSwapRouter {
uint16 public constant BPS = 10_000;
uint16 public constant MAX_FEE_BPS = 500; // 5% hard cap on the trade fee
uint16 public constant MAX_CREATOR_FEE_BPS = 500; // 5% hard cap on the creator fee
uint160 private constant MIN_SQRT_PRICE_LIMIT = 4295128740;
uint160 private constant MAX_SQRT_PRICE_LIMIT = 1461446703485210103287273052203988822378723970341;
address public owner;
address public treasury;
address public immutable poolManager;
IStockRouterLaunchpad public immutable launchpad;
// Pool shape (must match PeddlesStockLaunchpad: POOL_FEE / TICK_SPACING / hookless).
uint24 public immutable poolFee;
int24 public immutable poolTickSpacing;
address public immutable poolHook;
// Config-driven fees.
//
// ONE FEE (2026-09-03): `tradeFeeBps` is the ONLY charge. It is split creatorShareBps to the
// creator and the exact remainder to the treasury. It used to stack with a separate
// `creatorFeeBps`, so a buyer paid tradeFeeBps + creatorFeeBps (2.5% at the old defaults);
// that is gone. A trader now pays exactly tradeFeeBps, capped by MAX_FEE_BPS.
uint16 public tradeFeeBps = 100; // 1% — the single, total fee
/// @notice DEPRECATED and NOT CHARGED. Retained only so the constructor / setFeeConfig ABI
/// (and the deploy scripts that use it) keep working. It is read nowhere in buy() or sell(),
/// so no owner call can reintroduce a second, stacking fee. Use effectiveCreatorFeeBps().
uint16 public creatorFeeBps = 150;
uint16 public creatorShareBps = 5_000; // creator's share of the ONE fee; treasury takes the rest
// Flywheel (WETH-only buyback): receives a slice of the treasury QUOTE cut. Since the fee is
// in the quote asset (not WETH), the owner sweeps it from the flywheel to convert to WETH.
uint16 public constant MAX_FLYWHEEL_SHARE_BPS = 10_000;
address public flywheel;
uint16 public flywheelShareBps;
// Pull-based fee ledger (mirrors the launchpad's). USER FUNDS.
mapping(address => mapping(address => uint256)) public pendingQuote; // token => account => quote owed
mapping(address => mapping(address => uint256)) public pendingToken; // token => account => token owed
// Aggregate obligations per ASSET, so rescueToken() can never reach the creator ledger.
// reservedQuote is keyed by the QUOTE asset (shared across many coins); reservedToken by the
// coin token itself. An asset that is both is covered by the sum of the two.
mapping(address => uint256) public reservedQuote;
mapping(address => uint256) public reservedToken;
// ---- Treasury auto-sweep (batching) -------------------------------------------------
// Every trade still routes 100% of the treasury cut to the treasury, but BATCHED: the cut is
// accrued per quote asset and pushed automatically by the first trade that brings the pending
// balance to or above that asset's threshold. A dust trade does not pay for its own transfer;
// the trade that crosses the line pays it and pushes the WHOLE accrued amount. No keeper.
//
// THRESHOLDS ARE PER-ASSET BECAUSE DECIMALS DIFFER. This router quotes against many assets:
// on Robinhood Chain mainnet USDG is 6 decimals while the stock tokens are 18. A single
// 18-decimal constant applied to USDG would mean ten billion whole tokens.
/// @notice Default sweep minimum, in base units, FOR 18-DECIMAL ASSETS ONLY.
/// 0.01 ether == 1e16. A 6-decimal quote MUST be configured explicitly:
/// setTreasuryThreshold(USDG, 10_000) == 0.01 USDG. Never assume 18.
uint256 public constant DEFAULT_TREASURY_THRESHOLD = 0.01 ether; // 1e16 base units (18dp)
/// @dev 0 = use DEFAULT_TREASURY_THRESHOLD, 1 = push on every trade, n = accrue to n units.
mapping(address => uint256) public pendingTreasury;
mapping(address => uint256) public treasuryThresholdOverride;
uint256 private locked;
error NotOwner();
error Locked();
error InvalidAddress();
error InvalidFee();
/// @notice A router that trades HOOKED pools must not also charge its own fee.
error FeeStackingForbidden();
error InvalidAmount();
error UnknownCoin();
error Slippage();
error NoOutput();
error BadCallback();
error TransferFailed();
error NothingToClaim();
error NothingPending();
error ReservedBalance();
event TreasuryUpdated(address indexed treasury);
event FeeConfigUpdated(uint16 tradeFeeBps, uint16 creatorFeeBps, uint16 creatorShareBps);
event FlywheelUpdated(address indexed flywheel);
event FlywheelShareUpdated(uint16 flywheelShareBps);
event FlywheelFunded(address indexed flywheel, address indexed quote, uint256 amount);
event TradeFeeCollected(address indexed payer, address indexed token, address indexed quote, uint256 amount);
event CreatorFeeAccrued(address indexed token, address indexed creator, uint256 quoteAmount, uint256 tokenAmount);
event Bought(address indexed payer, address indexed token, uint256 quoteIn, uint256 tokenOut, address to);
event Sold(address indexed payer, address indexed token, uint256 tokenIn, uint256 quoteOut, address to);
event FeesClaimed(address indexed token, address indexed account, uint256 quoteAmount, uint256 tokenAmount);
event TreasuryThresholdUpdated(address indexed asset, uint256 threshold);
event TreasuryAccrued(address indexed asset, uint256 amount, uint256 pending);
event TreasurySwept(address indexed asset, address indexed to, uint256 amount, bool automatic);
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
modifier nonReentrant() {
if (locked != 0) revert Locked();
locked = 1;
_;
locked = 0;
}
/// @param initialOwner The administrative owner. AN EXPLICIT PARAMETER, NOT `msg.sender`:
/// this router's address is CREATE2-mined for the `1978` vanity suffix, and under CREATE2
/// `msg.sender` is the deterministic-deployment proxy (0x4e59b448...), which nobody controls.
/// Taking the owner from `msg.sender` would deploy a permanently unadministrable router.
constructor(
address initialOwner,
address treasury_,
address poolManager_,
address launchpad_,
uint24 poolFee_,
int24 poolTickSpacing_,
address poolHook_,
uint16 tradeFeeBps_,
uint16 creatorFeeBps_
) {
if (initialOwner == address(0)) revert InvalidAddress();
if (treasury_ == address(0) || poolManager_ == address(0) || launchpad_ == address(0)) revert InvalidAddress();
if (tradeFeeBps_ > MAX_FEE_BPS || creatorFeeBps_ > MAX_CREATOR_FEE_BPS) revert InvalidFee();
// NO STACKING, ENFORCED STRUCTURALLY.
//
// When `poolHook_` is set, the pools this router trades carry PeddlesFeeHook, which
// charges the protocol fee inside `beforeSwap` on EVERY swap regardless of router —
// that is the entire point of the hook. This router deducts its own `tradeFeeBps` from
// the input BEFORE swapping, so if both were active a trader would pay the router's fee
// AND the hook's fee on the same trade: up to 1% + 5% = 6%.
//
// That is exactly the stacking this contract's header says was removed in 2026-09-03,
// silently reintroduced the moment the launchpad started building its PoolKey with the
// hook. It is refused here rather than left to deploy configuration, because a
// configuration mistake here overcharges every trader on every trade and nothing in the
// system would notice.
if (poolHook_ != address(0) && tradeFeeBps_ != 0) revert FeeStackingForbidden();
require(poolTickSpacing_ > 0, "BAD_TICK_SPACING");
owner = initialOwner;
treasury = treasury_;
poolManager = poolManager_;
launchpad = IStockRouterLaunchpad(launchpad_);
poolFee = poolFee_;
poolTickSpacing = poolTickSpacing_;
poolHook = poolHook_;
tradeFeeBps = tradeFeeBps_;
creatorFeeBps = creatorFeeBps_;
}
// ---- Admin ---------------------------------------------------------------
function transferOwnership(address nextOwner) external onlyOwner {
if (nextOwner == address(0)) revert InvalidAddress();
owner = nextOwner;
}
function setTreasury(address t) external onlyOwner {
if (t == address(0)) revert InvalidAddress();
treasury = t;
emit TreasuryUpdated(t);
}
/// @notice Owner-settable, bounded fee config.
/// @param tradeFeeBps_ the SINGLE total fee a trader pays, hard-capped at MAX_FEE_BPS (5%).
/// @param creatorFeeBps_ DEPRECATED — stored for ABI compatibility, charged nowhere. It cannot
/// increase what a trader pays; the total is always tradeFeeBps_.
/// @param creatorShareBps_ the creator's share OF tradeFeeBps_; treasury takes the remainder.
function setFeeConfig(uint16 tradeFeeBps_, uint16 creatorFeeBps_, uint16 creatorShareBps_) external onlyOwner {
// Same invariant as the constructor: a hooked router can never charge its own fee.
if (poolHook != address(0) && tradeFeeBps_ != 0) revert FeeStackingForbidden();
if (tradeFeeBps_ > MAX_FEE_BPS || creatorFeeBps_ > MAX_CREATOR_FEE_BPS || creatorShareBps_ > BPS) {
revert InvalidFee();
}
tradeFeeBps = tradeFeeBps_;
creatorFeeBps = creatorFeeBps_;
creatorShareBps = creatorShareBps_;
emit FeeConfigUpdated(tradeFeeBps_, creatorFeeBps_, creatorShareBps_);
}
function setFlywheel(address f) external onlyOwner {
flywheel = f;
emit FlywheelUpdated(f);
}
function setFlywheelShareBps(uint16 bps) external onlyOwner {
if (bps > MAX_FLYWHEEL_SHARE_BPS) revert InvalidFee();
flywheelShareBps = bps;
emit FlywheelShareUpdated(bps);
}
// ---- Trading -------------------------------------------------------------
/// @notice Buy `token` with its stock `quote`. Fees are taken in the quote asset.
function buy(address token, uint256 quoteIn, uint256 minTokenOut, address to)
external
nonReentrant
returns (uint256 tokenOut)
{
if (token == address(0) || to == address(0)) revert InvalidAddress();
if (quoteIn == 0) revert InvalidAmount();
(address creator, address quote) = _coin(token);
// Checked: the same file already checks every `transfer` return (:320, :359, :389).
// A quote token that returns false instead of reverting would otherwise let a caller
// buy without paying, settling the swap out of other creators' unclaimed fees.
if (!IStockRouterERC20(quote).transferFrom(msg.sender, address(this), quoteIn)) revert TransferFailed();
// ---- ONE fee, then split ----
// The buyer pays exactly tradeFeeBps of the input. The treasury takes the exact
// REMAINDER of that one fee, never a second independent multiplication, so integer
// truncation cannot strand dust in the router: creatorPortion + treasuryCut == totalFee.
uint256 totalFee = (quoteIn * tradeFeeBps) / BPS;
uint256 creatorPortion = (totalFee * creatorShareBps) / BPS;
uint256 treasuryCut = totalFee - creatorPortion;
if (creatorPortion > 0) {
pendingQuote[token][creator] += creatorPortion;
reservedQuote[quote] += creatorPortion;
emit CreatorFeeAccrued(token, creator, creatorPortion, 0);
}
_routeTreasuryQuote(quote, treasuryCut);
if (totalFee > 0) emit TradeFeeCollected(msg.sender, token, quote, totalFee);
uint256 amountIn = quoteIn - totalFee;
if (amountIn == 0) revert InvalidAmount();
StockRouterPoolKey memory key = _poolKey(token, quote);
bool zeroForOne = key.currency0 == quote; // quote in
uint256 spent;
(tokenOut, spent) = _swapExactInput(key, zeroForOne, amountIn, minTokenOut, to);
// NO STUCK INPUT. A swap that exhausts the pool's liquidity settles only what it consumed;
// the rest goes straight back to the payer instead of sitting here unreserved, where only
// the owner's `rescueToken` could reach it.
if (spent < amountIn && !IStockRouterERC20(quote).transfer(msg.sender, amountIn - spent)) {
revert TransferFailed();
}
emit Bought(msg.sender, token, quoteIn, tokenOut, to);
}
/// @notice Sell `token` for its stock `quote`. Creator fee is taken in the TOKEN; the trade fee
/// is taken from the quote proceeds.
function sell(address token, uint256 tokenIn, uint256 minQuoteOut, address to)
external
nonReentrant
returns (uint256 quoteOut)
{
if (token == address(0) || to == address(0)) revert InvalidAddress();
if (tokenIn == 0) revert InvalidAmount();
(address creator, address quote) = _coin(token);
if (!IStockRouterERC20(token).transferFrom(msg.sender, address(this), tokenIn)) revert TransferFailed();
// ---- ONE fee, then split ----
// Taken in the TOKEN so the creator's share stays token-denominated. There is no second
// fee on the quote proceeds: the seller pays exactly tradeFeeBps.
uint256 totalFeeToken = (tokenIn * tradeFeeBps) / BPS;
uint256 creatorPortionToken = (totalFeeToken * creatorShareBps) / BPS;
if (creatorPortionToken > 0) {
pendingToken[token][creator] += creatorPortionToken;
reservedToken[token] += creatorPortionToken;
}
if (totalFeeToken > 0) emit CreatorFeeAccrued(token, creator, 0, creatorPortionToken);
if (tokenIn == totalFeeToken) revert InvalidAmount();
quoteOut = _sellSwap(
token,
quote,
tokenIn - totalFeeToken,
totalFeeToken - creatorPortionToken, // the treasury's exact remainder
tokenIn - creatorPortionToken,
minQuoteOut,
to
);
emit Sold(msg.sender, token, tokenIn, quoteOut, to);
}
/// @dev The swap legs of `sell`, in their own frame so `sell` stays within the legacy stack.
/// `swappable` is everything that was meant to reach the pool (the seller's leg plus the
/// treasury's slice); whatever the pool did not consume goes back to the seller.
function _sellSwap(
address token,
address quote,
uint256 tokenToSwap,
uint256 treasuryPortionToken,
uint256 swappable,
uint256 minQuoteOut,
address to
) private returns (uint256 quoteOut) {
StockRouterPoolKey memory key = _poolKey(token, quote);
bool zeroForOne = key.currency0 == token; // token in
uint256 spent;
(quoteOut, spent) = _swapExactInput(key, zeroForOne, tokenToSwap, 0, address(this));
if (quoteOut == 0) revert NoOutput();
if (quoteOut < minQuoteOut) revert Slippage();
// Settle the treasury's slice in the QUOTE asset so it is pushed automatically rather
// than left as a token balance someone has to claim.
if (treasuryPortionToken > 0) {
spent += _settleTreasuryPortion(key, zeroForOne, token, quote, treasuryPortionToken);
}
if (!IStockRouterERC20(quote).transfer(to, quoteOut)) revert TransferFailed();
// NO STUCK INPUT. Tokens a thin pool did not consume (a partial fill) go back to the seller
// instead of sitting here unreserved, where only the owner's `rescueToken` could reach them.
spent = swappable - spent;
if (spent > 0 && !IStockRouterERC20(token).transfer(msg.sender, spent)) revert TransferFailed();
}
/// @dev Swap the treasury's token slice to quote and route it; returns what the pool consumed.
/// Its own frame keeps `sell` within the stack.
function _settleTreasuryPortion(
StockRouterPoolKey memory key,
bool zeroForOne,
address token,
address quote,
uint256 portion
) private returns (uint256 spent) {
uint256 treasuryQuote;
(treasuryQuote, spent) = _swapExactInput(key, zeroForOne, portion, 0, address(this));
if (treasuryQuote > 0) {
_routeTreasuryQuote(quote, treasuryQuote);
emit TradeFeeCollected(msg.sender, token, quote, treasuryQuote);
}
}
/// @notice Claim accrued quote + token fees for `token`.
function claim(address token) external nonReentrant returns (uint256 quoteAmount, uint256 tokenAmount) {
(, address quote) = _coin(token);
quoteAmount = pendingQuote[token][msg.sender];
tokenAmount = pendingToken[token][msg.sender];
if (quoteAmount == 0 && tokenAmount == 0) revert NothingToClaim();
pendingQuote[token][msg.sender] = 0;
pendingToken[token][msg.sender] = 0;
if (quoteAmount > 0) reservedQuote[quote] -= quoteAmount;
if (tokenAmount > 0) reservedToken[token] -= tokenAmount;
if (quoteAmount > 0 && !IStockRouterERC20(quote).transfer(msg.sender, quoteAmount)) revert TransferFailed();
if (tokenAmount > 0 && !IStockRouterERC20(token).transfer(msg.sender, tokenAmount)) revert TransferFailed();
emit FeesClaimed(token, msg.sender, quoteAmount, tokenAmount);
}
function pendingFees(address token, address account) external view returns (uint256 quoteAmount, uint256 tokenAmount) {
return (pendingQuote[token][account], pendingToken[token][account]);
}
// ---- Internals -----------------------------------------------------------
function _coin(address token) internal view returns (address creator, address quote) {
(creator, quote,,,,) = launchpad.coins(token);
if (creator == address(0) || quote == address(0)) revert UnknownCoin();
}
/// @dev Flywheel slice first (immediate, unchanged); the treasury takes the remainder,
/// accrued and auto-pushed once it clears that asset's threshold.
function _routeTreasuryQuote(address quote, uint256 amount) internal {
if (amount == 0) return;
address fw = flywheel;
uint16 share = flywheelShareBps;
uint256 toFlywheel;
if (fw != address(0) && share > 0) toFlywheel = (amount * share) / BPS;
if (toFlywheel > 0) {
if (!IStockRouterERC20(quote).transfer(fw, toFlywheel)) revert TransferFailed();
emit FlywheelFunded(fw, quote, toFlywheel);
}
uint256 toTreasury = amount - toFlywheel;
_accrueTreasury(quote, toTreasury);
}
// ---- Treasury threshold config + auto-sweep -------------------------------------------
/// @notice Effective sweep threshold for `asset`, in that asset's BASE UNITS.
function treasuryThresholdFor(address asset) public view returns (uint256) {
uint256 t = treasuryThresholdOverride[asset];
return t == 0 ? DEFAULT_TREASURY_THRESHOLD : t;
}
/// @notice Set the per-asset auto-sweep minimum, in that asset's OWN base units.
/// @dev Example, a 6-decimal quote: setTreasuryThreshold(USDG, 10_000) == 0.01 USDG.
/// Cannot redirect funds — it only sets WHEN the accrued cut is pushed to `treasury`.
function setTreasuryThreshold(address asset, uint256 threshold) external onlyOwner {
treasuryThresholdOverride[asset] = threshold;
emit TreasuryThresholdUpdated(asset, threshold);
}
/// @dev Accrue the treasury's cut and push the WHOLE pending balance once it reaches the
/// asset's threshold. Never touches pendingQuote/pendingToken — those are creator funds.
function _accrueTreasury(address asset, uint256 amount) internal {
if (amount == 0) return;
uint256 pending = pendingTreasury[asset] + amount;
if (pending >= treasuryThresholdFor(asset)) {
pendingTreasury[asset] = 0;
if (!IStockRouterERC20(asset).transfer(treasury, pending)) revert TransferFailed();
emit TreasurySwept(asset, treasury, pending, true);
} else {
pendingTreasury[asset] = pending;
emit TreasuryAccrued(asset, amount, pending);
}
}
/// @notice PERMISSIONLESS. Push an asset's pending treasury balance to `treasury` regardless
/// of threshold, so a below-threshold balance can never be trapped. There is no recipient
/// parameter by design: it can only ever pay `treasury`.
function sweepTreasury(address asset) external nonReentrant returns (uint256 amount) {
amount = pendingTreasury[asset];
if (amount == 0) revert NothingPending();
pendingTreasury[asset] = 0;
if (!IStockRouterERC20(asset).transfer(treasury, amount)) revert TransferFailed();
emit TreasurySwept(asset, treasury, amount, false);
}
/// @notice PERMISSIONLESS. Push any NATIVE balance to `treasury`.
///
/// This router has no `receive`, no `fallback` and no payable function, so nothing
/// can pay it natively on purpose. Native can still be FORCED in — `selfdestruct`
/// credits any address whether it consents or not, and so does being named a
/// block's fee recipient — and before this existed that balance had no exit at
/// all: `sweepTreasury` and `rescueToken` both go through ERC20 `transfer`, which
/// native currency has no interface for. A contract that can hold value must have
/// the exact function that gets it out; this is that function for the native leg.
///
/// Permissionless and recipient-less for the same reason as `sweepTreasury`: it
/// can only ever pay `treasury`, so calling it is never profitable to the caller,
/// and gating it would only add a way for the rescue to become impossible if a key
/// were lost. It can never take money the router owes, because nothing in the
/// ledger is denominated in native — `reservedBalance` is ERC20-only.
///
/// `address(0)` stands for the native leg in the event, matching the convention
/// used by the sweeps on the other Peddles contracts.
function sweepNative() external nonReentrant returns (uint256 amount) {
amount = address(this).balance;
if (amount == 0) revert NothingPending();
(bool ok,) = payable(treasury).call{value: amount}("");
if (!ok) revert TransferFailed();
emit TreasurySwept(address(0), treasury, amount, false);
}
/// @notice The creator's slice of the ONE fee, in bps of the trade (UI helper).
function effectiveCreatorFeeBps() external view returns (uint16) {
return uint16((uint256(tradeFeeBps) * creatorShareBps) / BPS);
}
/// @notice Balance of `asset` this router owes to creators and to the treasury ledger.
function reservedBalance(address asset) public view returns (uint256) {
return pendingTreasury[asset] + reservedQuote[asset] + reservedToken[asset];
}
function _swapExactInput(
StockRouterPoolKey memory key,
bool zeroForOne,
uint256 amountIn,
uint256 minOut,
address recipient
) internal returns (uint256 out, uint256 spent) {
bytes memory ret =
IStockRouterPoolManager(poolManager).unlock(abi.encode(key, zeroForOne, amountIn, minOut, recipient));
(out, spent) = abi.decode(ret, (uint256, uint256));
}
function unlockCallback(bytes calldata data) external returns (bytes memory) {
if (msg.sender != poolManager) revert BadCallback();
(StockRouterPoolKey memory key, bool zeroForOne, uint256 amountIn, uint256 minOut, address recipient) =
abi.decode(data, (StockRouterPoolKey, bool, uint256, uint256, address));
StockRouterSwapParams memory params = StockRouterSwapParams({
zeroForOne: zeroForOne,
amountSpecified: -int256(amountIn),
sqrtPriceLimitX96: zeroForOne ? MIN_SQRT_PRICE_LIMIT : MAX_SQRT_PRICE_LIMIT
});
int256 delta = IStockRouterPoolManager(poolManager).swap(key, params, "");
int128 amount0 = int128(delta >> 128);
int128 amount1 = int128(delta);
int128 inputDelta = zeroForOne ? amount0 : amount1;
int128 outputDelta = zeroForOne ? amount1 : amount0;
if (inputDelta >= 0) revert InvalidAmount();
if (outputDelta <= 0) revert NoOutput();
uint256 owed = uint256(uint128(-inputDelta));
uint256 out = uint256(uint128(outputDelta));
if (out < minOut) revert Slippage();
address inputCurrency = zeroForOne ? key.currency0 : key.currency1;
address outputCurrency = zeroForOne ? key.currency1 : key.currency0;
_settle(inputCurrency, owed);
IStockRouterPoolManager(poolManager).take(outputCurrency, recipient, out);
return abi.encode(out, owed);
}
function _poolKey(address token, address quote) internal view returns (StockRouterPoolKey memory key) {
(address c0, address c1) = uint160(token) < uint160(quote) ? (token, quote) : (quote, token);
key = StockRouterPoolKey({
currency0: c0,
currency1: c1,
fee: poolFee,
tickSpacing: poolTickSpacing,
hooks: poolHook
});
}
function _settle(address currency, uint256 amount) internal {
IStockRouterPoolManager(poolManager).sync(currency);
if (!IStockRouterERC20(currency).transfer(poolManager, amount)) revert TransferFailed();
uint256 paid = IStockRouterPoolManager(poolManager).settle();
require(paid == amount, "SETTLE_MISMATCH");
}
/// @notice Rescue only the balance this router does NOT owe to anyone.
/// @dev Audit fix: rescueToken previously had no ledger check, so the owner could drain the
/// creators' pendingQuote/pendingToken balances. Only the excess over reservedBalance() —
/// creator fees plus the accrued treasury ledger — can now be moved.
function rescueToken(address token, address to, uint256 amount) external onlyOwner {
if (to == address(0)) revert InvalidAddress();
uint256 reserved = reservedBalance(token);
if (reserved != 0) {
uint256 bal = IStockRouterERC20(token).balanceOf(address(this));
if (amount + reserved > bal) revert ReservedBalance();
}
if (!IStockRouterERC20(token).transfer(to, amount)) revert TransferFailed();
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@uniswap/v4-core/=lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"solady/=lib/solady/",
"@openzeppelin/contracts/=lib/infinity-core/lib/openzeppelin-contracts/contracts/",
"permit2/=lib/v4-periphery/lib/permit2/",
"infinity-core/=lib/infinity-core/",
"lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
"lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
"lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
"lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
"lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
"lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
"lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/infinity-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/infinity-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/infinity-core/lib/pancake-create3-factory/:forge-gas-snapshot/=lib/infinity-core/lib/pancake-create3-factory/lib/forge-gas-snapshot/src/",
"lib/infinity-core/lib/pancake-create3-factory/:forge-gas-snapshot/=lib/infinity-core/lib/pancake-create3-factory/lib/forge-gas-snapshot/src/",
"lib/infinity-core/lib/pancake-create3-factory/:openzeppelin-contracts/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/",
"lib/infinity-core/lib/pancake-create3-factory/:openzeppelin-contracts/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/",
"lib/infinity-core/lib/solmate/:ds-test/=lib/infinity-core/lib/solmate/lib/ds-test/src/",
"lib/infinity-core/lib/solmate/:ds-test/=lib/infinity-core/lib/solmate/lib/ds-test/src/",
"lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
"lib/v4-periphery/lib/permit2/:solmate/=lib/v4-periphery/lib/permit2/lib/solmate/",
"lib/v4-periphery/lib/permit2/:solmate/=lib/v4-periphery/lib/permit2/lib/solmate/",
"lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"lib/v4-periphery/lib/v4-core/:solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
"lib/v4-periphery/lib/v4-core/:solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
"lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"lib/infinity-core/:solmate/=lib/infinity-core/lib/solmate/",
"lib/infinity-core/:solmate/=lib/infinity-core/lib/solmate/",
"lib/infinity-core/:openzeppelin-contracts/=lib/infinity-core/lib/openzeppelin-contracts/",
"lib/infinity-core/:openzeppelin-contracts/=lib/infinity-core/lib/openzeppelin-contracts/",
"lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
"lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"lib/v4-periphery/:v4-core/=lib/v4-periphery/lib/v4-core/src/",
"lib/v4-periphery/:v4-core/=lib/v4-periphery/lib/v4-core/src/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=lib/infinity-core/lib/openzeppelin-contracts/",
"ds-test/=lib/infinity-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/infinity-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/infinity-core/lib/forge-gas-snapshot/src/",
"halmos-cheatcodes/=lib/infinity-core/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/infinity-core/lib/openzeppelin-contracts/",
"pancake-create3-factory/=lib/infinity-core/lib/pancake-create3-factory/",
"solmate/=lib/infinity-core/lib/solmate/",
"v4-core/=lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.