Skip to content
Verified contractExactMIT

FlatAndPerformanceFeeStrategy

Address0x454f5f89fd6cd74d001a8a128ac84bdb2b6bc530
Balance

0 ETH

 

Transactions

5

 

Compiler

solc 0.8.34

 

Same code

2 more contracts

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,724,755
Creation transaction
0x2c1e754e6c…ac967922c3

src/modules/hooks/fee/feeStrategies/FlatAndPerformanceFeeStrategy.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

import {IFeeStrategy, FeeContext} from "src/interfaces/IFee.sol";
import {FlatBpsFeeBase} from "./FlatBpsFeeBase.sol";
import {PerformanceFeeBase} from "./PerformanceFeeBase.sol";
import {YoungOwnable} from "src/core/Ownable.sol";
import {YieldOpType} from "src/modules/hooks/fee/feeDecoders/AaveDecoder.sol";

/**
 * @title FlatAndPerformanceFeeStrategy
 * @notice Configurable fee strategy: flat and/or performance per operation type
 * @dev TrackingEnabled is decoupled from performanceFeeBps so the owner can suspend the
 *      performance fee rate without losing depositBasis history to re-enabled later without stale data
 *      Both deposit and withdraw selectors must be registered to the same instance
 *      so depositBasis state is shared for yield calculation.
 * @author Young Platform
 */
