Verified contractPartialMIT
FeeRouter
Address0x2eaf12022db5353a69c2632f0021687c8a24ac0b
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 999,999 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,075,263
- Creation transaction
- 0xbedac59e83…84d9c7cf19
28 files
- src/fees/FeeRouter.solmain58.82 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol3.49 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol4.03 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol6.6 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol636 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol881 B
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol472 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.03 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol2.06 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol5.07 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- src/interfaces/ICreatorFeeRegistry.sol2.53 KB
- src/interfaces/ICreatorFeeVault.sol1.43 KB
- src/interfaces/IMotoSwapRouter02.sol5.28 KB
- src/interfaces/IPermit2.sol2.27 KB
- src/interfaces/IQuoteAssetRegistry.sol810 B
- src/interfaces/IWETH.sol299 B
- src/upgrade/UUPSRenounceable.sol8.56 KB
src/fees/FeeRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuardTransient } from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { UUPSRenounceable } from "../upgrade/UUPSRenounceable.sol";
import { Ownable2StepUpgradeable } from
"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import { IMotoSwapRouter02 } from "../interfaces/IMotoSwapRouter02.sol";
import { IQuoteAssetRegistry } from "../interfaces/IQuoteAssetRegistry.sol";
import { IPermit2 } from "../interfaces/IPermit2.sol";
import { IWETH } from "../interfaces/IWETH.sol";
import { ICreatorFeeRegistry } from "../interfaces/ICreatorFeeRegistry.sol";
import { ICreatorFeeVault } from "../interfaces/ICreatorFeeVault.sol";
/// @title FeeRouter
/// @notice Front-door swap router that takes the **0.7% protocol fee on the quote-asset side** of a
/// swap (`protocolFeeBps`) and forwards it to the `Collector`, then routes the rest through the
/// standard `MotoSwapRouter02`. This 0.7% is a pure periphery accounting path — FeeRouter
/// itself never touches the constant-product swap math — only the protocol-fee collection
/// path changes, swap mechanics stay standard AMM behaviour. It is SEPARATE from the core pair
/// swap fee, which is configurable rather than the fixed 0.3% Uniswap-V2 default:
/// `MotoSwapFactory.swapFeeBps` initializes to 100 bps (1.00%) and is retunable by the
/// feeToSetter up to `MAX_SWAP_FEE_BPS` = 200 bps (2.00%).
///
/// How that fee splits depends on `feeTo`, which is NOT set by `MotoSwapFactory.initialize`:
/// `MotoSwapPair._mintFee` no-ops entirely while `feeTo == address(0)`, so the whole pair fee
/// accrues to LPs. Only once the feeToSetter points `feeTo` somewhere does the pair mint the
/// protocol's ~60% share (LPs keeping ~40%).
///
/// A deployment that sets the pair swap fee to 30 bps and leaves `feeTo` at zero charges
/// **0.30%, entirely to LPs** — the 1.00%/60-40 figures above describe the contract defaults,
/// not any particular deployment.
/// @dev Fee side: if exactly one leg is a quote asset, the fee is taken from
/// that leg. When BOTH legs are quote (e.g. WETH/USDC, USDC/MOTO), the fee is charged on the
/// higher-`quoteRank` side so protocol fees concentrate in the most senior quote asset
/// (WETH>USDT>USDC>MOTO); an unranked registry (all ranks 0) falls back to charging the output
/// side. Exactly one side is ever charged.
///
/// Routes where NEITHER endpoint is quote (TOKEN_A→ETH→TOKEN_B) are supported by splitting at the
/// first quote leg and skimming the fee there — fee once, always in a quote asset. Multihop routes
/// like Uniswap: the fee applies on the first swap only and later hops are exempt. Only a route
/// with no quote leg anywhere still reverts `NoQuoteSide`.
///
/// The user-facing `amountOutMin` is enforced on the **net** amount actually delivered. Because
/// this contract holds no balances between calls, any dust left by rounding is negligible and
/// swept on the next distribution; there is no protocol value stored here.
///
/// @dev This contract's runtime size sits close to the EIP-170 limit, so anything added here should
/// be measured with `forge build --sizes` in the same change. Moving logic into an external
/// library is the available escape hatch if the margin runs out.
contract FeeRouter is Initializable, UUPSRenounceable, Ownable2StepUpgradeable, ReentrancyGuardTransient {
using SafeERC20 for IERC20;
/// @notice One leg of an atomic split fill. Every leg shares the
/// same input asset (`path[0]`) and the same final output asset (`path[last]`).
struct SwapLeg {
uint256 amountIn;
address[] path;
}
/// @notice Max legs in one split call — 2 covers the launcher's TOKEN/WETH + TOKEN/MOTO case;
/// 4 is a comfortable ceiling.
uint256 public constant MAX_SPLIT_LEGS = 4;
IMotoSwapRouter02 public router;
IQuoteAssetRegistry public registry;
address public collector;
address public WETH;
/// @notice Canonical Permit2 (`0x000000000022D473030F116dDEE9F6B43aC78BA3` on mainnet/Sepolia), or
/// `address(0)` when signature swaps are switched off. Set at `initialize`, retunable via
/// {setPermit2} (a fork or a local chain deploys Permit2 elsewhere, if at all).
IPermit2 public permit2;
/// @notice Steady-state protocol fee: 0.70%, which with the pair's 0.30% LP fee makes the 1.00%
/// every swap pays once the protocol fee is switched on.
uint256 public constant LAUNCH_PROTOCOL_FEE_BPS = 70;
/// @notice Hard ceiling on {protocolFeeBps}. Governance can retune the fee below this and can
/// switch it off entirely, but can never raise it past this without an upgrade.
uint256 public constant MAX_PROTOCOL_FEE_BPS = 100;
uint256 public constant BPS_DENOM = 10_000;
/// @notice Live protocol fee in basis points, skimmed off the quote leg of every swap and sent to
/// the Collector. The split across buckets lives in the Collector, not here.
/// @dev Settable, and 0 is a supported setting: at 0 a swap pays the 0.30% LP fee only and the
/// FeeRouter still emits {Swap} (with `feeAmount == 0`), so the indexer keeps scoring every
/// trade. At {LAUNCH_PROTOCOL_FEE_BPS} the full 1.00% applies. Read live by everything that
/// has to price a swap — notably {MotoSwapZap}'s optimal-split math and {TokenLauncher}'s
/// floors — so changing it needs no redeploy anywhere.
uint256 public protocolFeeBps;
/// @notice Creator-fee config. An ADDITIONAL skim on the same quote leg when
/// a swap-path endpoint is a registered token, sent to the vault instead of the Collector,
/// and separate from `protocolFeeBps`. `creatorRegistry == 0` OR `creatorFeeBps == 0`
/// disables it entirely, so a deployment without the feature is provably unchanged.
ICreatorFeeRegistry public creatorRegistry;
ICreatorFeeVault public creatorVault;
/// @notice Creator fee in bps of the quote leg (0.20% = 20). Owner-settable like `protocolFeeBps`.
uint256 public creatorFeeBps;
/// @notice Hard ceiling on {creatorFeeBps}; only an upgrade can raise it.
uint256 public constant MAX_CREATOR_FEE_BPS = 50;
/// @dev Storage gap for future upgrades. Never shrink; only consume from the front.
/// Five slots consumed: `permit2`, `protocolFeeBps`, `creatorRegistry`, `creatorVault`,
/// `creatorFeeBps` (50 → 45).
uint256[45] private __gap;
// The fee configuration (`collector`, `protocolFeeBps`, `creatorFeeBps`) is stored unpacked, one slot
// per value. The layout is fixed by `storage-layouts/FeeRouter.json` and checked on every push.
/// @notice The real trader (`msg.sender`) + endpoints + net delivered, plus the EXACT quote-asset
/// fee. It carries the PAYER, never `to` (the RECIPIENT). The two coincide for an ordinary
/// swap and diverge the moment a caller directs output elsewhere — a contract integrator, a
/// swap made on someone's behalf, or the Zap, which swaps through here with itself as `to`.
/// Since points, rakeback and referral attribution are all derived from this field, using
/// `to` would credit the volume to whoever received the tokens rather than whoever paid.
/// (`feeToken`, `feeAmount`) transferred to the collector. The off-chain indexer attributes
/// per-user swaps (points / referrals / boosts) from THIS event, because the underlying
/// pair `Swap` has `to = address(this)` (the router takes custody to skim the fee); it also
/// accrues rakeback as a fixed fraction of `feeAmount` (no need to re-derive the fee side
/// from a quote-asset set, and no gross-vs-net base ambiguity).
event Swap(
address indexed user,
address indexed tokenIn,
address indexed tokenOut,
uint256 amountIn,
uint256 amountOut,
address feeToken,
uint256 feeAmount
);
/// @notice Permit2 address changed (`address(0)` disables the signature entrypoints).
event Permit2Set(address permit2);
event ProtocolFeeSet(uint256 protocolFeeBps);
/// @notice A creator-fee skim was taken on `token`'s quote leg, sent to the vault.
event CreatorFee(address indexed token, address indexed creator, address quoteAsset, uint256 amount);
event CreatorFeeConfigSet(address registry, address vault, uint256 creatorFeeBps);
/// @notice A stranded token (or ETH, as `address(0)`) was swept out by the owner.
event Rescued(address indexed token, address indexed to, uint256 amount);
error InvalidPath();
error InsufficientOutput();
error EthTransferFailed();
error NoQuoteSide();
error FeeTooHigh();
error ZeroAddress();
error Permit2NotSet();
error PermitTokenMismatch();
error NoLegs();
error TooManyLegs();
error LegMismatch();
error ValueMismatch();
/// @notice A live `creatorFeeBps` was pointed at a vault that has not admitted this router as a
/// depositor, so the skim could not be recorded. See {setCreatorFeeConfig}.
error VaultDoesNotAdmitRouter();
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @param permit2_ Permit2 for the signature entrypoints. `address(0)` leaves them switched off
/// (they revert `Permit2NotSet`) — the right setting on a chain with no Permit2 deployment.
/// @param protocolFeeBps_ Fee to start with. 0 starts with the protocol fee off (LP fee only);
/// {LAUNCH_PROTOCOL_FEE_BPS} once the full 1.00% applies.
function initialize(
address router_,
address registry_,
address collector_,
address permit2_,
uint256 protocolFeeBps_,
address owner_
) external initializer {
// All four addresses are checked here so a zero argument reverts `ZeroAddress`, naming the bad
// argument, rather than failing later in the `WETH()` call below with an opaque decode error.
if (registry_ == address(0) || collector_ == address(0) || router_ == address(0)) revert ZeroAddress();
if (owner_ == address(0)) revert ZeroAddress();
// Ownership transfer is two-step: the destination has to accept it, so a mistyped address
// leaves `pendingOwner` pointing at it and the current owner still in charge.
//
// `__Ownable2Step_init()` adds nothing at runtime in OZ v5 and takes no sequential storage slot
// (ERC-7201 namespaced), so this is layout-safe on existing proxies.
__Ownable_init(owner_);
__Ownable2Step_init();
__UUPSUpgradeable_init();
router = IMotoSwapRouter02(router_);
registry = IQuoteAssetRegistry(registry_);
collector = collector_;
WETH = IMotoSwapRouter02(router_).WETH();
permit2 = IPermit2(permit2_);
emit Permit2Set(permit2_);
if (protocolFeeBps_ > MAX_PROTOCOL_FEE_BPS) revert FeeTooHigh();
protocolFeeBps = protocolFeeBps_;
emit ProtocolFeeSet(protocolFeeBps_);
}
/// @notice Retune the protocol fee, or switch it off entirely. Owner-gated.
/// @dev The pair's LP fee is independent (`factory.swapFeeBps`); this is only the protocol's leg.
function setProtocolFeeBps(uint256 bps) external onlyOwner {
if (bps > MAX_PROTOCOL_FEE_BPS) revert FeeTooHigh();
protocolFeeBps = bps;
emit ProtocolFeeSet(bps);
}
/// @notice Wire (or update) the creator-fee registry + vault and the rate. Owner-gated. A zero
/// registry/vault or zero bps switches the feature off; the swap paths then never touch it.
/// @dev THE VAULT MUST ADMIT THIS ROUTER. {_skimOne} calls `vault.notifyDeposit` unconditionally,
/// with no try/catch, and that call is depositor-gated on the vault's side. While the two are
/// out of step — a redeployed vault, a re-point, a `setDepositor(router,false)` — every swap
/// whose path touches a registered token reverts `NotDepositor`, on every entrypoint including
/// the FoT family, split fills and mid-quote routes. The check below is one `staticcall` and
/// refuses a live rate against a vault that does not admit this router.
function setCreatorFeeConfig(address registry_, address vault_, uint256 bps) external onlyOwner {
if (bps > MAX_CREATOR_FEE_BPS) revert FeeTooHigh();
// A live fee (bps>0) needs both a registry to resolve creators and a vault to receive the skim;
// a zero registry/vault while bps>0 would make every registered-token swap revert (transfer or
// notify to address(0)). Zeroing bps is the intended off switch.
if (bps > 0 && (registry_ == address(0) || vault_ == address(0))) revert ZeroAddress();
if (bps > 0 && !ICreatorFeeVault(vault_).isDepositor(address(this))) revert VaultDoesNotAdmitRouter();
creatorRegistry = ICreatorFeeRegistry(registry_);
creatorVault = ICreatorFeeVault(vault_);
creatorFeeBps = bps;
emit CreatorFeeConfigSet(registry_, vault_, bps);
}
/// @dev Skim the creator fee for EACH of {tokenA,tokenB} that is a registered token, from the
/// `quoteToken` this contract already HOLDS (the same asset the protocol fee comes from), and
/// record it in the vault. Returns the total skimmed. `quoteBase` is the protocol-fee base (the
/// quote-leg amount), so a swap of a given size pays the same creator fee whether it's routed
/// as one path or split. Off entirely when the registry or rate is zero.
/// @dev BOTH endpoints are charged when both are registered — each creator earns their own
/// `creatorFeeBps` of the quote leg, so a long-tail↔long-tail trade pays the fee TWICE (up to
/// `2 * MAX_CREATOR_FEE_BPS` = 1.00% in aggregate, on top of the protocol fee). That is the
/// intended accrual — two registered tokens means two creators — and the trader is protected
/// by their own `amountOutMin`, which every path enforces on the NET after all skims. Quote
/// assets are never registered, so the common quote↔long-tail swap only ever pays it once.
function _skimCreators(address tokenA, address tokenB, address quoteToken, uint256 quoteBase)
private
returns (uint256 total)
{
if (address(creatorRegistry) == address(0) || creatorFeeBps == 0) return 0;
total = _skimOne(tokenA, quoteToken, quoteBase);
if (tokenB != tokenA) total += _skimOne(tokenB, quoteToken, quoteBase);
}
/**
* @dev THE VAULT IS TOLD WHAT ARRIVED, NOT WHAT WAS SENT, and the two differ for a quote asset that
* taxes its own transfers: such an asset delivers less than `cut`, so the balance delta at the
* vault is measured here and `notifyDeposit` is given the measured figure. That keeps
* {CreatorFeeVault}'s pooled per-quote-asset ledger equal to what the vault actually holds.
*
* Only the fee-on-transfer entrypoints can carry a taxing asset at all: the plain entrypoints
* compute with nominal amounts, so a taxing asset makes the swap revert there.
*
* `cut` is deliberately still the figure the SWAP arithmetic uses — it is what left this router,
* so the trader's own output is unaffected by the measurement. Only the ledger takes the
* measured number.
*/
function _skimOne(address token, address quoteToken, uint256 quoteBase) private returns (uint256 cut) {
address creator = creatorRegistry.activeCreator(token);
if (creator == address(0)) return 0; // unregistered or disabled — quote assets are never registered
cut = (quoteBase * creatorFeeBps) / BPS_DENOM;
if (cut == 0) return 0;
address vault = address(creatorVault);
uint256 before = IERC20(quoteToken).balanceOf(vault);
IERC20(quoteToken).safeTransfer(vault, cut);
uint256 landed = IERC20(quoteToken).balanceOf(vault) - before;
creatorVault.notifyDeposit(token, quoteToken, landed);
emit CreatorFee(token, creator, quoteToken, landed);
}
/// @dev ETH-quote variant: the quote value is native ETH held by this contract (an ETH-in swap or
/// a token→ETH swap). Wrap the cut to WETH and record it. Only the non-WETH endpoint can be
/// registered (WETH is a quote asset), so a single lookup suffices.
/// @dev DELIBERATELY NOT DELTA-MEASURED, unlike {_skimOne}. That one measures because `quoteToken`
/// is any registered quote asset and one of them could tax its transfers. Here the asset is
/// always WETH — canonical, read once from the router at initialize, and non-taxing by
/// construction — so a measurement would cost two `balanceOf` calls to confirm something that
/// cannot vary.
function _skimCreatorEth(address token, uint256 ethBase) private returns (uint256 cut) {
if (address(creatorRegistry) == address(0) || creatorFeeBps == 0) return 0;
address creator = creatorRegistry.activeCreator(token);
if (creator == address(0)) return 0;
cut = (ethBase * creatorFeeBps) / BPS_DENOM;
if (cut == 0) return 0;
IWETH(WETH).deposit{ value: cut }();
IERC20(WETH).safeTransfer(address(creatorVault), cut);
creatorVault.notifyDeposit(token, WETH, cut);
emit CreatorFee(token, creator, WETH, cut);
}
/// @dev Only the owner may upgrade the implementation, and `_requireUpgradable()` closes the path
/// permanently once {renounceUpgradeability} has been called. The upgrade and the renounce
/// share the `onlyOwner` gate with every fee setter below.
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {
_requireUpgradable();
}
/// @notice Permanently relinquish the ability to upgrade this contract (one-way,
/// owner-gated). The "upgrade-to-immutable" switch. Ownership and every
/// operational setter keep working — only the upgrade path is frozen.
function renounceUpgradeability() external onlyOwner {
_renounceUpgradeability();
}
/// @notice Sweep a stranded token to `to`. This contract settles every path to the wei and holds
/// nothing between calls, so there is no user balance here to take — but without a sweep,
/// anything sent here directly would be stuck forever.
/// @dev Owner-gated and `nonReentrant`, so it cannot interleave with a swap in flight.
function rescueERC20(address token, address to) external onlyOwner nonReentrant {
if (to == address(0)) revert ZeroAddress();
uint256 amount = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(to, amount);
emit Rescued(token, to, amount);
}
/// @notice Sweep stranded native ETH. `receive` only admits the router and WETH, so this only ever
/// captures ETH that arrived outside those two paths, never an in-flight swap.
function rescueETH(address to) external onlyOwner nonReentrant {
if (to == address(0)) revert ZeroAddress();
uint256 amount = address(this).balance;
(bool ok,) = to.call{ value: amount }("");
if (!ok) revert EthTransferFailed();
emit Rescued(address(0), to, amount);
}
/// @notice Re-point the signature entrypoints at a different Permit2, or switch them off with
/// `address(0)`. `initialize` sets this; the setter exists because Permit2's address is
/// canonical per chain but not universal, and because turning signature swaps off should
/// not require an upgrade.
function setPermit2(address permit2_) external onlyOwner {
permit2 = IPermit2(permit2_);
emit Permit2Set(permit2_);
}
/// @dev Accept ETH from the router (WETH withdraw) during token→ETH swaps.
receive() external payable {
if (msg.sender != address(router) && msg.sender != WETH) revert EthTransferFailed();
}
/// @notice True if the 0.7% fee is taken from the output leg. When only one endpoint is a quote
/// asset the fee follows it; when both are quote the higher-`quoteRank` side wins (ties and
/// an unranked registry default to the output side).
function feeOnOutput(address[] calldata path) public view returns (bool) {
return _feeOnOutput(path[0], path[path.length - 1]);
}
/// @dev Fee-side selection shared by every swap entrypoint. `_requireQuoteEndpoint` guarantees at
/// least one endpoint is quote before this runs on the swap path; as a standalone view over a
/// no-quote pair it harmlessly returns true (the swap itself would revert `NoQuoteSide`).
function _feeOnOutput(address tokenIn, address tokenOut) private view returns (bool) {
bool outQuote = registry.isQuote(tokenOut);
bool inQuote = registry.isQuote(tokenIn);
if (outQuote && !inQuote) return true;
if (inQuote && !outQuote) return false;
// Both legs quote: charge the more senior quote asset. Ranks default to 0, so an unranked
// registry keeps the "charge the output side" tie-break (rank(out) >= rank(in) == true).
return registry.quoteRank(tokenOut) >= registry.quoteRank(tokenIn);
}
/// @dev ETH entrypoints only: WETH is an endpoint there and is always a registered quote asset,
/// so this simply backstops a (hypothetical) WETH deregistration. Token→token routes do not
/// require a quote ENDPOINT — a mid-path quote leg is handled by `_swapViaMidQuote`
/// (TOKEN_A→ETH→TOKEN_B routes; fee once, on the first swap's quote leg).
function _requireQuoteEndpoint(address[] calldata path) private view {
if (!registry.isQuote(path[0]) && !registry.isQuote(path[path.length - 1])) revert NoQuoteSide();
}
/// @dev Index of the FIRST quote asset strictly inside the path (neither endpoint is quote).
/// Reverts `NoQuoteSide` when the route has no quote leg anywhere — such a route cannot pay
/// a quote-denominated fee (and can't exist on gated pairs anyway: `createPair` requires a
/// quote side on every pair).
function _firstMidQuote(address[] calldata path) private view returns (uint256 j) {
uint256 last = path.length - 1;
for (j = 1; j < last; ++j) {
if (registry.isQuote(path[j])) return j;
}
revert NoQuoteSide();
}
/// @dev TOKEN_A→…→QUOTE→…→TOKEN_B: split the route at the first quote leg. Leg A swaps into the
/// quote asset held here, the 0.7% is skimmed from those quote proceeds (fee once, and always
/// in a quote asset), then leg B swaps the remainder to the trader.
/// `amountOutMin` is enforced by leg B on the net final delivery, exactly like the
/// endpoint-fee paths.
function _swapViaMidQuote(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) private returns (uint256[] memory amounts, address feeToken, uint256 feeAmount) {
uint256 j = _firstMidQuote(path);
feeToken = path[j];
IERC20(path[0]).forceApprove(address(router), amountIn);
uint256[] memory legA = router.swapExactTokensForTokens(amountIn, 0, path[:j + 1], address(this), deadline);
uint256 gross = legA[legA.length - 1];
feeAmount = (gross * protocolFeeBps) / BPS_DENOM;
IERC20(feeToken).safeTransfer(collector, feeAmount);
// Creator fee on either long-tail endpoint, off the same quote leg (feeToken == path[j]).
uint256 creatorTotal = _skimCreators(path[0], path[path.length - 1], feeToken, gross);
uint256 swapAmount = gross - feeAmount - creatorTotal;
IERC20(feeToken).forceApprove(address(router), swapAmount);
uint256[] memory legB = router.swapExactTokensForTokens(swapAmount, amountOutMin, path[j:], to, deadline);
// Stitch the hop amounts back into one array. THE ARRAY DOES NOT FULLY CHAIN, AND CANNOT: a fee
// is removed between the two legs, so exactly one consecutive pair is not a swap that happened.
//
// What an integrator should rely on: `amounts[0]` is the input, the final element is what `to`
// received, and the fee is on the {Swap} event with its token. The non-chaining index is
// `j-1 -> j`, where `j` is `_firstMidQuote(path)`.
//
// `amounts[j]` holds leg B's INPUT — the post-fee net — rather than leg A's gross output, so
// every other consecutive pair is a real swap. Leg A's gross is `amounts[j] + fee + creator cut`
// for anyone who wants it.
amounts = new uint256[](path.length);
for (uint256 i; i < j; ++i) {
amounts[i] = legA[i];
}
for (uint256 i = j; i < path.length; ++i) {
amounts[i] = legB[i - j];
}
}
// --- token → token ---
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external nonReentrant returns (uint256[] memory amounts) {
IERC20(path[0]).safeTransferFrom(msg.sender, address(this), amountIn);
return _swapTokensForTokens(amountIn, amountOutMin, path, to, deadline);
}
/// @notice Same swap as {swapExactTokensForTokens}, with the input pulled by a Permit2 signature
/// instead of a prior `approve` to this router: one signature, one transaction.
///
/// @dev NOT EVERY ENTRYPOINT HAS A PERMIT2 TWIN: twins exist for this one and
/// {swapExactTokensForETHPermit2} only. The fee-on-transfer token-in entrypoints and both
/// token-in split entrypoints pull with `safeTransferFrom` / `_pullRealised`, so they need
/// a prior `approve` to this router and revert on a zero router allowance.
/// @dev Everything downstream of the pull is the identical code path: same fee-side selection,
/// same 0.70% skim to the `collector`, same `amountOutMin` on the net, same {Swap} event —
/// so points, rakeback and referral attribution behave exactly as they do for an approved
/// swap. Routing signature swaps through a pair-only adapter instead would pay the LP fee
/// alone and emit no {Swap}, silently zeroing those rewards.
///
/// The Permit2 digest binds `spender` to `msg.sender` of `permitTransferFrom` — this
/// contract — so a signature is only ever valid for the contract it was issued to.
/// @param permit The Permit2 authorisation. `permit.permitted.token` MUST equal `path[0]`, and
/// `amountIn` MUST be ≤ `permit.permitted.amount` (Permit2 enforces the latter).
/// @param signature The user's EIP-712 signature over `permit` for this router as spender.
function swapExactTokensForTokensPermit2(
IPermit2.PermitTransferFrom calldata permit,
bytes calldata signature,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external nonReentrant returns (uint256[] memory amounts) {
_pullWithPermit2(permit, signature, path[0], amountIn);
return _swapTokensForTokens(amountIn, amountOutMin, path, to, deadline);
}
/// @dev The whole token→token body downstream of the input pull. `amountIn` of `path[0]` is
/// already held by this contract when this runs.
function _swapTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) private returns (uint256[] memory amounts) {
address feeToken;
uint256 feeAmount;
(amounts, feeToken, feeAmount) = _swapT4TCore(amountIn, amountOutMin, path, to, deadline);
emit Swap(msg.sender, path[0], path[path.length - 1], amountIn, amounts[amounts.length - 1], feeToken, feeAmount);
}
/// @dev The token→token swap body WITHOUT emitting {Swap}. Returns the amounts and the exact
/// quote-leg protocol fee. Shared by the single-path entrypoint (which emits) and the split
/// entrypoint (which sums across legs and emits ONCE). `amountOutMin` should be 0 for a split
/// leg — the aggregate floor is enforced on the sum.
function _swapT4TCore(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline)
private
returns (uint256[] memory amounts, address feeToken, uint256 feeAmount)
{
address tokenIn = path[0];
address tokenOut = path[path.length - 1];
if (!registry.isQuote(tokenIn) && !registry.isQuote(tokenOut)) {
(amounts, feeToken, feeAmount) = _swapViaMidQuote(amountIn, amountOutMin, path, to, deadline);
} else if (feeOnOutput(path)) {
IERC20(tokenIn).forceApprove(address(router), amountIn);
amounts = router.swapExactTokensForTokens(amountIn, 0, path, address(this), deadline);
uint256 grossOut = amounts[amounts.length - 1];
uint256 net;
(net, feeAmount) = _takeOutputFee(tokenIn, tokenOut, grossOut, amountOutMin, to);
amounts[amounts.length - 1] = net;
feeToken = tokenOut;
} else {
uint256 swapAmount;
(swapAmount, feeAmount) = _takeInputFee(tokenIn, tokenOut, amountIn);
IERC20(tokenIn).forceApprove(address(router), swapAmount);
amounts = router.swapExactTokensForTokens(swapAmount, amountOutMin, path, to, deadline);
// `amounts[0]` is the caller's GROSS input on every branch. The router only ever saw
// `swapAmount`, so the gross is restated here, giving `amounts[0]` one meaning regardless of
// which side the fee landed on.
amounts[0] = amountIn;
feeToken = tokenIn;
}
}
// --- ETH → token ---
function swapExactETHForTokens(uint256 amountOutMin, address[] calldata path, address to, uint256 deadline)
external
payable
nonReentrant
returns (uint256[] memory amounts)
{
address feeToken;
uint256 feeAmount;
(amounts, feeToken, feeAmount) = _swapETHForTokensCore(msg.value, amountOutMin, path, to, deadline);
emit Swap(msg.sender, WETH, path[path.length - 1], msg.value, amounts[amounts.length - 1], feeToken, feeAmount);
}
/// @dev ETH→token body WITHOUT emitting {Swap}, parameterized on `ethIn` (== `msg.value` for a
/// single swap, or a leg's share for a split). This contract must hold `ethIn` of ETH.
function _swapETHForTokensCore(
uint256 ethIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) private returns (uint256[] memory amounts, address feeToken, uint256 feeAmount) {
if (path[0] != WETH) revert InvalidPath();
_requireQuoteEndpoint(path);
address tokenOut = path[path.length - 1];
if (feeOnOutput(path)) {
amounts = router.swapExactETHForTokens{ value: ethIn }(0, path, address(this), deadline);
uint256 grossOut = amounts[amounts.length - 1];
uint256 net;
(net, feeAmount) = _takeOutputFee(WETH, tokenOut, grossOut, amountOutMin, to);
amounts[amounts.length - 1] = net;
feeToken = tokenOut;
} else {
uint256 fee = (ethIn * protocolFeeBps) / BPS_DENOM;
IWETH(WETH).deposit{ value: fee }();
IERC20(WETH).safeTransfer(collector, fee);
uint256 creatorTotal = _skimCreatorEth(tokenOut, ethIn);
uint256 swapAmount = ethIn - fee - creatorTotal;
amounts = router.swapExactETHForTokens{ value: swapAmount }(amountOutMin, path, to, deadline);
// The same restatement the token-in branch above does: the router only ever saw
// `swapAmount`, so `amounts[0]` is set back to the gross ETH input. `_feeOnOutput(WETH,
// nonQuote)` is false, so this is the branch a plain ETH -> token swap takes. {Swap} already
// reports the gross, so this affects only the returned array.
amounts[0] = ethIn;
(feeToken, feeAmount) = (WETH, fee);
}
}
// --- token → ETH ---
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external nonReentrant returns (uint256[] memory amounts) {
IERC20(path[0]).safeTransferFrom(msg.sender, address(this), amountIn);
return _swapTokensForETH(amountIn, amountOutMin, path, to, deadline);
}
/// @notice Same swap as {swapExactTokensForETH}, input pulled by a Permit2 signature. See
/// {swapExactTokensForTokensPermit2} — identical fee path, identical {Swap} event.
function swapExactTokensForETHPermit2(
IPermit2.PermitTransferFrom calldata permit,
bytes calldata signature,
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external nonReentrant returns (uint256[] memory amounts) {
_pullWithPermit2(permit, signature, path[0], amountIn);
return _swapTokensForETH(amountIn, amountOutMin, path, to, deadline);
}
/// @dev The token→ETH body downstream of the input pull.
function _swapTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) private returns (uint256[] memory amounts) {
(uint256 net, uint256 fee, address feeToken) =
_swapTokensForETHCore(amountIn, amountOutMin, path, to, deadline);
// ONLY `[0]` AND THE LAST ELEMENT ARE FILLED. This array is rebuilt from the gross input and
// the net delivered rather than from the router's per-hop amounts, so on a multihop route
// (`path.length >= 3`, e.g. `[TOKEN, MOTO, WETH]`) the interior elements are zero. `amounts[0]`
// is the input and the final element is the net ETH `to` received; the fee is on the {Swap}
// event with its token.
amounts = new uint256[](path.length);
amounts[0] = amountIn;
amounts[amounts.length - 1] = net;
emit Swap(msg.sender, path[0], WETH, amountIn, net, feeToken, fee);
}
/// @dev token→ETH body WITHOUT emitting {Swap}. This contract must already HOLD `amountIn` of
/// `path[0]` (pulled by the caller). Returns the net ETH delivered and the protocol fee.
function _swapTokensForETHCore(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) private returns (uint256 net, uint256 fee, address feeToken) {
if (path[path.length - 1] != WETH) revert InvalidPath();
_requireQuoteEndpoint(path);
address tokenIn = path[0];
// The fee side is selected here rather than assumed, exactly as `_swapETHForTokensCore` and the
// token→token path do. The documented rule is "when both legs are quote assets, charge the more
// senior one", and `quoteRank` is owner-settable at any time
// (`QuoteAssetRegistry.setQuoteRank`), so ETH out is the quote leg only while WETH outranks the
// input token.
if (feeOnOutput(path)) {
IERC20(tokenIn).forceApprove(address(router), amountIn);
uint256[] memory a = router.swapExactTokensForETH(amountIn, 0, path, address(this), deadline);
uint256 out = a[a.length - 1];
fee = (out * protocolFeeBps) / BPS_DENOM;
uint256 creatorTotal = _skimCreatorEth(tokenIn, out);
net = out - fee - creatorTotal;
if (net < amountOutMin) revert InsufficientOutput();
IWETH(WETH).deposit{ value: fee }();
IERC20(WETH).safeTransfer(collector, fee);
(bool ok,) = to.call{ value: net }("");
if (!ok) revert EthTransferFailed();
feeToken = WETH;
} else {
// The input token is the senior quote: skim it here and let the router deliver ETH straight
// to `to`, enforcing the floor on the real output. Same shape as the token→token input-fee
// branch, so the fee accounting is shared rather than re-derived.
uint256 swapAmount;
(swapAmount, fee) = _takeInputFee(tokenIn, WETH, amountIn);
IERC20(tokenIn).forceApprove(address(router), swapAmount);
uint256[] memory a = router.swapExactTokensForETH(swapAmount, amountOutMin, path, to, deadline);
net = a[a.length - 1];
feeToken = tokenIn;
}
}
// --- internals ---
/// @dev Pull `amountIn` of `tokenIn` from the caller via Permit2 SignatureTransfer, straight into
/// this contract — the same starting state as the `safeTransferFrom` entrypoints.
///
/// The token check is explicit: Permit2 authorises `permit.permitted.token` and the swap
/// spends `path[0]`, so the two must name the same token.
function _pullWithPermit2(
IPermit2.PermitTransferFrom calldata permit,
bytes calldata signature,
address tokenIn,
uint256 amountIn
) private {
IPermit2 p2 = permit2;
if (address(p2) == address(0)) revert Permit2NotSet();
if (permit.permitted.token != tokenIn) revert PermitTokenMismatch();
p2.permitTransferFrom(
permit,
IPermit2.SignatureTransferDetails({ to: address(this), requestedAmount: amountIn }),
msg.sender,
signature
);
}
// --- fee-on-transfer variants ---------------------------------------------------------------
//
// Some tokens tax their own transfers, so the nominal amount and the amount that actually lands
// differ. The paths above compute with nominal amounts and revert on such a token; these measure
// realised balance deltas instead, exactly as Uniswap's `*SupportingFeeOnTransferTokens` family
// does — and take the SAME protocol fee off the SAME quote leg, so the fee model is unchanged
// (0.30% LP + `protocolFeeBps`). Quote assets are curated and non-taxing, so the fee leg itself
// always transfers cleanly; only the long-tail leg needs measuring.
//
// Routing parity with the non-FoT family: the token→token entrypoint supports the mid-quote
// route (TOKEN_A→QUOTE→TOKEN_B) via {_swapViaMidQuoteFot}, so a taxing token is routable wherever
// a plain one is.
/// @notice {swapExactTokensForTokens} for a token that taxes its own transfers.
/// @dev `amountIn` is what leaves the caller; what reaches the pool is whatever survives the
/// token's tax. `amountOutMin` is enforced on the amount the recipient actually receives.
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external nonReentrant returns (uint256 delivered) {
address tokenIn = path[0];
address tokenOut = path[path.length - 1];
uint256 received = _pullRealised(tokenIn, amountIn);
if (!registry.isQuote(tokenIn) && !registry.isQuote(tokenOut)) {
// Neither endpoint is quote: split at the first quote leg, exactly like the non-FoT twin.
return _swapViaMidQuoteFot(received, amountOutMin, path, to, deadline);
}
if (_feeOnOutput(tokenIn, tokenOut)) {
// Quote OUTPUT pays: swap to ourselves, measure what landed, then skim and pay the net.
IERC20(tokenIn).forceApprove(address(router), received);
uint256 balBefore = IERC20(tokenOut).balanceOf(address(this));
router.swapExactTokensForTokensSupportingFeeOnTransferTokens(received, 0, path, address(this), deadline);
uint256 grossOut = IERC20(tokenOut).balanceOf(address(this)) - balBefore;
uint256 protocolFee;
(delivered, protocolFee) = _takeOutputFeeRealised(tokenIn, tokenOut, grossOut, amountOutMin, to);
emit Swap(msg.sender, tokenIn, tokenOut, received, delivered, tokenOut, protocolFee);
} else {
// Quote INPUT pays: skim first, then let the router measure the taxed leg and enforce the
// floor on the recipient's realised delta.
(uint256 swapAmount, uint256 protocolFee) = _takeInputFee(tokenIn, tokenOut, received);
IERC20(tokenIn).forceApprove(address(router), swapAmount);
uint256 balBefore = IERC20(tokenOut).balanceOf(to);
router.swapExactTokensForTokensSupportingFeeOnTransferTokens(swapAmount, amountOutMin, path, to, deadline);
delivered = IERC20(tokenOut).balanceOf(to) - balBefore;
emit Swap(msg.sender, tokenIn, tokenOut, received, delivered, tokenIn, protocolFee);
}
}
/// @notice {swapExactETHForTokens} for a token that taxes its own transfers.
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable nonReentrant returns (uint256 delivered) {
if (path[0] != WETH) revert InvalidPath();
_requireQuoteEndpoint(path);
address tokenOut = path[path.length - 1];
if (_feeOnOutput(WETH, tokenOut)) {
uint256 balBefore = IERC20(tokenOut).balanceOf(address(this));
router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: msg.value }(
0, path, address(this), deadline
);
uint256 grossOut = IERC20(tokenOut).balanceOf(address(this)) - balBefore;
uint256 protocolFee;
(delivered, protocolFee) = _takeOutputFeeRealised(WETH, tokenOut, grossOut, amountOutMin, to);
emit Swap(msg.sender, WETH, tokenOut, msg.value, delivered, tokenOut, protocolFee);
} else {
// ETH is the quote leg: wrap the protocol fee, skim the creator fee (both in WETH, like the
// non-FoT twin), then swap the remainder.
uint256 fee = (msg.value * protocolFeeBps) / BPS_DENOM;
IWETH(WETH).deposit{ value: fee }();
IERC20(WETH).safeTransfer(collector, fee);
uint256 creatorTotal = _skimCreatorEth(tokenOut, msg.value);
uint256 balBefore = IERC20(tokenOut).balanceOf(to);
router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: msg.value - fee - creatorTotal }(
amountOutMin, path, to, deadline
);
delivered = IERC20(tokenOut).balanceOf(to) - balBefore;
emit Swap(msg.sender, WETH, tokenOut, msg.value, delivered, WETH, fee);
}
}
/**
* @notice {swapExactTokensForETH} for a token that taxes its own transfers.
*
* @dev BRANCHES ON {feeOnOutput}, LIKE ITS TWIN. ETH out is NOT always the quote leg, so the fee
* side is selected rather than assumed. This function mirrors the non-FoT twin on BOTH the
* creator skim and the fee-side selection.
*
* The rule, documented at {_feeOnOutput}: the fee is charged on the quote side, and when BOTH
* endpoints are quote assets the more senior one pays, by `quoteRank`. That rank is owner-set
* and changeable in one transaction, so which side pays can change without an upgrade.
*
* NOT ONLY REACHABLE BY FEE-ON-TRANSFER TOKENS. Nothing here requires `path[0]` to tax
* anything — the guards are "route ends in WETH" and "an endpoint is a quote asset" — so an
* ordinary quote→ETH swap may be routed through this entrypoint as well, and is charged the
* same fee, on the same side, as it would be through the twin.
*
* THE INPUT BRANCH SKIMS BEFORE THE SWAP, which is the same order the twin uses: `_takeInputFee`
* takes the protocol fee and the creator cut off the input token, and only the remainder is
* approved to the router.
*
* The one place this cannot mirror the twin: the fee-on-transfer router call returns nothing, so
* unlike `_swapTokensForETHCore` it cannot hand the router `to` and read the delivered amount
* back. It receives the ETH here and measures the balance delta instead, so the shape differs
* from its twin without the accounting differing.
*/
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external nonReentrant returns (uint256 net) {
if (path[path.length - 1] != WETH) revert InvalidPath();
_requireQuoteEndpoint(path);
address tokenIn = path[0];
uint256 received = _pullRealised(tokenIn, amountIn);
bool outFee = feeOnOutput(path);
uint256 fee;
uint256 swapAmount = received;
if (!outFee) {
// The input token is the senior quote: skim it here and swap only the remainder, exactly as
// the twin's input-fee branch does. `_takeInputFee` carries the creator cut too, so the two
// paths share the accounting rather than re-deriving it.
(swapAmount, fee) = _takeInputFee(tokenIn, WETH, received);
}
IERC20(tokenIn).forceApprove(address(router), swapAmount);
uint256 ethBefore = address(this).balance;
router.swapExactTokensForETHSupportingFeeOnTransferTokens(swapAmount, 0, path, address(this), deadline);
uint256 out = address(this).balance - ethBefore;
if (outFee) {
// Protocol fee + creator skim on the realised ETH (both in WETH), as in the non-FoT twin.
fee = (out * protocolFeeBps) / BPS_DENOM;
uint256 creatorTotal = _skimCreatorEth(tokenIn, out);
net = out - fee - creatorTotal;
} else {
net = out; // already paid for on the way in
}
if (net < amountOutMin) revert InsufficientOutput();
if (outFee) {
IWETH(WETH).deposit{ value: fee }();
IERC20(WETH).safeTransfer(collector, fee);
}
(bool ok,) = to.call{ value: net }("");
if (!ok) revert EthTransferFailed();
emit Swap(msg.sender, tokenIn, WETH, received, net, outFee ? WETH : tokenIn, fee);
}
// --- atomic split fills -----------------------------------------------------------------
//
// One transaction fills an order across both launch pools at once (e.g. USDC → WETH → TOKEN and
// USDC → MOTO → TOKEN), all-or-nothing. Each leg runs through the same fee-taking core as a
// single-path swap, so a split pays exactly the fee the same volume pays through sequential
// singles — to the dust. `minTotalOut` floors the SUM; there are NO per-leg floors, and atomicity
// is what makes the aggregate floor sufficient — any failed leg reverts the whole call.
//
// Each leg emits its OWN {Swap} (one per leg), NOT one aggregate event: legs sharing the same
// (tokenIn,tokenOut) can still take their fee in DIFFERENT quote assets (a `TOKEN_A→WETH→TOKEN_B`
// leg pays in WETH, a `TOKEN_A→MOTO→TOKEN_B` leg pays in MOTO), so a single aggregate event cannot
// name the fee token/amount without mis-attributing it. Per-leg events are byte-identical to what
// the same volume through sequential singles would emit, so the off-chain fee/rakeback indexer
// stays exact.
/// @notice Token-in split fill. Pulls the sum in one `transferFrom`; every leg shares `path[0]` and
/// `path[last]`. `minTotalOut` is enforced on the sum of net outputs.
function swapExactTokensForTokensSplit(
SwapLeg[] calldata legs,
uint256 minTotalOut,
address to,
uint256 deadline
) external nonReentrant returns (uint256[] memory legOuts, uint256 totalOut) {
(address tokenIn, address tokenOut, uint256 totalIn) = _validateLegs(legs);
IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), totalIn);
legOuts = new uint256[](legs.length);
for (uint256 i; i < legs.length; ++i) {
(uint256[] memory a, address ft, uint256 fa) = _swapT4TCore(legs[i].amountIn, 0, legs[i].path, to, deadline);
legOuts[i] = a[a.length - 1];
totalOut += legOuts[i];
// One Swap per leg with THIS leg's own fee token — legs can diverge (mid-quote routes).
emit Swap(msg.sender, tokenIn, tokenOut, legs[i].amountIn, legOuts[i], ft, fa);
}
if (totalOut < minTotalOut) revert InsufficientOutput();
}
/// @notice ETH-in split fill. `msg.value` must equal the sum of leg inputs; every `path[0] == WETH`.
function swapExactETHForTokensSplit(SwapLeg[] calldata legs, uint256 minTotalOut, address to, uint256 deadline)
external
payable
nonReentrant
returns (uint256[] memory legOuts, uint256 totalOut)
{
(address tokenIn, address tokenOut, uint256 totalIn) = _validateLegs(legs);
if (tokenIn != WETH) revert InvalidPath();
if (msg.value != totalIn) revert ValueMismatch();
legOuts = new uint256[](legs.length);
for (uint256 i; i < legs.length; ++i) {
(uint256[] memory a, address ft, uint256 fa) =
_swapETHForTokensCore(legs[i].amountIn, 0, legs[i].path, to, deadline);
legOuts[i] = a[a.length - 1];
totalOut += legOuts[i];
emit Swap(msg.sender, WETH, tokenOut, legs[i].amountIn, legOuts[i], ft, fa);
}
if (totalOut < minTotalOut) revert InsufficientOutput();
}
/// @notice Token-in → ETH-out split fill. Pulls the sum in one `transferFrom`; every `path[last] == WETH`.
function swapExactTokensForETHSplit(SwapLeg[] calldata legs, uint256 minTotalOut, address to, uint256 deadline)
external
nonReentrant
returns (uint256[] memory legOuts, uint256 totalOut)
{
(address tokenIn, address tokenOut, uint256 totalIn) = _validateLegs(legs);
if (tokenOut != WETH) revert InvalidPath();
IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), totalIn);
legOuts = new uint256[](legs.length);
for (uint256 i; i < legs.length; ++i) {
(uint256 net, uint256 fa, address ft) =
_swapTokensForETHCore(legs[i].amountIn, 0, legs[i].path, to, deadline);
legOuts[i] = net;
totalOut += net;
// One Swap per leg, so the indexer can treat a split like sequential singles. The fee token
// comes from the leg rather than being assumed to be WETH: ETH-out is the quote leg
// only while WETH outranks the input, and `quoteRank` is owner-mutable.
emit Swap(msg.sender, tokenIn, WETH, legs[i].amountIn, net, ft, fa);
}
if (totalOut < minTotalOut) revert InsufficientOutput();
}
/// @dev Shared validation: legs non-empty and within the cap, no zero-amount leg, and every leg
/// shares the same input (`path[0]`) and final output (`path[last]`) asset. Returns those two
/// endpoints and the summed input.
function _validateLegs(SwapLeg[] calldata legs)
private
pure
returns (address tokenIn, address tokenOut, uint256 totalIn)
{
uint256 n = legs.length;
if (n == 0) revert NoLegs();
if (n > MAX_SPLIT_LEGS) revert TooManyLegs();
tokenIn = legs[0].path[0];
tokenOut = legs[0].path[legs[0].path.length - 1];
for (uint256 i; i < n; ++i) {
address[] calldata p = legs[i].path;
if (legs[i].amountIn == 0) revert NoLegs();
// `tokenIn`/`tokenOut` are read FROM leg 0, so comparing leg 0 against them is a
// tautology. The zero-amount check and the running total still have to run for it.
if (i != 0 && (p[0] != tokenIn || p[p.length - 1] != tokenOut)) revert LegMismatch();
totalIn += legs[i].amountIn;
}
}
/// @dev Pull `amountIn` and report what actually arrived — the difference is the token's own tax.
function _pullRealised(address token, uint256 amountIn) private returns (uint256 received) {
uint256 balBefore = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransferFrom(msg.sender, address(this), amountIn);
received = IERC20(token).balanceOf(address(this)) - balBefore;
}
/// @dev Skim `protocolFeeBps` of `grossOut` of `tokenOut` to the collector, enforce the net min, pay `to`.
/// @dev Output-side settle: protocol fee AND any creator fee off `grossOut` (the quote leg),
/// enforce the net floor, deliver net to `to`. Returns net + the PROTOCOL fee alone — the
/// {Swap} `feeAmount` is protocol-only, so creator fees never inflate rakeback/points.
function _takeOutputFee(address tokenIn, address tokenOut, uint256 grossOut, uint256 amountOutMin, address to)
private
returns (uint256 net, uint256 protocolFee)
{
protocolFee = (grossOut * protocolFeeBps) / BPS_DENOM;
uint256 creatorTotal = _skimCreators(tokenIn, tokenOut, tokenOut, grossOut);
net = grossOut - protocolFee - creatorTotal;
if (net < amountOutMin) revert InsufficientOutput();
IERC20(tokenOut).safeTransfer(collector, protocolFee);
IERC20(tokenOut).safeTransfer(to, net);
}
/// @dev Output-side settle for the FEE-ON-TRANSFER entrypoints: identical to {_takeOutputFee}
/// except the floor is enforced on what `to` ACTUALLY RECEIVES — measured as a balance delta
/// at `to` — rather than on the nominal net, so a `tokenOut` that taxes its own transfers
/// cannot deliver less than `amountOutMin`. The returned `delivered` is that measured amount,
/// and it is what the {Swap} event and the caller both read.
function _takeOutputFeeRealised(
address tokenIn,
address tokenOut,
uint256 grossOut,
uint256 amountOutMin,
address to
) private returns (uint256 delivered, uint256 protocolFee) {
protocolFee = (grossOut * protocolFeeBps) / BPS_DENOM;
uint256 creatorTotal = _skimCreators(tokenIn, tokenOut, tokenOut, grossOut);
uint256 net = grossOut - protocolFee - creatorTotal;
IERC20(tokenOut).safeTransfer(collector, protocolFee);
uint256 balBefore = IERC20(tokenOut).balanceOf(to);
IERC20(tokenOut).safeTransfer(to, net);
delivered = IERC20(tokenOut).balanceOf(to) - balBefore;
if (delivered < amountOutMin) revert InsufficientOutput();
}
/// @dev Fee-on-transfer twin of {_swapViaMidQuote}: TOKEN_A→…→QUOTE→…→TOKEN_B where either long-tail
/// endpoint may tax its own transfers. Same guarantee — the fee is taken ONCE, from the
/// quote proceeds of leg A — but every amount is a measured balance delta instead of a
/// nominal router return, and `amountOutMin` is enforced on what `to` actually receives.
/// `amountIn` is the REALISED amount of `path[0]` this contract already holds.
function _swapViaMidQuoteFot(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) private returns (uint256 delivered) {
uint256 j = _firstMidQuote(path);
address feeToken = path[j];
address tokenOut = path[path.length - 1];
IERC20(path[0]).forceApprove(address(router), amountIn);
uint256 quoteBefore = IERC20(feeToken).balanceOf(address(this));
router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
amountIn, 0, path[:j + 1], address(this), deadline
);
// Quote assets are curated and non-taxing, so this delta is the honest gross — the same base
// the non-FoT path takes its fee from.
uint256 gross = IERC20(feeToken).balanceOf(address(this)) - quoteBefore;
uint256 feeAmount = (gross * protocolFeeBps) / BPS_DENOM;
IERC20(feeToken).safeTransfer(collector, feeAmount);
uint256 creatorTotal = _skimCreators(path[0], tokenOut, feeToken, gross);
uint256 swapAmount = gross - feeAmount - creatorTotal;
IERC20(feeToken).forceApprove(address(router), swapAmount);
uint256 outBefore = IERC20(tokenOut).balanceOf(to);
router.swapExactTokensForTokensSupportingFeeOnTransferTokens(swapAmount, 0, path[j:], to, deadline);
delivered = IERC20(tokenOut).balanceOf(to) - outBefore;
if (delivered < amountOutMin) revert InsufficientOutput();
emit Swap(msg.sender, path[0], tokenOut, amountIn, delivered, feeToken, feeAmount);
}
/// @dev Input-side settle: protocol fee AND any creator fee off `amountIn` (the quote leg);
/// returns the amount left to swap and the protocol fee alone.
function _takeInputFee(address tokenIn, address tokenOut, uint256 amountIn)
private
returns (uint256 swapAmount, uint256 protocolFee)
{
protocolFee = (amountIn * protocolFeeBps) / BPS_DENOM;
IERC20(tokenIn).safeTransfer(collector, protocolFee);
uint256 creatorTotal = _skimCreators(tokenIn, tokenOut, tokenIn, amountIn);
swapAmount = amountIn - protocolFee - creatorTotal;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {OwnableUpgradeable} from "./OwnableUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step
struct Ownable2StepStorage {
address _pendingOwner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable2Step")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant Ownable2StepStorageLocation = 0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00;
function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) {
assembly {
$.slot := Ownable2StepStorageLocation
}
}
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
function __Ownable2Step_init() internal onlyInitializing {
}
function __Ownable2Step_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
return $._pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
$._pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
Ownable2StepStorage storage $ = _getOwnable2StepStorage();
delete $._pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/interfaces/ICreatorFeeRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title ICreatorFeeRegistry
/// @notice Which tokens have a creator fee, and who the creator is. Populated only by authorized
/// registrar contracts, never by end users
/// (creator-fees v2).
interface ICreatorFeeRegistry {
/// @notice The address the FeeRouter branches on: the current creator of `token`, or `address(0)`
/// when the token is unregistered or its fee is disabled. One SLOAD on the swap hot path.
function activeCreator(address token) external view returns (address);
/// @notice The current creator of `token` REGARDLESS of the disabled flag, or `address(0)` when the
/// token was never registered.
/// @dev The claim-side counterpart to {activeCreator}, and the two must not be conflated. Disabling a
/// token is a statement about FUTURE accrual — it stops the FeeRouter skimming, which is what
/// {activeCreator} returning zero is for. It is not a statement about money already earned, and
/// gating `CreatorFeeVault.claim` on {activeCreator} made it one: a disabled token's creator lost
/// access to fees already collected, indefinitely, at the registry owner's discretion.
/// This is a policy call rather than a correctness one: earned is earned, and withholding money
/// already earned as leverage is not a posture this protocol takes. So the vault reads THIS, the
/// router reads {activeCreator}, and disabling does exactly one thing.
function creatorOf(address token) external view returns (address);
/// @notice Register `token` with `creator`. Registrar-only; sets the initial (and, per v2, only)
/// creator. Reverts on a zero creator or a re-register.
function register(address token, address creator) external;
/**
* @notice Register the CALLING TOKEN with its creator, while open registration is on.
* @dev ON THE INTERFACE BECAUSE THIS IS THE ONE A THIRD PARTY INTEGRATES AGAINST. `register` is
* for the registrar; this is the open path, and an integrator reading only this interface
* needs to be able to see it.
* @param creator who receives the fee. The entry is keyed on `msg.sender`, so a token can only ever
* register itself.
*/
function registerSelf(address creator) external;
/// @notice True while any token may register itself. Off by default.
function openRegistration() external view returns (bool);
}
src/interfaces/ICreatorFeeVault.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title ICreatorFeeVault
/// @notice Claim-based escrow where creator fees accrue per token, in quote assets. The FeeRouter
/// transfers the quote asset in and then records it; creators pull (creator-fees v2).
/// @dev THE SKIM IS NOT PASSIVE. {notifyDeposit} is depositor-gated and the FeeRouter calls it
/// unconditionally, with no try/catch, so the vault has to admit the router for a swap on a
/// registered token to complete. It is not wrapped deliberately: the quote asset is transferred in
/// FIRST and the entitlement recorded second, so a swallowed revert would leave that balance here
/// credited to nobody. {isDepositor} is exposed instead, so `FeeRouter.setCreatorFeeConfig` can
/// check the wiring before a fee is armed against this vault.
interface ICreatorFeeVault {
/// @notice Record `amount` of `quoteAsset` accrued to `token`'s creator. The caller MUST have
/// already transferred the `amount` in. Depositor-gated (the FeeRouter).
function notifyDeposit(address token, address quoteAsset, uint256 amount) external;
/// @notice Whether `depositor` may call {notifyDeposit}. Read by `FeeRouter.setCreatorFeeConfig`,
/// which refuses a live creator fee against a vault that would reject its deposits.
function isDepositor(address depositor) external view returns (bool);
}
src/interfaces/IMotoSwapRouter02.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.26;
/// @notice MotoSwap router interface (Router01 + Router02 merged).
interface IMotoSwapRouter02 {
function factory() external view returns (address);
function WETH() 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);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(uint256 amountOutMin, address[] calldata path, address to, uint256 deadline)
external
payable
returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(uint256 amountOut, address[] calldata path, address to, uint256 deadline)
external
payable
returns (uint256[] memory amounts);
function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external pure returns (uint256 amountB);
function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut)
external
view
returns (uint256 amountOut);
function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
external
view
returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
src/interfaces/IPermit2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title IPermit2 (SignatureTransfer subset)
/// @notice The slice of Uniswap's canonical Permit2 that the FeeRouter's signature-swap
/// entrypoints (`swapExactTokensFor*Permit2`) depend on.
/// @dev Declared in-tree rather than vendoring the whole Permit2 package: the FeeRouter only ever calls
/// `permitTransferFrom`, and pulling in the upstream repo would add a second Solidity-version
/// pragma and a large unused surface for one function. Struct layouts and the function selector
/// match Uniswap's `ISignatureTransfer` exactly — they are consensus-critical, since the signature
/// the user's wallet produces is hashed over these fields by the real Permit2 deployment.
interface IPermit2 {
/// @notice The token and maximum amount a signature authorises.
struct TokenPermissions {
address token;
uint256 amount;
}
/// @notice A single-use transfer authorisation.
/// @dev The signed digest also binds `spender` — the address that calls `permitTransferFrom`, i.e.
/// the adapter — so a signature is valid only for the contract it was made for.
struct PermitTransferFrom {
TokenPermissions permitted;
uint256 nonce;
uint256 deadline;
}
/// @notice Where the pulled tokens go, and how much of the permitted maximum to actually move.
struct SignatureTransferDetails {
address to;
uint256 requestedAmount;
}
/// @notice Pull `transferDetails.requestedAmount` of `permit.permitted.token` from `owner` to
/// `transferDetails.to`, authorised by `signature`.
/// @dev Reverts if the signature is invalid for `(permit, msg.sender, owner)`, if `permit.deadline`
/// has passed, if `permit.nonce` was already used, or if `requestedAmount > permitted.amount`.
function permitTransferFrom(
PermitTransferFrom calldata permit,
SignatureTransferDetails calldata transferDetails,
address owner,
bytes calldata signature
) external;
/// @notice EIP-712 domain separator of the Permit2 deployment. Exposed for off-chain signers.
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
src/interfaces/IQuoteAssetRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
/// @title IQuoteAssetRegistry
/// @notice Admin-managed set of "quote" assets (ETH/WETH/USDT/USDC/MOTO). Every MotoSwap pair must
/// have one side in this set; all non-LP protocol fees are collected on that side.
interface IQuoteAssetRegistry {
function isQuote(address token) external view returns (bool);
/// @notice Fee-side priority of a quote asset (higher = more senior). When BOTH legs of a swap
/// are quote assets, the FeeRouter charges the fee on the higher-ranked side, so protocol
/// fees concentrate in the more liquid quote. Defaults to 0 (unranked), which leaves the
/// default of charging the output side.
function quoteRank(address token) external view returns (uint256);
}
src/interfaces/IWETH.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.26;
/// @notice Minimal Wrapped-ETH interface used by the router.
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
src/upgrade/UUPSRenounceable.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;
import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
/// @title UUPSRenounceable
/// @notice UUPS mix-in adding an operations-preserving "upgrade-to-immutable" switch.
/// @dev A contract that shares its single `owner` between upgrade authority AND live operational levers
/// (emission schedules, fee buckets, keepers, …) cannot use `renounceOwnership` to freeze upgrades,
/// because renouncing ownership would also end those operations permanently. This base provides an
/// INDEPENDENT one-way flag: once `_renounceUpgradeability()` is called, `_requireUpgradable()` makes
/// `_authorizeUpgrade` revert forever, while ownership and every operational setter keep working.
/// Uses ERC-7201 namespaced storage, so it adds ZERO sequential storage slots to any inheriting
/// contract (no layout impact, no `__gap` accounting needed for it).
///
/// @dev Not every UUPS contract in this repo inherits this mix-in; one implements the same mechanism
/// with its own ERC-7201 slot and its own `_authorizeUpgrade`. ERC-7201 storage is per-proxy and
/// the slots differ, so the two are independent.
abstract contract UUPSRenounceable is UUPSUpgradeable {
/// @custom:storage-location erc7201:motoswap.storage.UUPSRenounceable
/// @dev THE SECOND FIELD COSTS NO SLOT ANYWHERE, and that is the reason this lives here rather than
/// in each contract. The struct sits at an ERC-7201 namespaced slot, so it is not part of any
/// inheriting contract's sequential layout: adding a field consumes no `__gap`, shifts nothing,
/// and leaves every inheriting contract's storage layout unchanged. `bool` + `address` is
/// 21 of the slot's 32 bytes, so both reads share one `SLOAD`.
struct RenounceStorage {
bool renounced;
address upgradeAuthority;
/// @dev Set on the FIRST non-zero authority and never cleared. Once true, a zero authority is
/// refused - see {_setUpgradeAuthority}. `bool` + `address` + `bool` is 22 of the slot's
/// 32 bytes, so all three still share one `SLOAD`.
bool splitArmed;
}
// keccak256(abi.encode(uint256(keccak256("motoswap.storage.UUPSRenounceable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant RENOUNCE_STORAGE_SLOT = 0xa5942d98813e409540b6788a82bc0bf3bf6bb19b1d41d7399297cc0ab99b7c00;
event UpgradesRenounced();
event UpgradeAuthoritySet(address indexed previousAuthority, address indexed newAuthority);
error UpgradesAreRenounced();
/// @dev `caller` is not the upgrade authority (nor the owner, while no authority is set).
error NotUpgradeAuthority(address caller);
/// @dev The split is armed, so the authority may not be set back to zero.
error UpgradeSplitArmed();
/// @dev The authority must be a contract. Both the setter and the renounce are gated on it, so an
/// address with no code behind it would leave the proxy with no reachable upgrade path.
error UpgradeAuthorityNotAContract(address authority);
function _renounceStorage() private pure returns (RenounceStorage storage $) {
assembly {
$.slot := RENOUNCE_STORAGE_SLOT
}
}
/// @notice True once the implementation can never be upgraded again (one-way).
function upgradesRenounced() public view returns (bool) {
return _renounceStorage().renounced;
}
/// @dev Call from `_authorizeUpgrade` to block upgrades once renounced.
function _requireUpgradable() internal view {
if (_renounceStorage().renounced) revert UpgradesAreRenounced();
}
/// @notice Who may upgrade this proxy. **Zero means the owner**, which is what every already-deployed
/// contract reads, so this whole mechanism is inert until somebody sets it.
///
/// @dev Separating the upgrade authority from the owner lets a contract put upgrades behind a
/// timelock while ordinary operational setters stay with the owner. Both gate on the same
/// `onlyOwner` otherwise, so handing `owner` to a timelock would delay every setter too.
///
/// INTERNAL HERE. A contract that takes the split declares its own one-line public
/// override; one that does not take the split exports nothing, rather than carrying a
/// getter whose answer is zero forever in its runtime and its ABI.
function _upgradeAuthority() internal view returns (address) {
return _renounceStorage().upgradeAuthority;
}
/// @dev Not every inheriting contract adopts this. One keeps `onlyOwner` on both its upgrade and
/// its renounce and never writes its authority field, because adopting the split does not fit
/// inside its runtime size limit; its own docstring records what it relies on instead.
///
/// @dev Call from `_authorizeUpgrade` INSTEAD of `onlyOwner` + {_requireUpgradable}. Pass the
/// contract's own owner: this mixin deliberately knows nothing about how ownership is stored,
/// so it stays usable by a contract that is not `Ownable` at all.
///
/// THE ZERO FALLBACK IS LOAD-BEARING, not a convenience. A contract that takes the authority
/// at `initialize` has it from the start, but a proxy that predates this mix-in reads the slot
/// as zero once the introducing implementation goes live. Without the fallback it would have
/// no reachable upgrade path and no way to set the field, because setting it is itself gated.
function _requireUpgrader(address owner_) internal view {
_requireUpgradable();
address authority = _renounceStorage().upgradeAuthority;
if (msg.sender != (authority == address(0) ? owner_ : authority)) revert NotUpgradeAuthority(msg.sender);
}
/// @dev The inheriting contract exposes the external entrypoint GATED ON THE CURRENT AUTHORITY,
/// rather than on the owner. So once an authority is installed, changing it is that
/// authority's move and carries whatever delay that authority imposes. There is no owner
/// override: if the installed authority can never execute, upgrades on this contract end
/// permanently. That is the accepted cost of the split.
/**
* @dev ZERO IS REFUSED ONCE THE SPLIT IS ARMED, so the first write may be zero and a later one may
* not. Handovers are non-zero to non-zero.
*
* `_requireUpgrader` reads a zero authority as "the owner keeps authority", so an unconditional
* write of zero would return the upgrade, the setter and the irreversible renounce to the owner
* in one call, all three being gated on `_requireUpgrader`. The zero fallback therefore stays
* reachable for the one case it exists for - a proxy whose slot reads zero before the
* introducing upgrade writes it - and becomes unreachable once an authority has been installed.
*
* AND A CODELESS AUTHORITY IS REFUSED ON EVERY PATH, setters and initializers alike. An address
* with nothing behind it cannot be corrected, because correcting it is gated on it.
*/
function _setUpgradeAuthority(address newAuthority) internal {
RenounceStorage storage $ = _renounceStorage();
if (newAuthority == address(0)) {
if ($.splitArmed) revert UpgradeSplitArmed();
} else {
if (newAuthority.code.length == 0) revert UpgradeAuthorityNotAContract(newAuthority);
$.splitArmed = true;
}
emit UpgradeAuthoritySet($.upgradeAuthority, newAuthority);
$.upgradeAuthority = newAuthority;
}
/// @notice Whether a non-zero upgrade authority has ever been installed, after which zero is refused.
/// @dev Exposed so a deployment check can tell "never armed" from "armed and pointing somewhere",
/// which `upgradeAuthority() == address(0)` alone cannot distinguish.
function upgradeSplitArmed() public view returns (bool) {
return _renounceStorage().splitArmed;
}
/// @dev One-way: permanently disables `_authorizeUpgrade`. Ownership and admin ops are unaffected.
/// The inheriting contract exposes the access-gated external entrypoint that calls this.
function _renounceUpgradeability() internal {
_renounceStorage().renounced = true;
emit UpgradesRenounced();
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 999999,
"details": {
"yulDetails": {
"optimizerSteps": "dhfoDgvulfnTUtnIf",
"stackAllocation": true
}
},
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"solady/=lib/solady/src/",
"forge-std/=lib/forge-std/src/",
"@layerzerolabs/oapp-evm/=lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/",
"@layerzerolabs/lz-evm-protocol-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/",
"@layerzerolabs/lz-evm-messagelib-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/messagelib/",
"@layerzerolabs/oft-evm/=lib/devtools/packages/oft-evm/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.