Robinhood MainnetChain ID: 4663
Contract detail

FeeCalculatorDispatcher

Live Robinhood Chain account facts for 0x04cdded8…c279d613 with at least 2 observed transactions. The history total is updating as indexing continues.

Address type
Smart contract
Transactions
2+ observed
First indexed block
#28345533
Latest indexed block
#72851825
History coverage
Recent activity available; total is catching up
Emitted events
79
Verification
Verified
Compiler
v0.8.26+commit.8a97fa7a
Verification match
full
Creation transaction
0x0952e684…dae8ec11
Created at block
#28345525
Language
solidity
EVM version
cancun
License
none
Compiler optimization
Enabled · 777 runs
Related activity

Transactions

Verified contract

Contract source code

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import {Ownable} from '@solady/auth/Ownable.sol';

import {AccessControl} from '@openzeppelin/contracts/access/AccessControl.sol';

import {BalanceDelta} from '@uniswap/v4-core/src/types/BalanceDelta.sol';
import {PoolId} from '@uniswap/v4-core/src/types/PoolId.sol';
import {PoolKey} from '@uniswap/v4-core/src/types/PoolKey.sol';
import {SwapParams} from '@uniswap/v4-core/src/types/PoolOperation.sol';

import {IFeeCalculator} from '@flaunch-interfaces/IFeeCalculator.sol';
import {ProtocolRoles} from '@flaunch/libraries/ProtocolRoles.sol';

/**
 * A routing {IFeeCalculator} that occupies the protocol's single global fee calculator slot
 * and dispatches per pool to a registered sub-calculator.
 *
 * The protocol has exactly one `feeCalculator` slot on the {PositionManager} (owner-set), so
 * supporting multiple gating/fee economics side by side - e.g. a spend-gated game launch next
 * to ordinary launches - requires a dispatcher in that slot. Routing is chosen at flaunch time:
 * a launch that wants a specific sub-calculator prefixes its `feeCalculatorParams` with
 * {ROUTING_PREFIX} followed by the sub-calculator address and that calculator's own params.
 * Any launch without the prefix routes to the default calculator, preserving existing
 * behaviour exactly.
 *
 * The default calculator is expected to be stateless (e.g. {StaticFeeCalculator}): the
 * dispatcher does not forward `setFlaunchParams` to it, so pools already configured before the
 * dispatcher was installed keep working - their swaps route to the same stateless default.
 */
