Curve2TokenOracle

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "src/oracles/Curve2TokenOracle.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.29;

import { AbstractLPOracle, ERC20 } from "./AbstractLPOracle.sol";
import { ICurvePool } from "../interfaces/Curve/ICurve.sol";
import { TokenUtils } from "../utils/TokenUtils.sol";
import { ETH_ADDRESS, ALT_ETH_ADDRESS, DEFAULT_PRECISION } from "../utils/Constants.sol";
import { TypeConvert } from "../utils/TypeConvert.sol";
import { AggregatorV2V3Interface } from "../interfaces/AggregatorV2V3Interface.sol";

contract Curve2TokenOracle is AbstractLPOracle {
    using TypeConvert for uint256;

    uint8 internal immutable SECONDARY_INDEX;
    address internal immutable TOKEN_1;
    address internal immutable TOKEN_2;
    uint8 internal immutable DECIMALS_1;
    uint8 internal immutable DECIMALS_2;
    AggregatorV2V3Interface internal immutable baseToUSDOracle;
    bool internal immutable invertBase;
    /// @dev The amount of secondary token to swap for the primary token, this is customizable
    /// to account for different pool sizes.
    uint256 internal immutable dyAmount;
    int256 internal immutable baseToUSDDecimals;

    constructor(
        uint256 _lowerLimitMultiplier,
        uint256 _upperLimitMultiplier,
        address _lpToken,
        uint8 _primaryIndex,
        string memory description_,
        address sequencerUptimeOracle_,
        AggregatorV2V3Interface baseToUSDOracle_,
        bool _invertBase,
        uint256 _dyAmount
    )
        // Curve LP tokens are in 18 decimals so we use DEFAULT_PRECISION
        AbstractLPOracle(
            DEFAULT_PRECISION,
            _lowerLimitMultiplier,
            _upperLimitMultiplier,
            _lpToken,
            _primaryIndex,
            description_,
            sequencerUptimeOracle_
        )
    {
        TOKEN_1 = _rewriteAltETH(ICurvePool(_lpToken).coins(0));
        TOKEN_2 = _rewriteAltETH(ICurvePool(_lpToken).coins(1));
        DECIMALS_1 = TokenUtils.getDecimals(TOKEN_1);
        DECIMALS_2 = TokenUtils.getDecimals(TOKEN_2);
        SECONDARY_INDEX = 1 - PRIMARY_INDEX;
        baseToUSDOracle = baseToUSDOracle_;
        invertBase = _invertBase;
        dyAmount = _dyAmount;

        uint8 _baseDecimals = baseToUSDOracle_.decimals();
        baseToUSDDecimals = int256(10 ** _baseDecimals);
    }

    function _rewriteAltETH(address token) private pure returns (address) {
        return token == address(ALT_ETH_ADDRESS) ? ETH_ADDRESS : address(token);
    }

    function _lpTokenValue() internal view returns (int256) {
        uint256[] memory balances = new uint256[](2);
        balances[0] = ICurvePool(LP_TOKEN).balances(0);
        balances[1] = ICurvePool(LP_TOKEN).balances(1);

        uint8[] memory decimals = new uint8[](2);
        decimals[0] = DECIMALS_1;
        decimals[1] = DECIMALS_2;

        ERC20[] memory tokens = new ERC20[](2);
        tokens[0] = ERC20(TOKEN_1);
        tokens[1] = ERC20(TOKEN_2);

        // The primary index spot price is left as zero.
        uint256[] memory spotPrices = new uint256[](2);
        uint256 primaryPrecision = 10 ** decimals[PRIMARY_INDEX];
        uint256 secondaryPrecision = 10 ** decimals[SECONDARY_INDEX];

        if (TOKEN_1 == ETH_ADDRESS || TOKEN_2 == ETH_ADDRESS) {
            // Ensures that we are not inside a reentrancy context
            ICurvePool(LP_TOKEN).get_virtual_price();
        }

        // `get_dy` returns the price of one unit of the primary token
        // converted to the secondary token. The spot price is in secondary
        // precision and then we convert it to DEFAULT_PRECISION for comparison
        // with the oracle price.
        spotPrices[SECONDARY_INDEX] = ICurvePool(LP_TOKEN).get_dy(int8(PRIMARY_INDEX), int8(SECONDARY_INDEX), dyAmount)
            * primaryPrecision * DEFAULT_PRECISION / (dyAmount * secondaryPrecision);

        // This is returned in DEFAULT_PRECISION
        return _calculateLPTokenValue(tokens, decimals, balances, spotPrices).toInt();
    }

    function _calculateBaseToQuote()
        internal
        view
        override
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
    {
        int256 lpTokenValue = _lpTokenValue();

        int256 baseToUSD;
        (roundId, baseToUSD, startedAt, updatedAt, answeredInRound) = baseToUSDOracle.latestRoundData();
        require(baseToUSD > 0, "Chainlink Rate Error");
        // Overflow and div by zero not possible
        if (invertBase) baseToUSD = (baseToUSDDecimals * baseToUSDDecimals) / baseToUSD;

        answer = lpTokenValue * baseToUSD / baseToUSDDecimals;
    }
}
"
    },
    "src/oracles/AbstractLPOracle.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.29;