contract FlatAndPerformanceFeeStrategy is
    IFeeStrategy,
    FlatBpsFeeBase,
    PerformanceFeeBase,
    YoungOwnable
{
    struct FeeConfig {
        bool flatEnabled;
        bool performanceEnabled;
    }

    bool public trackingEnabled;

    mapping(YieldOpType => FeeConfig) public feeConfigs;

    error PerformanceFeeNotSupportedForOpType(YieldOpType opType);

    event FeeConfigSet(
        YieldOpType indexed opType,
        bool flatEnabled,
        bool performanceEnabled
    );
    event TrackingEnabled(bool enabled);
    event FlatFeeBpsSet(uint256 bps);
    event PerformanceFeeBpsSet(uint256 bps);

    constructor(
        address owner_,
        uint256 flatBps_,
        uint256 performanceBps_,
        address authorizedHook_
    )
        FlatBpsFeeBase(flatBps_)
        PerformanceFeeBase(performanceBps_, authorizedHook_)
        YoungOwnable(owner_)
    {
        trackingEnabled = performanceBps_ > 0;
    }

    /// @dev Performance fee is only meaningful for DEPOSIT/WITHDRAW
    ///      revert when it's mistakenly enabled for BORROW/REPAY
    function setFeeConfig(
        YieldOpType opType,
        bool flatEnabled,
        bool performanceEnabled
    ) external onlyOwner {
        require(
            !performanceEnabled ||
                opType == YieldOpType.DEPOSIT ||
                opType == YieldOpType.WITHDRAW,
            PerformanceFeeNotSupportedForOpType(opType)
        );

        feeConfigs[opType] = FeeConfig(flatEnabled, performanceEnabled);

        emit FeeConfigSet(opType, flatEnabled, performanceEnabled);
    }

    function setFlatFeeBps(uint256 bps) external onlyOwner {
        require(bps <= MAX_FLAT_BPS, FlatFeeBpsTooHigh());
        flatFeeBps = bps;

        emit FlatFeeBpsSet(bps);
    }

    /// @dev Activating a nonzero rate always turns tracking on
    ///      Setting bps back to 0 leaves trackingEnabled untouched, so basis
    ///      history keeps accruing while the fee is suspended.
    function setPerformanceFeeBps(uint256 bps) external onlyOwner {
        require(bps <= MAX_PERFORMANCE_BPS, PerformanceFeeBpsTooHigh());
        performanceFeeBps = bps;
        if (bps > 0 && !trackingEnabled) {
            trackingEnabled = true;
            emit TrackingEnabled(true);
        }

        emit PerformanceFeeBpsSet(bps);
    }

    function setTrackingEnabled(bool enabled) external onlyOwner {
        trackingEnabled = enabled;
        emit TrackingEnabled(enabled);
    }

    function calculateFee(
        address wallet,
        uint256,
        FeeContext calldata ctx
    ) external view override returns (uint256) {
        if (ctx.extraData.length == 0) return 0;

        YieldOpType opType = abi.decode(ctx.extraData, (YieldOpType));
        FeeConfig memory config = feeConfigs[opType];

        uint256 fee = 0;
        if (config.flatEnabled) fee += _flatFee(ctx);
        if (config.performanceEnabled) fee += _performanceFee(wallet, ctx);

        return fee;
    }

    function supportsAfterExecution() external view override returns (bool) {
        return trackingEnabled;
    }

    function afterExecution(
        address wallet,
        FeeContext calldata ctx
    ) external override onlyAuthorizedHook {
        if (ctx.extraData.length == 0) return;
        YieldOpType opType = abi.decode(ctx.extraData, (YieldOpType));

        if (opType == YieldOpType.DEPOSIT)
            _trackDeposit(wallet, ctx.token, ctx.amount);
        else if (opType == YieldOpType.WITHDRAW)
            _trackWithdraw(wallet, ctx.token, ctx.amount);
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.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 Ownable is Context {
    address private _owner;

    /**
     * @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.
     */
    constructor(address initialOwner) {
        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) {
        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 {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {Ownable} from "./Ownable.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 Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        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 {
        _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 {
        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/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

src/core/Ownable.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

import {Ownable2Step, Ownable} from "@openzeppelin/contracts/access/Ownable2Step.sol";

/**
 * @title Young Platform Ownable
 * @notice Implements OZ Ownable2Step but disable renounceOwnership
 * @author Young Platform
 */

contract YoungOwnable is Ownable2Step {
    constructor(address owner_) Ownable(owner_) {}

    function renounceOwnership() public pure override(Ownable) {
        revert("Not supported");
    }
}

src/interfaces/IFee.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

struct FeeContext {
    address token;
    uint256 amount;
    bytes extraData; // fee strategy specific
    bool skipBasisTracking; // charge fee but suppress afterExecution callback
    bool isWithdrawal; // set by decoders for withdrawal ops — used for per-token batch dedup
}

enum YieldOpType {
    DEPOSIT,
    WITHDRAW,
    BORROW,
    REPAY
}

/// @dev Carries the strategy address and decoded context for a single operation afterExecution callback.
struct StrategyCallbackData {
    address strategy;
    FeeContext ctx;
}

/// @dev interface for fee context decoders
interface IFeeDecoder {
    function decode(
        address wallet,
        address target,
        bytes4 selector,
        bytes calldata data
    ) external view returns (FeeContext memory ctx);
}

/// @dev interface for fee strategy modules - receives decoded context
interface IFeeStrategy {
    function calculateFee(
        address wallet,
        uint256 value,
        FeeContext calldata ctx
    ) external view returns (uint256 fee);

    /// @dev Returns true if this strategy needs afterExecution callbacks.
    function supportsAfterExecution() external view returns (bool);

    /// @dev Called after execution completes
    function afterExecution(address wallet, FeeContext calldata ctx) external;
}

/// @dev interface for fee policy modules
interface IFeePolicy {
    function adjustFee(
        address wallet,
        uint256 rawFee,
        FeeContext calldata ctx
    ) external view returns (uint256 fee);

    /// @dev Returns true if this policy needs afterExecution callbacks
    function supportsAfterExecution() external view returns (bool);

    function afterExecution(address wallet, uint256 finalFee) external;
}

/// @dev interface for fee strategy registry contract
interface IFeeStrategyChain {
    function getStrategy(
        bytes4 selector,
        address target
    ) external view returns (address strategy, address decoder);

    function setStrategy(
        bytes4 selector,
        address target,
        address strategy,
        address decoder
    ) external;
}

src/modules/hooks/fee/feeDecoders/AaveDecoder.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

import {IFeeDecoder, FeeContext, YieldOpType} from "src/interfaces/IFee.sol";

/**
 * @title AaveFeeDecoder
 * @notice Decodes aave interactions calldata into a FeeContext
 * @author Young Platform
 */
contract AaveFeeDecoder is IFeeDecoder {
    // bytes4(keccak256("supply(address,uint256,address,uint16)"));
    bytes4 constant DEPOSIT_SELECTOR = 0x617ba037;

    // bytes4(keccak256("withdraw(address,uint256,address)"));
    bytes4 constant WITHDRAW_SELECTOR = 0x69328dec;

    // bytes4(keccak256("borrow(address,uint256,uint256,uint16,address)"));
    bytes4 constant BORROW_SELECTOR = 0xa415bcad;

    // bytes4(keccak256("repay(address,uint256,uint256,address)"));
    bytes4 constant REPAY_SELECTOR = 0x573ade81;

    function decode(
        address wallet,
        address, // TODO can check target is aave pool
        bytes4 selector,
        bytes calldata data
    ) external pure override returns (FeeContext memory ctx) {
        if (data.length < 4) return ctx;

        if (selector == DEPOSIT_SELECTOR) {
            return _decodeDeposit(wallet, data);
        } else if (selector == WITHDRAW_SELECTOR) {
            return _decodeWithdraw(data);
        } else if (selector == REPAY_SELECTOR) {
            return _decodeRepay(data);
        } else if (selector == BORROW_SELECTOR) {
            return _decodeBorrow(data);
        }

        // empty ctx -> no fee is charged
    }

    // supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode)
    function _decodeDeposit(
        address wallet,
        bytes calldata supplyCalldata
    ) internal pure returns (FeeContext memory ctx) {
        address onBehalfOf;
        (ctx.token, ctx.amount, onBehalfOf, ) = abi.decode(
            supplyCalldata,
            (address, uint256, address, uint16)
        );
        ctx.extraData = abi.encode(YieldOpType.DEPOSIT);
        if (onBehalfOf != wallet) ctx.skipBasisTracking = true;
    }

    // withdraw(address asset, uint256 amount, address to)
    function _decodeWithdraw(
        bytes calldata withdrawCalldata
    ) internal pure returns (FeeContext memory ctx) {
        (ctx.token, ctx.amount, ) = abi.decode(
            withdrawCalldata,
            (address, uint256, address)
        );
        ctx.extraData = abi.encode(YieldOpType.WITHDRAW);
        ctx.isWithdrawal = true;
    }

    // repay(address asset, uint256 amount, uint256 interestRateMode, address onBehalfOf)
    function _decodeRepay(
        bytes calldata repayCalldata
    ) internal pure returns (FeeContext memory ctx) {
        (ctx.token, ctx.amount, , ) = abi.decode(
            repayCalldata,
            (address, uint256, uint256, address)
        );
        ctx.extraData = abi.encode(YieldOpType.REPAY);
    }

    // borrow(address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf)
    function _decodeBorrow(
        bytes calldata data
    ) internal pure returns (FeeContext memory ctx) {
        (ctx.token, ctx.amount, , , ) = abi.decode(
            data,
            (address, uint256, uint256, uint16, address)
        );
        ctx.extraData = abi.encode(YieldOpType.BORROW);
    }
}

src/modules/hooks/fee/feeStrategies/FlatBpsFeeBase.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

import {FeeContext} from "src/interfaces/IFee.sol";

/**
 * @title FlatBpsFeeBase
 * @notice Abstract base for strategies that include a flat basis-points fee component
 * @author Young Platform
 */
abstract contract FlatBpsFeeBase {
    uint256 public flatFeeBps;
    uint256 public constant BPS_DENOMINATOR = 10_000;
    uint256 public constant MAX_FLAT_BPS = 1_000;

    error FlatFeeBpsTooHigh();

    constructor(uint256 flatFeeBps_) {
        if (flatFeeBps_ > MAX_FLAT_BPS) revert FlatFeeBpsTooHigh();
        flatFeeBps = flatFeeBps_;
    }

    function _flatFee(FeeContext calldata ctx) internal view returns (uint256) {
        return (ctx.amount * flatFeeBps) / BPS_DENOMINATOR;
    }
}

src/modules/hooks/fee/feeStrategies/PerformanceFeeBase.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;

import {FeeContext} from "src/interfaces/IFee.sol";

/**
 * @title PerformanceFeeBase
 * @notice Abstract base for strategies that charge a performance fee on realised yield.
 * @dev Tracks each wallet's deposit basis per token. Yield = withdraw amount - basis.
 *      Only the authorizedHook may call afterExecution to update basis.
 * @author Young Platform
 */
abstract contract PerformanceFeeBase {
    uint256 public performanceFeeBps;
    address public immutable authorizedHook;

    mapping(address => mapping(address => uint256)) internal depositBasis;

    uint256 public constant MAX_PERFORMANCE_BPS = 5_000;

    error PerformanceFeeBpsTooHigh();
    error UnauthorizedCaller(address caller);

    constructor(uint256 performanceFeeBps_, address authorizedHook_) {
        if (performanceFeeBps_ > MAX_PERFORMANCE_BPS)
            revert PerformanceFeeBpsTooHigh();
        performanceFeeBps = performanceFeeBps_;
        authorizedHook = authorizedHook_;
    }

    modifier onlyAuthorizedHook() {
        if (msg.sender != authorizedHook) revert UnauthorizedCaller(msg.sender);
        _;
    }

    function _performanceFee(
        address wallet,
        FeeContext calldata ctx
    ) internal view returns (uint256) {
        uint256 basis = depositBasis[wallet][ctx.token];
        if (ctx.amount <= basis) return 0;
        return ((ctx.amount - basis) * performanceFeeBps) / 10_000;
    }

    function _trackDeposit(
        address wallet,
        address token,
        uint256 amount
    ) internal {
        depositBasis[wallet][token] += amount;
    }

    function _trackWithdraw(
        address wallet,
        address token,
        uint256 amount
    ) internal {
        uint256 current = depositBasis[wallet][token];
        depositBasis[wallet][token] = amount >= current ? 0 : current - amount;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "account-abstraction/=lib/account-abstraction/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@solady/=lib/solady/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.