contract FeeCalculatorDispatcher is IFeeCalculator, Ownable, AccessControl {
    error CalculatorNotRegistered(address _calculator);
    error CallerNotPositionManager();
    error InvalidCalculator();

    event CalculatorRegistered(address indexed _calculator, bool _registered);
    event DefaultCalculatorUpdated(address _calculator);
    event PoolCalculatorSet(PoolId _poolId, address indexed _calculator);
    /// A pool that already had a route was pointed at a different one; see {setFlaunchParams}
    event RouteChanged(PoolId _poolId, address indexed _previousCalculator, address indexed _newCalculator);

    /// Marker that a launch's `feeCalculatorParams` opts into routing:
    /// `abi.encode(ROUTING_PREFIX, address subCalculator, bytes subParams)`
    bytes32 public constant ROUTING_PREFIX = keccak256('flaunch.dispatcher.route.v1');

    /// The stateless calculator used for every pool without an explicit route
    IFeeCalculator public defaultCalculator;

    /// Owner-curated set of calculators that launches are allowed to route to
    mapping(address _calculator => bool _registered) public registeredCalculators;

    /// The calculator each pool routes to; unset means the default calculator
    mapping(PoolId _poolId => IFeeCalculator _calculator) public poolCalculator;

    /**
     * Sets the default calculator and grants the deployer admin control.
     *
     * @param _defaultCalculator The stateless calculator handling all unrouted pools
     */
    constructor(
        IFeeCalculator _defaultCalculator
    ) {
        if (address(_defaultCalculator) == address(0)) {
            revert InvalidCalculator();
        }

        defaultCalculator = _defaultCalculator;

        // Grant the deployer the admin role and contract ownership
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        _initializeOwner(msg.sender);
    }

    /**
     * Returns the swap fee for a pool by delegating to the pool's routed calculator.
     *
     * @param _poolKey The key for the pool
     * @param _params The swap parameters
     * @param _baseFee The base fee passed in by the {PositionManager}
     *
     * @return swapFee_ The fee determined by the routed calculator
     */
    function determineSwapFee(
        PoolKey memory _poolKey,
        SwapParams memory _params,
        uint24 _baseFee
    ) public view returns (uint24 swapFee_) {
        return _resolve(_poolKey.toId()).determineSwapFee(_poolKey, _params, _baseFee);
    }

    /**
     * Reports a swap to the pool's routed calculator.
     *
     * @param _sender The swap sender reported by the hook
     * @param _poolKey The key for the pool being swapped against
     * @param _params The swap parameters
     * @param _delta The swap's balance delta
     * @param _hookData Arbitrary swap data forwarded to the routed calculator
     */
    function trackSwap(
        address _sender,
        PoolKey calldata _poolKey,
        SwapParams calldata _params,
        BalanceDelta _delta,
        bytes calldata _hookData
    ) public {
        // Only the PositionManager is permitted to report swaps
        if (!hasRole(ProtocolRoles.POSITION_MANAGER, msg.sender)) {
            revert CallerNotPositionManager();
        }

        _resolve(_poolKey.toId()).trackSwap(_sender, _poolKey, _params, _delta, _hookData);
    }

    /**
     * Records a pool's routing choice at flaunch time and forwards the sub-calculator's own
     * params to it. Params without the {ROUTING_PREFIX} leave the pool on the default
     * calculator and are intentionally not forwarded (the default is stateless).
     *
     * @param _poolId The ID of the pool being configured
     * @param _params Either empty or un-prefixed params (→ default), or
     *                `abi.encode(ROUTING_PREFIX, address subCalculator, bytes subParams)`
     */
    function setFlaunchParams(
        PoolId _poolId,
        bytes calldata _params
    ) external override {
        // Only the PositionManager is permitted to set flaunch parameters
        if (!hasRole(ProtocolRoles.POSITION_MANAGER, msg.sender)) {
            revert CallerNotPositionManager();
        }

        /**
         * A pool's route is deliberately MUTABLE, and a once-only guard was tried here and
         * withdrawn. Recording the write would have to happen before the prefix check below to
         * cover unrouted pools, which makes a pool id markable before that pool exists — and pool
         * ids are predictable, because {Flaunch} clones its memecoin deterministically from a
         * public sequential counter. A role holder could therefore mark the NEXT id, and since
         * the reverted flaunch rolls that counter back, every retry re-derives the same id and
         * dies the same way: a permanent halt of the launch path, not a bounded blast radius.
         *
         * Validating that the pool exists first is not available as a fix: the {PositionManager}
         * deployment this dispatcher serves configures its calculators BEFORE calling
         * `poolManager.initialize`, so a "pool must exist" check would refuse every launch.
         * Later PositionManager revisions reverse that order, so no single check satisfies both.
         *
         * What bounds the risk instead is reachability. The pool id is an argument, but the only
         * caller that can pass an arbitrary one is a POSITION_MANAGER role holder, and that role
         * is grantable solely by DEFAULT_ADMIN_ROLE. A launching user reaches this function only
         * through `flaunch`, which derives the pool id internally — nobody can name a pool other
         * than the one they are creating. A re-route therefore requires a privileged key, and
         * such a key can already lift a gate by sanctioned means anyway: the calculator's owner
         * may zero any pool's signer, which stops enforcement outright.
         *
         * Replacing an existing route additionally announces itself through {RouteChanged}.
         * Note the limit of that signal: giving a pool its FIRST route emits only
         * {PoolCalculatorSet}, which is what an ordinary launch emits too, so a pool that was
         * never routed can be routed later without tripping the alarm. Distinguishing those is
         * an off-chain job — the pool's age gives it away — and it is why the alarm is worth
         * having but is not a substitute for custody of the admin key.
         */

        // A routed opt-in is at least four words: prefix, calculator, params offset and length.
        // Anything shorter, or without the exact prefix marker, routes to the default and is
        // left undecoded - legacy launches must never be able to brick on a decode revert.
        if (_params.length < 128 || bytes32(_params[:32]) != ROUTING_PREFIX) {
            return;
        }

        (, address subCalculator, bytes memory subParams) = abi.decode(_params, (bytes32, address, bytes));

        // Routing is only permitted to calculators the owner has explicitly registered
        if (!registeredCalculators[subCalculator]) {
            revert CalculatorNotRegistered(subCalculator);
        }

        // Record the route and hand the sub-calculator its own params. Replacing an existing
        // route is the case worth alerting on — a launch writing its own route for the first
        // time is ordinary, so {RouteChanged} is reserved for a genuine change of destination.
        address previousCalculator = address(poolCalculator[_poolId]);
        poolCalculator[_poolId] = IFeeCalculator(subCalculator);
        emit PoolCalculatorSet(_poolId, subCalculator);

        if (previousCalculator != address(0) && previousCalculator != subCalculator) {
            emit RouteChanged(_poolId, previousCalculator, subCalculator);
        }

        IFeeCalculator(subCalculator).setFlaunchParams(_poolId, subParams);
    }

    /**
     * Adds or removes a calculator from the routing allowlist.
     *
     * @param _calculator The calculator to update
     * @param _registered True to allow launches to route to it
     */
    function setCalculatorRegistered(
        address _calculator,
        bool _registered
    ) external onlyOwner {
        if (_calculator == address(0)) {
            revert InvalidCalculator();
        }

        registeredCalculators[_calculator] = _registered;
        emit CalculatorRegistered(_calculator, _registered);
    }

    /**
     * Replaces the default calculator handling all unrouted pools.
     *
     * @param _defaultCalculator The new default; must be stateless like {StaticFeeCalculator}
     */
    function setDefaultCalculator(
        IFeeCalculator _defaultCalculator
    ) external onlyOwner {
        if (address(_defaultCalculator) == address(0)) {
            revert InvalidCalculator();
        }

        defaultCalculator = _defaultCalculator;
        emit DefaultCalculatorUpdated(address(_defaultCalculator));
    }

    /**
     * Resolves the calculator a pool routes to, falling back to the default.
     *
     * @param _poolId The ID of the pool
     *
     * @return calculator_ The calculator responsible for the pool
     */
    function _resolve(
        PoolId _poolId
    ) internal view returns (IFeeCalculator calculator_) {
        calculator_ = poolCalculator[_poolId];
        if (address(calculator_) == address(0)) {
            calculator_ = defaultCalculator;
        }
    }
}