import { DEFAULT_PRECISION } from "../utils/Constants.sol";
import { InvalidPrice } from "../interfaces/Errors.sol";
import { TRADING_MODULE } from "../interfaces/ITradingModule.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { AbstractCustomOracle } from "./AbstractCustomOracle.sol";

/// @notice Returns the value of one LP token in terms of the primary index token. Will revert if the spot
/// price on the pool is not within some deviation tolerance of the implied oracle price. This is intended
/// to prevent any pool manipulation. The value of the LP token is calculated as the value of the token if
/// all the balance claims are withdrawn proportionally and then converted to the primary currency at the
/// oracle price.
abstract contract AbstractLPOracle is AbstractCustomOracle {
    /// @dev The precision of the pool, generally 1e18
    uint256 internal immutable POOL_PRECISION;
    /// @dev Defines the lower limit of a tolerable price deviation from the oracle price
    uint256 internal immutable LOWER_LIMIT_MULTIPLIER;
    /// @dev Defines the upper limit of a tolerable price deviation from the oracle price
    uint256 internal immutable UPPER_LIMIT_MULTIPLIER;
    /// @dev The address of the LP token
    address internal immutable LP_TOKEN;
    /// @dev The index of the primary index token in the LP token, the price will be returned
    /// in terms of this token
    uint8 internal immutable PRIMARY_INDEX;

    constructor(
        uint256 _poolPrecision,
        uint256 _lowerLimitMultiplier,
        uint256 _upperLimitMultiplier,
        address _lpToken,
        uint8 _primaryIndex,
        string memory description_,
        address sequencerUptimeOracle_
    )
        AbstractCustomOracle(description_, sequencerUptimeOracle_)
    {
        require(_lowerLimitMultiplier < DEFAULT_PRECISION);
        require(DEFAULT_PRECISION < _upperLimitMultiplier);

        POOL_PRECISION = _poolPrecision;
        // These are in "default precision" terms, so 0.99e18 is 99%
        LOWER_LIMIT_MULTIPLIER = _lowerLimitMultiplier;
        UPPER_LIMIT_MULTIPLIER = _upperLimitMultiplier;
        LP_TOKEN = _lpToken;
        PRIMARY_INDEX = _primaryIndex;
    }

    function _totalPoolSupply() internal view virtual returns (uint256) {
        return ERC20(LP_TOKEN).totalSupply();
    }

    /// @notice Returns the pair price of two tokens via the TRADING_MODULE which holds a registry
    /// of oracles. Will revert of the oracle pair is not listed.
    function _getOraclePairPrice(address base, address quote) internal view returns (uint256) {
        // The trading module always returns a positive rate in DEFAULT_PRECISION so we can safely
        // cast to uint256
        (int256 rate, /* */ ) = TRADING_MODULE.getOraclePrice(base, quote);
        return uint256(rate);
    }

    /// @notice Calculates the claim of one LP token on relevant pool balances
    /// and compares the oracle price to the spot price, reverting if the deviation is too high.
    /// @return oneLPValueInPrimary the value of one LP token in terms of the primary index token,
    /// scaled to default precision (1e18)
    function _calculateLPTokenValue(
        ERC20[] memory tokens,
        uint8[] memory decimals,
        uint256[] memory balances,
        uint256[] memory spotPrices
    )
        internal
        view
        returns (uint256)
    {
        address primaryToken = address(tokens[PRIMARY_INDEX]);
        uint256 primaryDecimals = 10 ** decimals[PRIMARY_INDEX];
        uint256 totalSupply = _totalPoolSupply();
        uint256 oneLPValueInPrimary;

        for (uint256 i; i < tokens.length; i++) {
            // Skip the pool token if it is in the token list (i.e. Balancer V2 ComposablePools)
            if (address(tokens[i]) == address(LP_TOKEN)) continue;
            // This is the claim on the pool balance of 1 LP token in terms of the token's native
            // precision
            uint256 tokenClaim = balances[i] * POOL_PRECISION / totalSupply;
            if (i == PRIMARY_INDEX) {
                oneLPValueInPrimary += tokenClaim;
            } else {
                uint256 price = _getOraclePairPrice(primaryToken, address(tokens[i]));

                // Check that the spot price and the oracle price are near each other. If this is
                // not true then we assume that the LP pool is being manipulated.
                uint256 lowerLimit = price * LOWER_LIMIT_MULTIPLIER / DEFAULT_PRECISION;
                uint256 upperLimit = price * UPPER_LIMIT_MULTIPLIER / DEFAULT_PRECISION;
                if (spotPrices[i] < lowerLimit || upperLimit < spotPrices[i]) {
                    revert InvalidPrice(price, spotPrices[i]);
                }

                // Convert the token claim to primary using the oracle pair price.
                uint256 secondaryDecimals = 10 ** decimals[i];
                // Scale the token claim to primary token precision, DEFAULT_PRECISION is used
                // to match the precision of the oracle pair price.
                oneLPValueInPrimary += (tokenClaim * DEFAULT_PRECISION * primaryDecimals) / (price * secondaryDecimals);
            }
        }

        // Scale this up to default precision
        return oneLPValueInPrimary * DEFAULT_PRECISION / primaryDecimals;
    }
}
"
    },
    "src/interfaces/Curve/ICurve.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28;

enum CurveInterface {
    V1,
    V2,
    StableSwapNG
}

interface ICurveGauge {
    struct Reward {
        address token;
        address distributor;
        uint256 period_finish;
        uint256 rate;
        uint256 last_update;
        uint256 integral;
    }

    function claim_rewards() external;
    function deposit(uint256 _value) external;
    function withdraw(uint256 _value) external;
    function reward_count() external view returns (uint256);
    function reward_tokens(uint256 idx) external view returns (address);
    function reward_data(address token) external view returns (Reward memory);
}

interface ICurveMinter {
    function mint(address gauge) external;
}

ICurveMinter constant MINTER = ICurveMinter(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0);

interface ICurvePool {
    function coins(uint256 idx) external view returns (address);

    // @notice Perform an exchange between two coins
    // @dev Index values can be found via the `coins` public getter method
    // @dev see: https://etherscan.io/address/0xDC24316b9AE028F1497c275EB9192a3Ea0f67022#readContract
    // @param i Index value for the stEth to send -- 1
    // @param j Index value of the Eth to receive -- 0
    // @param dx Amount of `i` (stEth) being exchanged
    // @param minDy Minimum amount of `j` (Eth) to receive
    // @return Actual amount of `j` (Eth) received
    function exchange(int128 i, int128 j, uint256 dx, uint256 minDy) external payable returns (uint256);

    function balances(uint256 i) external view returns (uint256);

    function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256);

    /// @notice Not used in the oracle but has a re-entrancy lock on it
    function get_virtual_price() external view returns (uint256);
}

interface ICurvePoolV1 is ICurvePool {
    function lp_token() external view returns (address);
}

interface ICurvePoolV2 is ICurvePool {
    function token() external view returns (address);
}

interface ICurve2TokenPoolV1 is ICurvePoolV1 {
    function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external payable returns (uint256);
    function remove_liquidity(uint256 amount, uint256[2] calldata _min_amounts) external returns (uint256[2] memory);
    function remove_liquidity_one_coin(
        uint256 _token_amount,
        int128 i,
        uint256 _min_amount
    )
        external
        returns (uint256);
}

interface ICurve2TokenPoolV2 is ICurvePoolV2 {
    function add_liquidity(
        uint256[2] calldata amounts,
        uint256 min_mint_amount,
        bool use_eth
    )
        external
        payable
        returns (uint256);
    function remove_liquidity_one_coin(
        uint256 token_amount,
        uint256 i,
        uint256 min_amount,
        bool use_eth,
        address receiver
    )
        external
        returns (uint256);
    // Curve V2 does not return the amounts removed
    function remove_liquidity(
        uint256 amount,
        uint256[2] calldata _min_amounts,
        bool use_eth,
        address receiver
    )
        external;
    function claim_admin_fees() external;
}

interface ICurveStableSwapNG is ICurvePoolV1 {
    function add_liquidity(uint256[] calldata amounts, uint256 min_mint_amount) external payable returns (uint256);
    function remove_liquidity_one_coin(
        uint256 _token_amount,
        int128 i,
        uint256 _min_amount
    )
        external
        returns (uint256);
    function remove_liquidity(uint256 amount, uint256[] calldata _min_amounts) external returns (uint256[] memory);
    function totalSupply() external view returns (uint256);
}
"
    },
    "src/utils/TokenUtils.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.29;

import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { ETH_ADDRESS, ALT_ETH_ADDRESS } from "./Constants.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

library TokenUtils {
    using SafeERC20 for ERC20;

    function getDecimals(address token) internal view returns (uint8 decimals) {
        decimals = (token == ETH_ADDRESS || token == ALT_ETH_ADDRESS) ? 18 : ERC20(token).decimals();
        require(decimals <= 18);
    }

    function tokenBalance(address token) internal view returns (uint256) {
        return token == ETH_ADDRESS ? address(this).balance : ERC20(token).balanceOf(address(this));
    }

    function checkApprove(ERC20 token, address spender, uint256 amount) internal {
        if (address(token) == address(0)) return;

        token.forceApprove(spender, amount);
    }

    function checkRevoke(ERC20 token, address spender) internal {
        if (address(token) == address(0)) return;
        token.forceApprove(spender, 0);
    }

    function checkReturnCode() internal pure returns (bool success) {
        uint256[1] memory result;
        assembly {
            switch returndatasize()
            case 0 {
                // This is a non-standard ERC-20
                success := 1 // set success to true
            }
            case 32 {
                // This is a compliant ERC-20
                returndatacopy(result, 0, 32)
                success := mload(result) // Set `success = returndata` of external call
            }
            default {
                // This is an excessively non-compliant ERC-20, revert.
                revert(0, 0)
            }
        }
    }
}
"
    },
    "src/utils/Constants.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.29;

import { WETH9 } from "../interfaces/IWETH.sol";
import { AddressRegistry } from "../proxy/AddressRegistry.sol";

address constant ETH_ADDRESS = address(0);
address constant ALT_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 constant DEFAULT_PRECISION = 1e18;
uint256 constant DEFAULT_DECIMALS = 18;
uint256 constant SHARE_PRECISION = 1e24;
uint256 constant VIRTUAL_SHARES = 1e6;

uint256 constant COOLDOWN_PERIOD = 5 minutes;
uint256 constant YEAR = 365 days;

// Will move these to a deployment file when we go to multiple chains
uint256 constant CHAIN_ID_MAINNET = 1;
WETH9 constant WETH = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
AddressRegistry constant ADDRESS_REGISTRY = AddressRegistry(0xe335d314BD4eF7DD44F103dC124FEFb7Ce63eC95);
"
    },
    "src/utils/TypeConvert.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.29;

library TypeConvert {
    function toUint(int256 x) internal pure returns (uint256) {
        require(x >= 0);
        return uint256(x);
    }

    function toInt(uint256 x) internal pure returns (int256) {
        require(x <= uint256(type(int256).max)); // dev: toInt overflow
        return int256(x);
    }

    function toUint128(uint256 x) internal pure returns (uint128) {
        require(x <= uint128(type(uint128).max)); // dev: toUint128 overflow
        return uint128(x);
    }

    function toUint120(uint256 x) internal pure returns (uint120) {
        require(x <= uint120(type(uint120).max)); // dev: toUint120 overflow
        return uint120(x);
    }
}
"
    },
    "src/interfaces/AggregatorV2V3Interface.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28;

interface AggregatorV2V3Interface {
    function latestAnswer() external view returns (int256);
    function latestTimestamp() external view returns (uint256);
    function latestRound() external view returns (uint256);
    function getAnswer(uint256 roundId) external view returns (int256);
    function getTimestamp(uint256 roundId) external view returns (uint256);

    function decimals() external view returns (uint8);
    function description() external view returns (string memory);
    function version() external view returns (uint256);

    // getRoundData and latestRoundData should both raise "No data present"
    // if they do not have data to report, instead of returning unset values
    // which could be misinterpreted as actual reported values.
    function getRoundData(uint80 _roundId)
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
"
    },
    "src/interfaces/Errors.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.28;

error NotAuthorized(address operator, address user);
error Unauthorized(address caller);
error UnauthorizedLendingMarketTransfer(address from, address to, uint256 value);
error InsufficientYieldTokenBalance();
error InsufficientAssetsForRepayment(uint256 assetsToRepay, uint256 assetsWithdrawn);
error CannotLiquidate(uint256 maxLiquidateShares, uint256 seizedAssets);
error CannotLiquidateZeroShares();
error Paused();
error CannotExitPositionWithinCooldownPeriod();
error CannotTokenizeWithdrawRequest();
error CurrentAccountAlreadySet();
error InvalidVault(address vault);

error WithdrawRequestNotFinalized(uint256 requestId);
error CannotInitiateWithdraw(address account);
error CannotForceWithdraw(address account);
error InsufficientSharesHeld();
error SlippageTooHigh(uint256 actualTokensOut, uint256 minTokensOut);

error CannotEnterPosition();
error NoExistingPosition();
error LiquidatorHasPosition();
error InvalidUpgrade();
error InvalidInitialization();
error InvalidLendingRouter();

error ExistingWithdrawRequest(address vault, address account, uint256 requestId);
error NoWithdrawRequest(address vault, address account);
error InvalidWithdrawRequestTokenization();

error InvalidPrice(uint256 oraclePrice, uint256 spotPrice);
error PoolShareTooHigh(uint256 poolClaim, uint256 maxSupplyThreshold);
error AssetRemaining(uint256 assetRemaining);
"
    },
    "src/interfaces/ITradingModule.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity >=0.8.28;

import { AggregatorV2V3Interface } from "./AggregatorV2V3Interface.sol";

enum DexId {
    _UNUSED, // flag = 1,  enum = 0
    UNISWAP_V2, // flag = 2,  enum = 1
    UNISWAP_V3, // flag = 4,  enum = 2
    ZERO_EX, // flag = 8,  enum = 3
    BALANCER_V2, // flag = 16, enum = 4
    // NOTE: this id is unused in the TradingModule
    CURVE, // flag = 32, enum = 5
    NOTIONAL_VAULT, // flag = 64, enum = 6
    CURVE_V2, // flag = 128, enum = 7
    CAMELOT_V3 // flag = 256, enum = 8

}

enum TradeType {
    EXACT_IN_SINGLE, // flag = 1
    EXACT_OUT_SINGLE, // flag = 2
    EXACT_IN_BATCH, // flag = 4
    EXACT_OUT_BATCH, // flag = 8
    STAKE_TOKEN // flag = 16

}

struct UniV3SingleData {
    uint24 fee;
}

// Path is packed encoding `token, fee, token, fee, outToken`
struct UniV3BatchData {
    bytes path;
}

struct CurveV2SingleData {
    // Address of the pool to use for the swap
    address pool;
    int128 fromIndex;
    int128 toIndex;
}

struct CurveV2BatchData {
    // Array of [initial token, pool, token, pool, token, ...]
    // The array is iterated until a pool address of 0x00, then the last
    // given token is transferred to `_receiver`
    address[9] route;
    // Multidimensional array of [i, j, swap type] where i and j are the correct
    // values for the n'th pool in `_route`. The swap type should be
    // 1 for a stableswap `exchange`,
    // 2 for stableswap `exchange_underlying`,
    // 3 for a cryptoswap `exchange`,
    // 4 for a cryptoswap `exchange_underlying`,
    // 5 for factory metapools with lending base pool `exchange_underlying`,
    // 6 for factory crypto-meta pools underlying exchange (`exchange` method in zap),
    // 7-11 for wrapped coin (underlying for lending or fake pool) -> LP token "exchange" (actually `add_liquidity`),
    // 12-14 for LP token -> wrapped coin (underlying for lending pool) "exchange" (actually
    // `remove_liquidity_one_coin`)
    // 15 for WETH -> ETH "exchange" (actually deposit/withdraw)
    uint256[3][4] swapParams;
}

struct Trade {
    TradeType tradeType;
    address sellToken;
    address buyToken;
    uint256 amount;
    /// minBuyAmount or maxSellAmount
    uint256 limit;
    uint256 deadline;
    bytes exchangeData;
}

error InvalidTrade();
error DynamicTradeFailed();
error TradeFailed();

interface nProxy {
    function getImplementation() external view returns (address);
}

interface ITradingModule {
    struct TokenPermissions {
        bool allowSell;
        /// @notice allowed DEXes
        uint32 dexFlags;
        /// @notice allowed trade types
        uint32 tradeTypeFlags;
    }

    event TradeExecuted(address indexed sellToken, address indexed buyToken, uint256 sellAmount, uint256 buyAmount);

    event PriceOracleUpdated(address token, address oracle);
    event MaxOracleFreshnessUpdated(uint32 currentValue, uint32 newValue);
    event TokenPermissionsUpdated(address sender, address token, TokenPermissions permissions);

    function tokenWhitelist(
        address spender,
        address token
    )
        external
        view
        returns (bool allowSell, uint32 dexFlags, uint32 tradeTypeFlags);

    function priceOracles(address token) external view returns (AggregatorV2V3Interface oracle, uint8 rateDecimals);

    function getExecutionData(
        uint16 dexId,
        address from,
        Trade calldata trade
    )
        external
        view
        returns (address spender, address target, uint256 value, bytes memory params);

    function setMaxOracleFreshness(uint32 newMaxOracleFreshnessInSeconds) external;

    function setPriceOracle(address token, AggregatorV2V3Interface oracle) external;

    function setTokenPermissions(address sender, address token, TokenPermissions calldata permissions) external;

    function getOraclePrice(address inToken, address outToken) external view returns (int256 answer, int256 decimals);

    function executeTrade(
        uint16 dexId,
        Trade calldata trade
    )
        external
        payable
        returns (uint256 amountSold, uint256 amountBought);

    function executeTradeWithDynamicSlippage(
        uint16 dexId,
        Trade memory trade,
        uint32 dynamicSlippageLimit
    )
        external
        payable
        returns (uint256 amountSold, uint256 amountBought);

    function getLimitAmount(
        address from,
        TradeType tradeType,
        address sellToken,
        address buyToken,
        uint256 amount,
        uint32 slippageLimit
    )
        external
        view
        returns (uint256 limitAmount);

    function canExecuteTrade(address from, uint16 dexId, Trade calldata trade) external view returns (bool);
}

ITradingModule constant TRADING_MODULE = ITradingModule(0x594734c7e06C3D483466ADBCe401C6Bd269746C8);
"
    },
    "node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}
"
    },
    "src/oracles/AbstractCustomOracle.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.29;

import { AggregatorV2V3Interface } from "../interfaces/AggregatorV2V3Interface.sol";

/// @notice Defines a custom oracle that implements the AggregatorV2V3Interface. Used to
/// get the price of more exotic assets like LP tokens, PT tokens, etc. Returns the price
/// in USD terms. Used inside the TradingModule to calculate the price of arbitrary token
/// pairs.
abstract contract AbstractCustomOracle is AggregatorV2V3Interface {
    uint256 public constant override version = 1;
    string public override description;

    uint8 public constant override decimals = 18;

    AggregatorV2V3Interface public immutable sequencerUptimeOracle;
    uint256 public constant SEQUENCER_UPTIME_GRACE_PERIOD = 1 hours;

    constructor(string memory description_, address sequencerUptimeOracle_) {
        description = description_;
        sequencerUptimeOracle = AggregatorV2V3Interface(sequencerUptimeOracle_);
    }

    function _calculateBaseToQuote()
        internal
        view
        virtual
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

    function _checkSequencer() private view {
        // See: https://docs.chain.link/data-feeds/l2-sequencer-feeds/
        if (address(sequencerUptimeOracle) != address(0)) {
            (
                /*uint80 roundID*/
                ,
                int256 answer,
                uint256 startedAt,
                /*uint256 updatedAt*/
                ,
                /*uint80 answeredInRound*/
            ) = sequencerUptimeOracle.latestRoundData();
            require(answer == 0, "Sequencer Down");
            require(SEQUENCER_UPTIME_GRACE_PERIOD < block.timestamp - startedAt, "Sequencer Grace Period");
        }
    }

    function latestRoundData()
        external
        view
        override
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
    {
        _checkSequencer();
        return _calculateBaseToQuote();
    }

    function latestAnswer() external view override returns (int256 answer) {
        ( /* */ , answer, /* */, /* */, /* */ ) = _calculateBaseToQuote();
    }

    function latestTimestamp() external view override returns (uint256 updatedAt) {
        ( /* */ , /* */, /* */, updatedAt, /* */ ) = _calculateBaseToQuote();
    }

    function latestRound() external view override returns (uint256 roundId) {
        (roundId, /* */, /* */, /* */, /* */ ) = _calculateBaseToQuote();
    }

    /// @dev Unused in the trading module
    function getRoundData(uint80 /* _roundId */ )
        external
        pure
        override
        returns (
            uint80, /* roundId */
            int256, /* answer */
            uint256, /* startedAt */
            uint256, /* updatedAt */
            uint80 /* answeredInRound */
        )
    {
        revert();
    }

    /// @dev Unused in the trading module
    function getAnswer(uint256 /* roundId */ ) external pure override returns (int256) {
        revert();
    }

    /// @dev Unused in the trading module
    function getTimestamp(uint256 /* roundId */ ) external pure override returns (uint256) {
        revert();
    }
}
"
    },
    "node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.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);
    }
}
"
    },
    "src/interfaces/IWETH.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.29;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface WETH9 is IERC20 {
    function deposit() external payable;
    function withdraw(uint256 wad) external;
}
"
    },
    "src/proxy/AddressRegistry.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.29;

import { Unauthorized, CannotEnterPosition, InvalidVault } from "../interfaces/Errors.sol";
import { IWithdrawRequestManager } from "../interfaces/IWithdrawRequestManager.sol";
import { VaultPosition } from "../interfaces/ILendingRouter.sol";
import { Initializable } from "./Initializable.sol";

/// @notice Registry for the addresses for different components of the protocol.
contract AddressRegistry is Initializable {
    event PendingUpgradeAdminSet(address indexed newPendingUpgradeAdmin);
    event UpgradeAdminTransferred(address indexed newUpgradeAdmin);
    event PendingPauseAdminSet(address indexed newPendingPauseAdmin);
    event PauseAdminTransferred(address indexed newPauseAdmin);
    event FeeReceiverTransferred(address indexed newFeeReceiver);
    event WithdrawRequestManagerSet(address indexed yieldToken, address indexed withdrawRequestManager);
    event LendingRouterSet(address indexed lendingRouter);
    event AccountPositionCreated(address indexed account, address indexed vault, address indexed lendingRouter);
    event AccountPositionCleared(address indexed account, address indexed vault, address indexed lendingRouter);
    event WhitelistedVault(address indexed vault, bool isWhitelisted);

    /// @notice Address of the admin that is allowed to:
    /// - Upgrade TimelockUpgradeableProxy contracts given a 7 day timelock
    /// - Transfer the upgrade admin role
    /// - Set the pause admin
    /// - Set the fee receiver
    /// - Add reward tokens to the RewardManager
    /// - Set the WithdrawRequestManager for a yield token
    /// - Whitelist vaults for the WithdrawRequestManager
    /// - Whitelist new lending routers
    address public upgradeAdmin;
    address public pendingUpgradeAdmin;

    /// @notice Address of the admin that is allowed to selectively pause or unpause
    /// TimelockUpgradeableProxy contracts
    address public pauseAdmin;
    address public pendingPauseAdmin;

    /// @notice Address of the account that receives the protocol fees
    address public feeReceiver;

    /// @notice Mapping of yield token to WithdrawRequestManager
    mapping(address token => address withdrawRequestManager) public withdrawRequestManagers;

    /// @notice Mapping of lending router to boolean indicating if it is whitelisted
    mapping(address lendingRouter => bool isLendingRouter) public lendingRouters;

    /// @notice Mapping to whitelisted vaults
    mapping(address vault => bool isWhitelisted) public whitelistedVaults;

    /// @notice Mapping of accounts to their existing position on a given vault
    mapping(address account => mapping(address vault => VaultPosition)) internal accountPositions;

    function _initialize(bytes calldata data) internal override {
        (address _upgradeAdmin, address _pauseAdmin, address _feeReceiver) =
            abi.decode(data, (address, address, address));
        upgradeAdmin = _upgradeAdmin;
        pauseAdmin = _pauseAdmin;
        feeReceiver = _feeReceiver;
    }

    modifier onlyUpgradeAdmin() {
        if (msg.sender != upgradeAdmin) revert Unauthorized(msg.sender);
        _;
    }

    function transferUpgradeAdmin(address _newUpgradeAdmin) external onlyUpgradeAdmin {
        pendingUpgradeAdmin = _newUpgradeAdmin;
        emit PendingUpgradeAdminSet(_newUpgradeAdmin);
    }

    function acceptUpgradeOwnership() external {
        if (msg.sender != pendingUpgradeAdmin) revert Unauthorized(msg.sender);
        upgradeAdmin = pendingUpgradeAdmin;
        delete pendingUpgradeAdmin;
        emit UpgradeAdminTransferred(upgradeAdmin);
    }

    function transferPauseAdmin(address _newPauseAdmin) external onlyUpgradeAdmin {
        pendingPauseAdmin = _newPauseAdmin;
        emit PendingPauseAdminSet(_newPauseAdmin);
    }

    function acceptPauseAdmin() external {
        if (msg.sender != pendingPauseAdmin) revert Unauthorized(msg.sender);
        pauseAdmin = pendingPauseAdmin;
        delete pendingPauseAdmin;
        emit PauseAdminTransferred(pauseAdmin);
    }

    function transferFeeReceiver(address _newFeeReceiver) external onlyUpgradeAdmin {
        feeReceiver = _newFeeReceiver;
        emit FeeReceiverTransferred(_newFeeReceiver);
    }

    function setWithdrawRequestManager(address withdrawRequestManager) external onlyUpgradeAdmin {
        address yieldToken = IWithdrawRequestManager(withdrawRequestManager).YIELD_TOKEN();
        // Prevent accidental override of a withdraw request manager, this is dangerous
        // as it could lead to withdraw requests being stranded on the deprecated withdraw
        // request manager. Managers can be upgraded using a TimelockUpgradeableProxy.
        require(withdrawRequestManagers[yieldToken] == address(0), "Withdraw request manager already set");

        withdrawRequestManagers[yieldToken] = withdrawRequestManager;
        emit WithdrawRequestManagerSet(yieldToken, withdrawRequestManager);
    }

    function setWhitelistedVault(address vault, bool isWhitelisted) external onlyUpgradeAdmin {
        whitelistedVaults[vault] = isWhitelisted;
        emit WhitelistedVault(vault, isWhitelisted);
    }

    function getWithdrawRequestManager(address yieldToken) external view returns (IWithdrawRequestManager) {
        return IWithdrawRequestManager(withdrawRequestManagers[yieldToken]);
    }

    function setLendingRouter(address lendingRouter) external onlyUpgradeAdmin {
        lendingRouters[lendingRouter] = true;
        emit LendingRouterSet(lendingRouter);
    }

    function isLendingRouter(address lendingRouter) external view returns (bool) {
        return lendingRouters[lendingRouter];
    }

    function getVaultPosition(address account, address vault) external view returns (VaultPosition memory) {
        return accountPositions[account][vault];
    }

    function setPosition(address account, address vault) external {
        // Must only be called by a lending router
        if (!lendingRouters[msg.sender]) revert Unauthorized(msg.sender);
        VaultPosition storage position = accountPositions[account][vault];

        if (position.lendingRouter == address(0)) position.lendingRouter = msg.sender;
        else if (position.lendingRouter != msg.sender) revert CannotEnterPosition();

        // Lending routers may be used to enter positions on any vault, including a malicious vault
        // so this ensures that only whitelisted vaults can be used to enter positions
        if (!whitelistedVaults[vault]) revert InvalidVault(vault);

        position.lastEntryTime = uint32(block.timestamp);
        emit AccountPositionCreated(account, vault, msg.sender);
    }

    function clearPosition(address account, address vault) external {
        // Must only be called by a lending router
        if (!lendingRouters[msg.sender]) revert Unauthorized(msg.sender);

        delete accountPositions[account][vault];
        emit AccountPositionCleared(account, vault, msg.sender);
    }

    function emitAccountNativePosition(address account, bool isCleared) external {
        // Can only be called by a whitelisted vault
        require(whitelistedVaults[msg.sender]);
        if (isCleared) emit AccountPositionCleared(account, msg.sender, address(0));
        else emit AccountPositionCreated(account, msg.sender, address(0));
    }
}
"
    },
    "node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// 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);
}
"
    },
    "node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}
"
    },
    "node_modules/@openzeppelin/contracts/utils/Context.sol": {
      "content": "// 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;
    }
}
"
    },
    "node_modules/@openzeppelin/contracts/interfaces/draft-IERC6093.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev I

Tags:
ERC20, ERC165, Multisig, Mintable, Swap, Staking, Yield, Upgradeable, Multi-Signature, Factory, Oracle|addr:0x9dab677fbd6549b3b908fe5559a6bdef64073d97|verified:true|block:23471130|tx:0x33f1b1ec4cb383dcb8dcba226146892d5f57777a3d0ec7077d7f33d6b6c491a3|first_check:1759219735

Submitted on: 2025-09-30 10:08:55

Comments

Log in to comment.

No comments yet.