Skip to content
Verified contractExactMIT

DFSSell

Address0xa144a66eea5e92540f4fe52836b2c3d60de69e6a
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,442,091
Creation transaction
0x6b1b6298eb…0ff93e6ff7

47 files

contracts/actions/exchange/DFSSell.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

import { DFSExchangeWithTxSaver } from "../../exchangeV3/DFSExchangeWithTxSaver.sol";
import { TokenGroupRegistry } from "../../exchangeV3/registries/TokenGroupRegistry.sol";
import { TokenUtils } from "../../utils/token/TokenUtils.sol";
import { ActionBase } from "../ActionBase.sol";

/// @title A exchange sell action through the dfs exchange
/// @dev The only action which has wrap/unwrap WETH builtin so we don't have to bundle into a recipe
contract DFSSell is ActionBase, DFSExchangeWithTxSaver {
    using TokenUtils for address;

    uint256 internal constant RECIPE_FEE = 400;

    struct Params {
        ExchangeData exchangeData;
        address from;
        address to;
    }

    /// @inheritdoc ActionBase
    function executeAction(
        bytes memory _callData,
        bytes32[] memory _subData,
        uint8[] memory _paramMapping,
        bytes32[] memory _returnValues
    ) public payable virtual override returns (bytes32) {
        Params memory params = parseInputs(_callData);

        params.exchangeData.srcAddr =
            _parseParamAddr(params.exchangeData.srcAddr, _paramMapping[0], _subData, _returnValues);
        params.exchangeData.destAddr = _parseParamAddr(
            params.exchangeData.destAddr, _paramMapping[1], _subData, _returnValues
        );

        params.exchangeData.srcAmount = _parseParamUint(
            params.exchangeData.srcAmount, _paramMapping[2], _subData, _returnValues
        );
        params.from = _parseParamAddr(params.from, _paramMapping[3], _subData, _returnValues);
        params.to = _parseParamAddr(params.to, _paramMapping[4], _subData, _returnValues);

        bool isDirect = _returnValues.length == 1 ? true : false;

        (uint256 exchangedAmount, bytes memory logData) =
            _dfsSell(params.exchangeData, params.from, params.to, isDirect);

        emit ActionEvent("DFSSell", logData);
        return bytes32(exchangedAmount);
    }

    /// @inheritdoc ActionBase
    function executeActionDirect(bytes memory _callData) public payable virtual override {
        Params memory params = parseInputs(_callData);
        (, bytes memory logData) = _dfsSell(params.exchangeData, params.from, params.to, true);
        logger.logActionDirectEvent("DFSSell", logData);
    }

    /// @inheritdoc ActionBase
    function actionType() public pure virtual override returns (uint8) {
        return uint8(ActionType.STANDARD_ACTION);
    }

    //////////////////////////// ACTION LOGIC ////////////////////////////

    /// @notice Sells a specified srcAmount for the dest token
    /// @param _exchangeData DFS Exchange data struct
    /// @param _from Address from which we'll pull the srcTokens
    /// @param _to Address where we'll send the _to token
    /// @param _isDirect True if it's just one sell action, false if part of recipe
    function _dfsSell(ExchangeData memory _exchangeData, address _from, address _to, bool _isDirect)
        internal
        returns (uint256, bytes memory)
    {
        // if we set srcAmount to max, take the whole user's wallet balance
        if (_exchangeData.srcAmount == type(uint256).max) {
            _exchangeData.srcAmount = _exchangeData.srcAddr.getBalance(address(this));
        }

        // if source and destination address are same we want to skip exchanging and take no fees
        if (_exchangeData.srcAddr == _exchangeData.destAddr) {
            bytes memory sameAssetLogData = abi.encode(
                address(0),
                _exchangeData.srcAddr,
                _exchangeData.destAddr,
                _exchangeData.srcAmount,
                _exchangeData.srcAmount,
                0
            );
            return (_exchangeData.srcAmount, sameAssetLogData);
        }

        // Wrap eth if sent directly
        if (_exchangeData.srcAddr == TokenUtils.ETH_ADDR) {
            TokenUtils.depositWeth(_exchangeData.srcAmount);
            _exchangeData.srcAddr = TokenUtils.WETH_ADDR;
        } else {
            _exchangeData.srcAddr.pullTokensIfNeeded(_from, _exchangeData.srcAmount);
        }

        // We always swap with weth, convert token addr when eth sent for unwrapping later
        bool isEthDest;
        if (_exchangeData.destAddr == TokenUtils.ETH_ADDR) {
            _exchangeData.destAddr = TokenUtils.WETH_ADDR;
            isEthDest = true;
        }

        /// @dev only check for custom fee if a non standard fee is sent
        if (!_isDirect) {
            if (_exchangeData.dfsFeeDivider != RECIPE_FEE) {
                _exchangeData.dfsFeeDivider = TokenGroupRegistry(TOKEN_GROUP_REGISTRY)
                    .getFeeForTokens(_exchangeData.srcAddr, _exchangeData.destAddr);
            }
        } else {
            _exchangeData.dfsFeeDivider = 0;
        }

        address wrapper;
        uint256 exchangedAmount;

        (wrapper, exchangedAmount,,) =
            _sellWithTxSaverChoice(_exchangeData, address(this), registry);

        if (isEthDest) {
            TokenUtils.withdrawWeth(exchangedAmount);

            (bool success,) = _to.call{ value: exchangedAmount }("");
            require(success, "Eth send failed");
        } else {
            _exchangeData.destAddr.withdrawTokens(_to, exchangedAmount);
        }

        bytes memory logData = abi.encode(
            wrapper,
            _exchangeData.srcAddr,
            _exchangeData.destAddr,
            _exchangeData.srcAmount,
            exchangedAmount,
            _exchangeData.dfsFeeDivider
        );
        return (exchangedAmount, logData);
    }

    function parseInputs(bytes memory _callData) public pure returns (Params memory params) {
        params = abi.decode(_callData, (Params));
    }
}

contracts/_vendor/DS/DSMath.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;

contract DSMath {
    function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = x + y;
    }

    function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = x - y;
    }

    function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = x * y;
    }

    function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
        return x / y;
    }

    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        return x <= y ? x : y;
    }

    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
        return x >= y ? x : y;
    }

    function imin(int256 x, int256 y) internal pure returns (int256 z) {
        return x <= y ? x : y;
    }

    function imax(int256 x, int256 y) internal pure returns (int256 z) {
        return x >= y ? x : y;
    }

    uint256 constant WAD = 10 ** 18;
    uint256 constant RAY = 10 ** 27;

    function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = add(mul(x, y), WAD / 2) / WAD;
    }

    function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = add(mul(x, y), RAY / 2) / RAY;
    }

    function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = add(mul(x, WAD), y / 2) / y;
    }

    function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = add(mul(x, RAY), y / 2) / y;
    }

    // This famous algorithm is called "exponentiation by squaring"
    // and calculates x^n with x as fixed-point and n as regular unsigned.
    //
    // It's O(log n), instead of O(n) for naive repeated multiplication.
    //
    // These facts are why it works:
    //
    //  If n is even, then x^n = (x^2)^(n/2).
    //  If n is odd,  then x^n = x * x^(n-1),
    //   and applying the equation for even x gives
    //    x^n = x * (x^2)^((n-1) / 2).
    //
    //  Also, EVM division is flooring and
    //    floor[(n-1) / 2] = floor[n / 2].
    //
    function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
        z = n % 2 != 0 ? x : RAY;

        for (n /= 2; n != 0; n /= 2) {
            x = rmul(x, x);

            if (n % 2 != 0) {
                z = rmul(z, x);
            }
        }
    }
}

contracts/_vendor/openzeppelin/Address.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

library Address {
    //insufficient balance
    error InsufficientBalance(uint256 available, uint256 required);
    //unable to send value, recipient may have reverted
    error SendingValueFail();
    //insufficient balance for call
    error InsufficientBalanceForCall(uint256 available, uint256 required);
    //call to non-contract
    error NonContractCall();

    function isContract(address account) internal view returns (bool) {
        // According to EIP-1052, 0x0 is the value returned for not-yet created accounts
        // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            codehash := extcodehash(account)
        }
        return (codehash != accountHash && codehash != 0x0);
    }

    function sendValue(address payable recipient, uint256 amount) internal {
        uint256 balance = address(this).balance;
        if (balance < amount) {
            revert InsufficientBalance(balance, amount);
        }

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success,) = recipient.call{ value: amount }("");
        if (!(success)) {
            revert SendingValueFail();
        }
    }

    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    function functionCall(address target, bytes memory data, string memory errorMessage)
        internal
        returns (bytes memory)
    {
        return _functionCallWithValue(target, data, 0, errorMessage);
    }

    function functionCallWithValue(address target, bytes memory data, uint256 value)
        internal
        returns (bytes memory)
    {
        return functionCallWithValue(
            target, data, value, "Address: low-level call with value failed"
        );
    }

    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        uint256 balance = address(this).balance;
        if (balance < value) {
            revert InsufficientBalanceForCall(balance, value);
        }
        return _functionCallWithValue(target, data, value, errorMessage);
    }

    function _functionCallWithValue(
        address target,
        bytes memory data,
        uint256 weiValue,
        string memory errorMessage
    ) private returns (bytes memory) {
        if (!(isContract(target))) {
            revert NonContractCall();
        }

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

contracts/_vendor/openzeppelin/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)
// changes made - renamed forceApprove to safeApprove
// changes made - removed safePermit, safeIncreaseAllowance, safeDecreaseAllowance functions

pragma solidity =0.8.24;

import { IERC20 } from "../../interfaces/token/IERC20.sol";
import { Address } from "./Address.sol";

library SafeERC20 {
    using Address for address;

    /**
     * @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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value)
        );
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
     * 0 before setting it to a non-zero value.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @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).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata =
            address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(
            returndata.length == 0 || abi.decode(returndata, (bool)),
            "SafeERC20: ERC20 operation did not succeed"
        );
    }

    /**
     * @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 silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool)))
            && address(token).code.length > 0;
    }
}

contracts/actions/ActionBase.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;

import { AdminAuth } from "../auth/AdminAuth.sol";
import { IDFSRegistry } from "../interfaces/core/IDFSRegistry.sol";
import { DefisaverLogger } from "../utils/DefisaverLogger.sol";
import { ActionsUtilHelper } from "./utils/helpers/ActionsUtilHelper.sol";
import { SmartWalletUtils } from "../utils/SmartWalletUtils.sol";

/// @title Implements Action interface and common helpers for passing inputs
abstract contract ActionBase is AdminAuth, ActionsUtilHelper, SmartWalletUtils {
    event ActionEvent(string indexed logName, bytes data);

    IDFSRegistry public constant registry = IDFSRegistry(REGISTRY_ADDR);

    DefisaverLogger public constant logger = DefisaverLogger(DFS_LOGGER_ADDR);

    //Wrong sub index value
    error SubIndexValueError();
    //Wrong return index value
    error ReturnIndexValueError();

    /// @dev Subscription params index range [128, 255]
    uint8 public constant SUB_MIN_INDEX_VALUE = 128;
    uint8 public constant SUB_MAX_INDEX_VALUE = 255;

    /// @dev Return params index range [1, 127]
    uint8 public constant RETURN_MIN_INDEX_VALUE = 1;
    uint8 public constant RETURN_MAX_INDEX_VALUE = 127;

    /// @dev If the input value should not be replaced
    uint8 public constant NO_PARAM_MAPPING = 0;

    /// @dev We need to parse Flash loan actions in a different way
    enum ActionType {
        FL_ACTION,
        STANDARD_ACTION,
        FEE_ACTION,
        CHECK_ACTION,
        CUSTOM_ACTION
    }

    /// @notice Parses inputs and runs the implemented action through a user wallet
    /// @dev Is called by the RecipeExecutor chaining actions together
    /// @param _callData Array of input values each value encoded as bytes
    /// @param _subData Array of subscribed vales, replaces input values if specified
    /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input
    /// @param _returnValues Returns values from actions before, which can be injected in inputs
    /// @return Returns a bytes32 value through user wallet, each actions implements what that value is
    function executeAction(
        bytes memory _callData,
        bytes32[] memory _subData,
        uint8[] memory _paramMapping,
        bytes32[] memory _returnValues
    ) public payable virtual returns (bytes32);

    /// @notice Parses inputs and runs the single implemented action through a user wallet
    /// @dev Used to save gas when executing a single action directly
    function executeActionDirect(bytes memory _callData) public payable virtual;

    /// @notice Returns the type of action we are implementing
    function actionType() public pure virtual returns (uint8);

    //////////////////////////// HELPER METHODS ////////////////////////////

    /// @notice Given an uint256 input, injects return/sub values if specified
    /// @param _param The original input value
    /// @param _mapType Indicated the type of the input in paramMapping
    /// @param _subData Array of subscription data we can replace the input value with
    /// @param _returnValues Array of subscription data we can replace the input value with
    function _parseParamUint(
        uint256 _param,
        uint8 _mapType,
        bytes32[] memory _subData,
        bytes32[] memory _returnValues
    ) internal pure returns (uint256) {
        if (isReplaceable(_mapType)) {
            if (isReturnInjection(_mapType)) {
                _param = uint256(_returnValues[getReturnIndex(_mapType)]);
            } else {
                _param = uint256(_subData[getSubIndex(_mapType)]);
            }
        }

        return _param;
    }

    /// @notice Given an addr input, injects return/sub values if specified
    /// @param _param The original input value
    /// @param _mapType Indicated the type of the input in paramMapping
    /// @param _subData Array of subscription data we can replace the input value with
    /// @param _returnValues Array of subscription data we can replace the input value with
    function _parseParamAddr(
        address _param,
        uint8 _mapType,
        bytes32[] memory _subData,
        bytes32[] memory _returnValues
    ) internal view returns (address) {
        if (isReplaceable(_mapType)) {
            if (isReturnInjection(_mapType)) {
                _param = address(bytes20((_returnValues[getReturnIndex(_mapType)])));
            } else {
                /// @dev The last two values are specially reserved for proxy addr and owner addr
                if (_mapType == 254) return address(this); // wallet address
                if (_mapType == 255) return _fetchOwnerOrWallet(address(this)); // owner if 1/1 wallet or the wallet itself

                _param = address(uint160(uint256(_subData[getSubIndex(_mapType)])));
            }
        }

        return _param;
    }

    /// @notice Given an bytes32 input, injects return/sub values if specified
    /// @param _param The original input value
    /// @param _mapType Indicated the type of the input in paramMapping
    /// @param _subData Array of subscription data we can replace the input value with
    /// @param _returnValues Array of subscription data we can replace the input value with
    function _parseParamABytes32(
        bytes32 _param,
        uint8 _mapType,
        bytes32[] memory _subData,
        bytes32[] memory _returnValues
    ) internal pure returns (bytes32) {
        if (isReplaceable(_mapType)) {
            if (isReturnInjection(_mapType)) {
                _param = (_returnValues[getReturnIndex(_mapType)]);
            } else {
                _param = _subData[getSubIndex(_mapType)];
            }
        }

        return _param;
    }

    /// @notice Checks if the paramMapping value indicated that we need to inject values
    /// @param _type Indicated the type of the input
    function isReplaceable(uint8 _type) internal pure returns (bool) {
        return _type != NO_PARAM_MAPPING;
    }

    /// @notice Checks if the paramMapping value is in the return value range
    /// @param _type Indicated the type of the input
    function isReturnInjection(uint8 _type) internal pure returns (bool) {
        return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE);
    }

    /// @notice Transforms the paramMapping value to the index in return array value
    /// @param _type Indicated the type of the input
    function getReturnIndex(uint8 _type) internal pure returns (uint8) {
        if (!(isReturnInjection(_type))) {
            revert SubIndexValueError();
        }

        return (_type - RETURN_MIN_INDEX_VALUE);
    }

    /// @notice Transforms the paramMapping value to the index in sub array value
    /// @param _type Indicated the type of the input
    function getSubIndex(uint8 _type) internal pure returns (uint8) {
        if (_type < SUB_MIN_INDEX_VALUE) {
            revert ReturnIndexValueError();
        }
        return (_type - SUB_MIN_INDEX_VALUE);
    }
}

contracts/actions/utils/helpers/ActionsUtilHelper.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

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

contract ActionsUtilHelper is MainnetActionsUtilAddresses { }

contracts/actions/utils/helpers/MainnetActionsUtilAddresses.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

contract MainnetActionsUtilAddresses {
    address internal constant REGISTRY_ADDR = 0x287778F121F134C66212FB16c9b53eC991D32f5b;
    address internal constant DFS_LOGGER_ADDR = 0xcE7a977Cac4a481bc84AC06b2Da0df614e621cf3;
    address internal constant SUB_STORAGE_ADDR = 0x1612fc28Ee0AB882eC99842Cde0Fc77ff0691e90;
    address internal constant PROXY_AUTH_ADDR = 0x149667b6FAe2c63D1B4317C716b0D0e4d3E2bD70;
    address internal constant LSV_PROXY_REGISTRY_ADDRESS =
        0xa8a3c86c4A2DcCf350E84D2b3c46BDeBc711C16e;
    address internal constant TRANSIENT_STORAGE = 0x2F7Ef2ea5E8c97B8687CA703A0e50Aa5a49B7eb2;
    address internal constant TRANSIENT_STORAGE_CANCUN = 0x0304E27cccE28bAB4d78C6cb7AfD4cd01c87c1e4;
}

contracts/auth/AdminAuth.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

import { IAdminVault } from "../interfaces/auth/IAdminVault.sol";
import { IERC20 } from "../interfaces/token/IERC20.sol";
import { SafeERC20 } from "../_vendor/openzeppelin/SafeERC20.sol";
import { AuthHelper } from "./helpers/AuthHelper.sol";

/// @title AdminAuth Handles owner/admin privileges over smart contracts
contract AdminAuth is AuthHelper {
    using SafeERC20 for IERC20;

    IAdminVault public constant adminVault = IAdminVault(ADMIN_VAULT_ADDR);

    error SenderNotOwner();
    error SenderNotAdmin();

    modifier onlyOwner() {
        if (adminVault.owner() != msg.sender) {
            revert SenderNotOwner();
        }
        _;
    }

    modifier onlyAdmin() {
        if (adminVault.admin() != msg.sender) {
            revert SenderNotAdmin();
        }
        _;
    }

    /// @notice withdraw stuck funds
    function withdrawStuckFunds(address _token, address _receiver, uint256 _amount)
        public
        onlyOwner
    {
        if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
            payable(_receiver).transfer(_amount);
        } else {
            IERC20(_token).safeTransfer(_receiver, _amount);
        }
    }
}

contracts/auth/helpers/AuthHelper.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

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

contract AuthHelper is MainnetAuthAddresses { }

contracts/auth/helpers/MainnetAuthAddresses.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

contract MainnetAuthAddresses {
    address internal constant ADMIN_VAULT_ADDR = 0xCCf3d848e08b94478Ed8f46fFead3008faF581fD;
    address internal constant DSGUARD_FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7;
    address internal constant ADMIN_ADDR = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; // USED IN ADMIN VAULT CONSTRUCTOR
    address internal constant PROXY_AUTH_ADDRESS = 0x149667b6FAe2c63D1B4317C716b0D0e4d3E2bD70;
    address internal constant MODULE_AUTH_ADDRESS = 0x7407974DDBF539e552F1d051e44573090912CC3D;
}

contracts/core/strategy/StrategyModel.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

/// @title StrategyModel - contract that implements the structs used in the core system
contract StrategyModel {
    /// @dev Group of strategies bundled together so user can sub to multiple strategies at once
    /// @param creator Address of the user who created the bundle
    /// @param strategyIds Array of strategy ids stored in StrategyStorage
    struct StrategyBundle {
        address creator;
        uint64[] strategyIds;
    }

    /// @dev Template/Class which defines a Strategy
    /// @param name Name of the strategy useful for logging what strategy is executing
    /// @param creator Address of the user which created the strategy
    /// @param triggerIds Array of identifiers for trigger - bytes4(keccak256(TriggerName))
    /// @param actionIds Array of identifiers for actions - bytes4(keccak256(ActionName))
    /// @param paramMapping Describes how inputs to functions are piped from return/subbed values
    /// @param continuous If the action is repeated (continuos) or one time
    struct Strategy {
        string name;
        address creator;
        bytes4[] triggerIds;
        bytes4[] actionIds;
        uint8[][] paramMapping;
        bool continuous;
    }

    /// @dev List of actions grouped as a recipe
    /// @param name Name of the recipe useful for logging what recipe is executing
    /// @param callData Array of calldata inputs to each action
    /// @param subData Used only as part of strategy, subData injected from StrategySub.subData
    /// @param actionIds Array of identifiers for actions - bytes4(keccak256(ActionName))
    /// @param paramMapping Describes how inputs to functions are piped from return/subbed values
    struct Recipe {
        string name;
        bytes[] callData;
        bytes32[] subData;
        bytes4[] actionIds;
        uint8[][] paramMapping;
    }

    /// @dev Actual data of the sub we store on-chain
    /// @dev In order to save on gas we store a keccak256(StrategySub) and verify later on
    /// @param walletAddr Address of the users smart wallet/proxy
    /// @param isEnabled Toggle if the subscription is active
    /// @param strategySubHash Hash of the StrategySub data the user inputted
    struct StoredSubData {
        bytes20 walletAddr; // address but put in bytes20 for gas savings
        bool isEnabled;
        bytes32 strategySubHash;
    }

    /// @dev Instance of a strategy, user supplied data
    /// @param strategyOrBundleId Id of the strategy or bundle, depending on the isBundle bool
    /// @param isBundle If true the id points to bundle, if false points directly to strategyId
    /// @param triggerData User supplied data needed for checking trigger conditions
    /// @param subData User supplied data used in recipe
    struct StrategySub {
        uint64 strategyOrBundleId;
        bool isBundle;
        bytes[] triggerData;
        bytes32[] subData;
    }

    /// @dev Data needed when signing relay transaction
    /// @param maxTxCostInFeeToken Max tx cost user is willing to pay in fee token
    /// @param feeToken Address of the token user is willing to pay fee in
    /// @param tokenPriceInEth Price of the token in ETH
    /// @param deadline Deadline for the relay transaction to be executed
    /// @param shouldTakeFeeFromPosition Flag to indicate if fee should be taken from position, otherwise from EOA/wallet
    struct TxSaverSignedData {
        uint256 maxTxCostInFeeToken;
        address feeToken;
        uint256 tokenPriceInEth;
        uint256 deadline;
        bool shouldTakeFeeFromPosition;
    }
}

contracts/exchangeV3/DFSExchangeCore.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;

import { IExchangeV3 } from "../interfaces/exchange/IExchangeV3.sol";
import { DFSExchangeData } from "./DFSExchangeData.sol";
import { Discount } from "../utils/Discount.sol";
import { FeeRecipient } from "../utils/fee/FeeRecipient.sol";
import { IOffchainWrapper } from "../interfaces/exchange/IOffchainWrapper.sol";
import { ExchangeHelper } from "./helpers/ExchangeHelper.sol";
import { StrategyModel } from "../core/strategy/StrategyModel.sol";
import { SafeERC20 } from "../_vendor/openzeppelin/SafeERC20.sol";
import { IERC20 } from "../interfaces/token/IERC20.sol";
import { TokenUtils } from "../utils/token/TokenUtils.sol";
import { DSMath } from "../_vendor/DS/DSMath.sol";

contract DFSExchangeCore is DSMath, DFSExchangeData, ExchangeHelper, StrategyModel {
    using SafeERC20 for IERC20;
    using TokenUtils for address;

    error SlippageHitError(uint256 amountBought, uint256 amountExpected);
    error InvalidWrapperError(address wrapperAddr);

    /// @notice Internal method that performs a sell on offchain aggregator/on-chain
    /// @dev Useful for other DFS contract to integrate for exchanging
    /// @param exData Exchange data struct
    function _sell(ExchangeData memory exData)
        internal
        returns (address wrapperAddress, uint256 destAmount)
    {
        (wrapperAddress, destAmount,) = _sell(exData, address(this));
    }

    /// @notice Internal method that performs a sell on offchain aggregator/on-chain
    /// @dev Useful for other DFS contract to integrate for exchanging
    /// @param exData Exchange data struct
    /// @return (address, uint, bool) Address of the wrapper used and destAmount and if there was fee
    function _sell(ExchangeData memory exData, address smartWallet)
        internal
        returns (address, uint256, bool)
    {
        uint256 amountWithoutFee = exData.srcAmount;
        uint256 destBalanceBefore = exData.destAddr.getBalance(address(this));

        _takeDfsExchangeFee(exData, smartWallet);

        address wrapperAddr = _executeSwap(exData);

        uint256 destBalanceAfter = exData.destAddr.getBalance(address(this));
        uint256 amountBought = destBalanceAfter - destBalanceBefore;

        // check slippage
        if (amountBought < wmul(exData.minPrice, exData.srcAmount)) {
            revert SlippageHitError(amountBought, wmul(exData.minPrice, exData.srcAmount));
        }

        bool hasFee = exData.srcAmount != amountWithoutFee;
        // revert back exData changes to keep it consistent
        exData.srcAmount = amountWithoutFee;

        return (wrapperAddr, amountBought, hasFee);
    }

    /// @notice Takes order from exchange aggregator and returns bool indicating if it is successful
    /// @param _exData Exchange data
    function offChainSwap(ExchangeData memory _exData) internal returns (bool success, uint256) {
        /// @dev Check if exchange address is in our registry to not call an untrusted contract
        if (!_getExchangeAggregatorRegistry()
                .isExchangeAggregatorAddr(_exData.offchainData.exchangeAddr)) {
            return (false, 0);
        }

        /// @dev Check if we have the address is a registered wrapper
        if (!_getWrapperExchangeRegistry().isWrapper(_exData.offchainData.wrapper)) {
            return (false, 0);
        }

        // send src amount
        IERC20(_exData.srcAddr).safeTransfer(_exData.offchainData.wrapper, _exData.srcAmount);

        return IOffchainWrapper(_exData.offchainData.wrapper).takeOrder(_exData);
    }

    /// @notice Calls wrapper contract for exchange to preform an on-chain swap
    /// @param _exData Exchange data struct
    /// @return swappedTokens Dest amount of tokens we get after sell
    function onChainSwap(ExchangeData memory _exData) internal returns (uint256 swappedTokens) {
        if (!_getWrapperExchangeRegistry().isWrapper(_exData.wrapper)) {
            revert InvalidWrapperError(_exData.wrapper);
        }

        IERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount);

        swappedTokens = IExchangeV3(_exData.wrapper)
            .sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData);
    }

    function _takeDfsExchangeFee(ExchangeData memory exData, address smartWallet) internal {
        if (exData.dfsFeeDivider != 0) {
            exData.srcAmount = sub(
                exData.srcAmount,
                getFee(exData.srcAmount, smartWallet, exData.srcAddr, exData.dfsFeeDivider)
            );
        }
    }

    function _executeSwap(ExchangeData memory exData) internal returns (address wrapperAddr) {
        wrapperAddr = exData.offchainData.wrapper;
        bool offChainSwapSuccess;

        // Try offchain aggregator first and then fallback on specific wrapper
        if (exData.offchainData.price > 0) {
            (offChainSwapSuccess,) = offChainSwap(exData);
        }

        // fallback to desired wrapper if offchain aggregator failed
        if (!offChainSwapSuccess) {
            onChainSwap(exData);
            wrapperAddr = exData.wrapper;
        }
    }

    /// @notice Takes a feePercentage and sends it to wallet
    /// @param _amount Amount of the whole trade
    /// @param _wallet Address of the users wallet
    /// @param _token Address of the token
    /// @param _dfsFeeDivider Dfs fee divider
    /// @return feeAmount Amount owner earned on the fee
    function getFee(uint256 _amount, address _wallet, address _token, uint256 _dfsFeeDivider)
        internal
        returns (uint256 feeAmount)
    {
        if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).serviceFeesDisabled(_wallet)) {
            _dfsFeeDivider = 0;
        }

        if (_dfsFeeDivider == 0) {
            feeAmount = 0;
        } else {
            feeAmount = _amount / _dfsFeeDivider;
            address walletAddr = FeeRecipient(FEE_RECIPIENT_ADDRESS).getFeeAddr();
            _token.withdrawTokens(walletAddr, feeAmount);
        }
    }
}

contracts/exchangeV3/DFSExchangeData.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;

contract DFSExchangeData {
    struct OffchainData {
        address wrapper; // dfs wrapper address for the aggregator (must be in WrapperExchangeRegistry)
        address exchangeAddr; // exchange address we are calling to execute the order (must be in ExchangeAggregatorRegistry)
        address allowanceTarget; // exchange aggregator contract we give allowance to
        uint256 price; // expected price that the aggregator sent us
        uint256 protocolFee; // deprecated (used as a separate fee amount for 0x v1)
        bytes callData; // 0ff-chain calldata the aggregator gives to perform the swap
    }

    struct ExchangeData {
        address srcAddr; // source token address (which we're selling)
        address destAddr; // destination token address (which we're buying)
        uint256 srcAmount; // amount of source token in token decimals
        uint256 destAmount; // amount of bought token in token decimals
        uint256 minPrice; // minPrice we are expecting (checked in DFSExchangeCore)
        uint256 dfsFeeDivider; // service fee divider
        address user; // currently deprecated (used to check custom fees for the user)
        address wrapper; // on-chain wrapper address (must be in WrapperExchangeRegistry)
        bytes wrapperData; // on-chain additional data for on-chain (uniswap route for example)
        OffchainData offchainData; // offchain aggregator order
    }

    struct InjectedExchangeData {
        address wrapper; // on-chain wrapper address (must be in WrapperExchangeRegistry)
        bytes wrapperData; // on-chain additional data for on-chain (uniswap route for example)
        OffchainData offchainData; // offchain aggregator order
    }
}

contracts/exchangeV3/DFSExchangeWithTxSaver.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;

import { DFSExchangeCore } from "./DFSExchangeCore.sol";
import { SafeERC20 } from "../_vendor/openzeppelin/SafeERC20.sol";
import { TokenUtils } from "../utils/token/TokenUtils.sol";
import { IERC20 } from "../interfaces/token/IERC20.sol";
import { TxSaverGasCostCalc } from "../tx-saver/TxSaverGasCostCalc.sol";
import {
    ITxSaverBytesTransientStorage
} from "../interfaces/core/ITxSaverBytesTransientStorage.sol";
import { IDFSRegistry } from "../interfaces/core/IDFSRegistry.sol";
import { DFSIds } from "../utils/DFSIds.sol";

contract DFSExchangeWithTxSaver is DFSExchangeCore, TxSaverGasCostCalc {
    using SafeERC20 for IERC20;
    using TokenUtils for address;

    uint256 constant EOA_OR_WALLET_FEE_FLAG = 2; // see TxSaverBytesTransientStorage

    /// For TxSaver, total gas cost fee taken from user can't be higher than maxTxCost set by user
    error TxCostInFeeTokenTooHighError(uint256 maxTxCost, uint256 txCost);

    error FeeTokenNotSameAsSrcToken(address srcToken, address feeToken);

    function _sellWithTxSaverChoice(
        ExchangeData memory _exData,
        address _user,
        IDFSRegistry _registry
    )
        internal
        returns (address wrapperAddress, uint256 destAmount, bool hasFee, bool txSaverFeeTaken)
    {
        address txSaverAddr = _registry.getAddr(DFSIds.TX_SAVER_EXECUTOR);
        ITxSaverBytesTransientStorage tStorage = ITxSaverBytesTransientStorage(txSaverAddr);

        // Check if TxSaverExecutor initiated transaction by setting right flag in transient storage.
        // We can't just check for msg.sender, as that wouldn't work for flashloan actions.
        // If no txSaverAddr is registered for this chain, default to regular sell.
        uint256 feeType = (txSaverAddr != address(0)) ? tStorage.getFeeType() : 0;

        // if not initiated by TxSaverExecutor, perform regular sell
        if (feeType == 0) {
            txSaverFeeTaken = false;
            (wrapperAddress, destAmount, hasFee) = _sell(_exData, _user);
            return (wrapperAddress, destAmount, hasFee, txSaverFeeTaken);
        }

        (
            uint256 estimatedGas,
            uint256 l1GasCostInEth,
            TxSaverSignedData memory txSaverData,
            InjectedExchangeData memory injectedExchangeData
        ) = _readDataFromTransientStorage(feeType, tStorage);

        uint256 amountWithoutFee = _exData.srcAmount;

        _injectExchangeData(_exData, injectedExchangeData);

        // when taking fee from EOA/wallet perform regular sell
        // fee is taken inside the RecipeExecutor
        if (feeType == EOA_OR_WALLET_FEE_FLAG) {
            txSaverFeeTaken = false;
            (wrapperAddress, destAmount, hasFee) = _sell(_exData, _user);
            return (wrapperAddress, destAmount, hasFee, txSaverFeeTaken);
        }

        // when taking fee from position, take tx cost before regular sell
        _takeTxSaverFee(_exData, txSaverData, estimatedGas, l1GasCostInEth);
        txSaverFeeTaken = true;

        // perform regular sell
        (wrapperAddress, destAmount, hasFee) = _sell(_exData, _user);

        // revert back exData changes to keep it consistent
        _exData.srcAmount = amountWithoutFee;
    }

    // Order of execution:
    // 1. Both off-chain and on-chain orders are injected:
    //    - Try the off-chain injected order first → then fall back to the on-chain injected order
    // 2. Only an off-chain order is injected:
    //    - Try the off-chain injected order first → then fall back to an existing on-chain order (if present)
    // 3. Only an on-chain order is injected:
    //    - Try the existing off-chain order first → then fall back to the on-chain injected order
    // 4. No orders are injected:
    //    - Try the existing off-chain order first → then fall back to the existing on-chain order (if present)
    function _injectExchangeData(
        ExchangeData memory _exData,
        InjectedExchangeData memory _injectedExchangeData
    ) internal pure {
        // If off-chain order data is present, inject it here.
        if (_injectedExchangeData.offchainData.price > 0) {
            _exData.offchainData = _injectedExchangeData.offchainData;
        }

        // If on-chain order data is present, inject it here.
        // We do not clear any existing off-chain order, as it should be tried first.
        if (_injectedExchangeData.wrapper != address(0)) {
            _exData.wrapper = _injectedExchangeData.wrapper;
            _exData.wrapperData = _injectedExchangeData.wrapperData;
        }
    }

    function _readDataFromTransientStorage(
        uint256 _feeType,
        ITxSaverBytesTransientStorage _tStorage
    )
        internal
        view
        returns (
            uint256 estimatedGas,
            uint256 l1GasCostInEth,
            TxSaverSignedData memory txSaverData,
            InjectedExchangeData memory injectedExchangeData
        )
    {
        if (_feeType == EOA_OR_WALLET_FEE_FLAG) {
            (estimatedGas, l1GasCostInEth, injectedExchangeData) = abi.decode(
                _tStorage.getBytesTransiently(), (uint256, uint256, InjectedExchangeData)
            );
        } else {
            (estimatedGas, l1GasCostInEth, txSaverData, injectedExchangeData) = abi.decode(
                _tStorage.getBytesTransiently(),
                (uint256, uint256, TxSaverSignedData, InjectedExchangeData)
            );
        }
    }

    function _takeTxSaverFee(
        ExchangeData memory _exData,
        TxSaverSignedData memory _txSaverData,
        uint256 _estimatedGas,
        uint256 _l1GasCostInEth
    ) internal {
        // when sending sponsored tx, no tx cost is taken
        if (_estimatedGas == 0) return;

        // calculate gas cost in src token
        uint256 txCostInSrcToken = calcGasCostUsingInjectedPrice(
            _estimatedGas, _exData.srcAddr, _txSaverData.tokenPriceInEth, _l1GasCostInEth
        );

        // revert if tx cost is higher than max value set by user
        if (txCostInSrcToken > _txSaverData.maxTxCostInFeeToken) {
            revert TxCostInFeeTokenTooHighError(_txSaverData.maxTxCostInFeeToken, txCostInSrcToken);
        }
        if (_exData.srcAddr != _txSaverData.feeToken) {
            revert FeeTokenNotSameAsSrcToken(_exData.srcAddr, _txSaverData.feeToken);
        }

        // subtract tx cost from src amount and send it to fee recipient
        _exData.srcAmount = sub(_exData.srcAmount, txCostInSrcToken);
        _exData.srcAddr.withdrawTokens(TX_SAVER_FEE_RECIPIENT, txCostInSrcToken);
    }
}

contracts/exchangeV3/helpers/ExchangeHelper.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

import {
    IExchangeAggregatorRegistry
} from "../../interfaces/exchange/IExchangeAggregatorRegistry.sol";
import { IWrapperExchangeRegistry } from "../../interfaces/exchange/IWrapperExchangeRegistry.sol";
import { IDFSRegistry } from "../../interfaces/core/IDFSRegistry.sol";
import { DFSIds } from "../../utils/DFSIds.sol";
import { MainnetExchangeAddresses } from "./MainnetExchangeAddresses.sol";

contract ExchangeHelper is MainnetExchangeAddresses {
    function _getExchangeAggregatorRegistry() internal view returns (IExchangeAggregatorRegistry) {
        return IExchangeAggregatorRegistry(
            IDFSRegistry(DFS_REGISTRY_ADDR).getAddr(DFSIds.EXCHANGE_AGGREGATOR_REGISTRY)
        );
    }

    function _getWrapperExchangeRegistry() internal view returns (IWrapperExchangeRegistry) {
        return IWrapperExchangeRegistry(
            IDFSRegistry(DFS_REGISTRY_ADDR).getAddr(DFSIds.WRAPPER_EXCHANGE_REGISTRY)
        );
    }
}

contracts/exchangeV3/helpers/MainnetExchangeAddresses.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

contract MainnetExchangeAddresses {
    address internal constant FEE_RECIPIENT_ADDRESS = 0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A;
    address internal constant DISCOUNT_ADDRESS = 0x84fE6D4aaD0CA1ce3af7153eecd11729fa7a74f0;
    address internal constant DFS_REGISTRY_ADDR = 0x287778F121F134C66212FB16c9b53eC991D32f5b;
    address internal constant TOKEN_GROUP_REGISTRY = 0xcA49e64FE1FE8be40ED30F682edA1b27a6c8611c;
}

contracts/exchangeV3/registries/TokenGroupRegistry.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;

import { ITokenGroupRegistry } from "../../interfaces/exchange/ITokenGroupRegistry.sol";
import { AdminAuth } from "../../auth/AdminAuth.sol";

/// @title TokenGroupRegistry
/// @notice Keeps track of tokens that are in a same group for different fee models
contract TokenGroupRegistry is AdminAuth, ITokenGroupRegistry {
    /// @notice 0.25% fee as we divide the amount with this number
    uint256 public constant STANDARD_FEE_DIVIDER = 400;

    /// @notice 0.1% fee as we divide the amount with this number
    uint256 public constant STABLE_FEE_DIVIDER = 1000;

    /// @notice Maximum fee divider, which means max fee is 2%
    uint256 public constant MAX_FEE_DIVIDER = 50;

    /// @notice Maps token address to a registered group it belongs to
    mapping(address => uint256) public groupIds;

    /// @notice Array of groups where the index is the grouped id and the value is the fee
    uint256[] public feesPerGroup;

    enum Groups {
        NOT_LISTED,
        BANNED,
        STABLECOIN,
        ETH_BASED,
        BTC_BASED
    }

    error FeeTooHigh(uint256 fee);
    error GroupNonExistent(uint256 groupId);

    constructor() {
        feesPerGroup.push(STANDARD_FEE_DIVIDER); // NOT_LISTED
        feesPerGroup.push(0); // BANNED
        feesPerGroup.push(STABLE_FEE_DIVIDER); // STABLECOIN
        feesPerGroup.push(STABLE_FEE_DIVIDER); // ETH_BASED
        feesPerGroup.push(STABLE_FEE_DIVIDER); // BTC_BASED
    }

    /// @notice Checks if 2 tokens are in the same group and returns the correct exchange fee for the pair
    /// @param _sellToken Sell token address
    /// @param _buyToken Buy token address
    /// @return fee Divider for the fee
    function getFeeForTokens(address _sellToken, address _buyToken) public view returns (uint256) {
        uint256 firstId = groupIds[_sellToken];
        uint256 secondId = groupIds[_buyToken];

        // Check if in the ban list, can just check the first token as we take fee from it.
        if (firstId == uint8(Groups.BANNED)) {
            return 0;
        }

        // If the tokens are in the same group, return the fee for the group.
        if (firstId == secondId) {
            return feesPerGroup[secondId];
        }

        return STANDARD_FEE_DIVIDER;
    }

    /////////////////////////////// ONLY OWNER FUNCTIONS ///////////////////////////////

    /// @notice Adds token to an existing group
    /// @dev This will overwrite if token is part of a different group
    /// @dev Groups needs to exist to add to it
    function addTokenInGroup(address _tokenAddr, uint256 _groupId) public onlyOwner {
        if (_groupId > feesPerGroup.length) revert GroupNonExistent(_groupId);

        groupIds[_tokenAddr] = _groupId;
    }

    /// @notice Add multiple tokens to a group
    function addTokensInGroup(address[] memory _tokensAddr, uint256 _groupId) public onlyOwner {
        if (_groupId > feesPerGroup.length) revert GroupNonExistent(_groupId);

        for (uint256 i; i < _tokensAddr.length; ++i) {
            groupIds[_tokensAddr[i]] = _groupId;
        }
    }

    /// @notice Create new group and add tokens
    /// @dev Divider has to gte 50, which means max fee is 2%
    function addNewGroup(address[] memory _tokensAddr, uint256 _feeDivider) public onlyOwner {
        if (_feeDivider < MAX_FEE_DIVIDER) revert FeeTooHigh(_feeDivider);

        feesPerGroup.push(_feeDivider);

        addTokensInGroup(_tokensAddr, feesPerGroup.length - 1);
    }

    /// @notice Change existing group fee
    /// @dev Divider has to be gte 50, which means max fee is 2%
    function changeGroupFee(uint256 _groupId, uint256 _newFeeDivider) public onlyOwner {
        if (_newFeeDivider < MAX_FEE_DIVIDER) revert FeeTooHigh(_newFeeDivider);

        feesPerGroup[_groupId] = _newFeeDivider;
    }
}

contracts/interfaces/DS/IDSProxy.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

interface IDSProxy {
    function execute(bytes memory _code, bytes memory _data)
        external
        payable
        returns (address, bytes32);

    function execute(address _target, bytes memory _data) external payable returns (bytes32);

    function setCache(address _cacheAddr) external payable returns (bool);

    function owner() external view returns (address);

    function guard() external view returns (address);
}

contracts/interfaces/DS/IDSProxyFactory.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

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

interface IDSProxyFactory {
    function isProxy(address _proxy) external view returns (bool);
    function build(address owner) external returns (IDSProxy proxy);
    function build() external returns (IDSProxy proxy);
}

contracts/interfaces/auth/IAdminVault.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

interface IAdminVault {
    function owner() external view returns (address);
    function admin() external view returns (address);
    function changeOwner(address _owner) external;
    function changeAdmin(address _admin) external;
}

contracts/interfaces/core/IDFSRegistry.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

interface IDFSRegistry {
    function getAddr(bytes4 _id) external view returns (address);

    function addNewContract(bytes4 _id, address _contractAddr, uint256 _waitPeriod) external;

    function startContractChange(bytes4 _id, address _newContractAddr) external;

    function approveContractChange(bytes4 _id) external;

    function cancelContractChange(bytes4 _id) external;
}

contracts/interfaces/core/ITxSaverBytesTransientStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

interface ITxSaverBytesTransientStorage {
    function getFeeType() external view returns (uint256);
    function getBytesTransiently() external view returns (bytes memory result);
}

contracts/interfaces/exchange/IExchangeAggregatorRegistry.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

interface IExchangeAggregatorRegistry {
    function isExchangeAggregatorAddr(address _exchangeAddr) external view returns (bool);
    function setExchangeTargetAddr(address _exchangeAddr, bool _state) external;
}

contracts/interfaces/exchange/IExchangeV3.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

/// @title IExchangeV3
/// @notice Shared interface for on-chain exchange wrapper contracts.
/// @dev Important security assumptions, which apply to every implementation:
/// 1. Exchange wrapper contracts are not intended to be used standalone, but as part of a DFS sell action,
///    which performs additional checks before forwarding the order and a final slippage check after the swap.
///    See DFSExchangeCore for more details.
/// 2. On-chain wrappers are primarily used for simulations and testing.
/// 3. Wrapper contracts are designed to be stateless, meaning they do not hold funds,
///    and any token balances can be cleared by anyone.
interface IExchangeV3 {
    /// @notice Sells `_srcAmount` of `_srcAddr` for `_destAddr` and returns the amount received
    /// @dev Implementations must approve exactly `_srcAmount` to the router, revoke that allowance
    /// after the swap and forward any unused source tokens to the caller.
    /// Slippage is checked in DFSExchangeCore instead of in the wrapper.
    /// @param _srcAddr The token to sell
    /// @param _destAddr The token to buy
    /// @param _srcAmount The amount of tokens to sell
    /// @param _additionalData Exchange specific route and swap params
    /// @return amountOut Amount of destination tokens received
    function sell(
        address _srcAddr,
        address _destAddr,
        uint256 _srcAmount,
        bytes memory _additionalData
    ) external returns (uint256 amountOut);

    /// @notice Returns the rate for which `_srcAmount` of `_srcAddr` can be sold for `_destAddr`
    /// @param _srcAddr The token to sell
    /// @param _destAddr The token to buy
    /// @param _srcAmount The amount of tokens to sell
    /// @param _additionalData Exchange specific route and swap params
    /// @return rate The sell rate
    function getSellRate(
        address _srcAddr,
        address _destAddr,
        uint256 _srcAmount,
        bytes memory _additionalData
    ) external returns (uint256 rate);
}

contracts/interfaces/exchange/IOffchainWrapper.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

import { DFSExchangeData } from "../../exchangeV3/DFSExchangeData.sol";

/// @title IOffchainWrapper
/// @notice Shared interface for off-chain exchange wrapper contracts.
/// @dev Important security assumptions, which apply to every implementation:
/// 1. Exchange wrapper contracts are not intended to be used standalone, but as part of a DFS sell action,
///    which performs additional checks before forwarding the order and a final slippage check after the swap.
///    See DFSExchangeCore for more details.
/// 2. Wrapper contracts are designed to be stateless, meaning they do not hold funds,
///    and any token balances can be cleared by anyone.
interface IOffchainWrapper {
    /// @notice Takes an order on the off-chain exchange and returns bool indicating if it is successful
    /// @dev Implementations must approve exactly `_exData.srcAmount` to `offchainData.allowanceTarget`,
    /// revoke that allowance before returning, and refund any leftover funds to the caller.
    /// @param _exData The exchange data
    /// @return success Whether the swap was successful
    /// @return tokensSwapped Amount of destination tokens received
    function takeOrder(DFSExchangeData.ExchangeData memory _exData)
        external
        payable
        returns (bool success, uint256 tokensSwapped);
}

contracts/interfaces/exchange/ITokenGroupRegistry.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;

/// @title ITokenGroupRegistry
interface ITokenGroupRegistry {
    function getFeeForTokens(address _sellToken, address _buyToken) external view returns (uint256);

    function addTokenInGroup(address _tokenAddr, uint256 _groupId) external;
    function addTokensInGroup(address[] memory _tokensAddr, uint256 _groupId) external;
    function addNewGroup(address[] memory _tokensAddr, uint256 _feeDivider) external;
    function changeGroupFee(uint256 _groupId, uint256 _newFeeDivider) external;
}

contracts/interfaces/exchange/IWrapperExchangeRegistry.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

interface IWrapperExchangeRegistry {
    function isWrapper(address _wrapper) external view returns (bool);
    function addWrapper(address _wrapper) external;
    function removeWrapper(address _wrapper) external;
}

contracts/interfaces/protocols/insta/IInstaList.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;

interface IInstaList {
    struct AccountLink {
        address first;
        address last;
        uint64 count;
    }

    struct AccountList {
        address prev;
        address next;
    }

    struct UserLink {
        uint64 first;
        uint64 last;
        uint64 count;
    }

    struct UserList {
        uint64 prev;
        uint64 next;
    }

    function accountAddr(uint64 _id) external view returns (address);
    function accountID(address _addr) external view returns (uint64);
    function accountLink(uint64 _id) external view returns (AccountLink memory);
    function accountList(uint64 _id, address _user) external view returns (AccountList memory);
    function userLink(address _user) external view returns (UserLink memory);
    function userList(address _user, uint64 _id) external view returns (UserList memory);
}

contracts/interfaces/protocols/safe/ISafe.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

interface ISafe {
    enum Operation {
        Call,
        DelegateCall
    }

    function setup(
        address[] calldata _owners,
        uint256 _threshold,
        address to,
        bytes calldata data,
        address fallbackHandler,
        address paymentToken,
        uint256 payment,
        address payable paymentReceiver
    ) external;

    function execTransaction(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation,
        uint256 safeTxGas,
        uint256 baseGas,
        uint256 gasPrice,
        address gasToken,
        address payable refundReceiver,
        bytes memory signatures
    ) external payable returns (bool success);

    function execTransactionFromModule(
        address to,
        uint256 value,
        bytes memory data,
        Operation operation
    ) external returns (bool success);

    function checkSignatures(bytes32 dataHash, bytes memory data, bytes memory signatures)
        external
        view;

    function checkNSignatures(
        address executor,
        bytes32 dataHash,
        bytes memory, /* data */
        bytes memory signatures,
        uint256 requiredSignatures
    ) external view;

    function approveHash(bytes32 hashToApprove) external;

    function domainSeparator() external view returns (bytes32);

    function getTransactionHash(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation,
        uint256 safeTxGas,
        uint256 baseGas,
        uint256 gasPrice,
        address gasToken,
        address refundReceiver,
        uint256 _nonce
    ) external view returns (bytes32);

    function nonce() external view returns (uint256);

    function setFallbackHandler(address handler) external;

    function getOwners() external view returns (address[] memory);

    function isOwner(address owner) external view returns (bool);

    function getThreshold() external view returns (uint256);

    function enableModule(address module) external;

    function isModuleEnabled(address module) external view returns (bool);

    function disableModule(address prevModule, address module) external;

    function getModulesPaginated(address start, uint256 pageSize)
        external
        view
        returns (address[] memory array, address next);
}

contracts/interfaces/token/IERC20.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

interface IERC20 {
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint256 digits);
    function totalSupply() external view returns (uint256 supply);

    function balanceOf(address _owner) external view returns (uint256 balance);

    function transfer(address _to, uint256 _value) external returns (bool success);

    function transferFrom(address _from, address _to, uint256 _value)
        external
        returns (bool success);

    function approve(address _spender, uint256 _value) external returns (bool success);

    function allowance(address _owner, address _spender) external view returns (uint256 remaining);

    event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}

contracts/interfaces/token/IWETH.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

interface IWETH {
    function allowance(address, address) external view returns (uint256);

    function balanceOf(address) external view returns (uint256);

    function approve(address, uint256) external;

    function transfer(address, uint256) external returns (bool);

    function transferFrom(address, address, uint256) external returns (bool);

    function deposit() external payable;

    function withdraw(uint256) external;
}

contracts/tx-saver/TxSaverGasCostCalc.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

import { TokenUtils } from "../utils/token/TokenUtils.sol";
import { DSMath } from "../_vendor/DS/DSMath.sol";
import { UtilAddresses } from "../utils/addresses/UtilAddresses.sol";

contract TxSaverGasCostCalc is DSMath, UtilAddresses {
    using TokenUtils for address;

    // only support token with decimals <= 18
    error TokenDecimalsTooHigh(uint256 decimals);
    // when injecting price, price must be greater than 0
    error ZeroTokenPriceInEthError();

    function calcGasCostUsingInjectedPrice(
        uint256 _gasUsed,
        address _feeToken,
        uint256 _tokenPriceInEth,
        uint256 _l1GasCostInEth
    ) internal view returns (uint256 txCost) {
        // can't use more gas than the block gas limit
        if (_gasUsed > block.gaslimit) {
            _gasUsed = block.gaslimit;
        }

        // calc gas used
        txCost = (_gasUsed * tx.gasprice) + _l1GasCostInEth;

        // convert to token amount
        if (_feeToken != TokenUtils.WETH_ADDR) {
            uint256 tokenDecimals = _feeToken.getTokenDecimals();

            if (tokenDecimals > 18) revert TokenDecimalsTooHigh(tokenDecimals);

            if (_tokenPriceInEth == 0) revert ZeroTokenPriceInEthError();

            txCost = wdiv(txCost, _tokenPriceInEth) / (10 ** (18 - tokenDecimals));
        }
    }
}

contracts/utils/DFSIds.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;

library DFSIds {
    bytes4 internal constant DFS_PROXY_REGISTRY_V2 = bytes4(keccak256("DFSProxyRegistryV2"));
    bytes4 internal constant RECIPE_EXECUTOR = bytes4(keccak256("RecipeExecutor"));
    bytes4 internal constant STRATEGY_EXECUTOR = bytes4(keccak256("StrategyExecutorID")); // Abstract, so support both L1 and L2
    bytes4 internal constant TX_SAVER_EXECUTOR = bytes4(keccak256("TxSaverExecutor"));
    bytes4 internal constant BOT_AUTH = bytes4(keccak256("BotAuth"));
    bytes4 internal constant BOT_AUTH_FOR_TX_SAVER = bytes4(keccak256("BotAuthForTxSaver"));
    bytes4 internal constant KYBER_SCALING_HELPER = bytes4(keccak256("KyberInputScalingHelper"));
    bytes4 internal constant WRAPPER_EXCHANGE_REGISTRY =
        bytes4(keccak256("WrapperExchangeRegistry"));
    bytes4 internal constant EXCHANGE_AGGREGATOR_REGISTRY =
        bytes4(keccak256("ExchangeAggregatorRegistry"));
    bytes4 internal constant LLAMALEND_SWAPPER = bytes4(keccak256("LlamaLendSwapper"));
    bytes4 internal constant CURVE_TRANSIENT_SWAPPER =
        bytes4(keccak256("CurveUsdSwapperTransient"));
    bytes4 internal constant SFPROXY_ENTRY_POINT = bytes4(keccak256("SFProxyEntryPoint"));
}

contracts/utils/DFSTypes.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

enum WalletType {
    DSPROXY,
    SAFE,
    DSAPROXY,
    SFPROXY
}

contracts/utils/DefisaverLogger.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

contract DefisaverLogger {
    event RecipeEvent(address indexed caller, string indexed logName);

    event ActionDirectEvent(address indexed caller, string indexed logName, bytes data);

    function logRecipeEvent(string memory _logName) public {
        emit RecipeEvent(msg.sender, _logName);
    }

    function logActionDirectEvent(string memory _logName, bytes memory _data) public {
        emit ActionDirectEvent(msg.sender, _logName, _data);
    }
}

contracts/utils/Discount.sol

// SPDX-License-Identifier: MIT
pragma solidity =0.8.24;

import { AdminAuth } from "../auth/AdminAuth.sol";

/// @title Contract used to check if a DFS user is exempt from paying a service fee
contract Discount is AdminAuth {
    mapping(address => bool) public serviceFeesDisabled;

    function reenableServiceFee(address _wallet) public onlyOwner {
        serviceFeesDisabled[_wallet] = false;
    }

    function disableServiceFee(address _wallet) public onlyOwner {
        serviceFeesDisabled[_wallet] = true;
    }
}

contracts/utils/SmartWalletUtils.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

import { IDSProxyFactory } from "../interfaces/DS/IDSProxyFactory.sol";
import { IInstaList } from "../interfaces/protocols/insta/IInstaList.sol";
import { IDSProxy } from "../interfaces/DS/IDSProxy.sol";
import { ISafe } from "../interfaces/protocols/safe/ISafe.sol";
import { DSProxyFactoryHelper } from "../utils/addresses/dsProxyFactory/DSProxyFactoryHelper.sol";
import {
    DSAProxyFactoryHelper
} from "../utils/addresses/dsaProxyFactory/DSAProxyFactoryHelper.sol";
import { SFProxyFactoryHelper } from "../utils/addresses/sfProxyFactory/SFProxyFactoryHelper.sol";
import { WalletType } from "../utils/DFSTypes.sol";

/// @title SmartWalletUtils - Helper contract with utility functions for smart wallets
contract SmartWalletUtils is DSProxyFactoryHelper, DSAProxyFactoryHelper, SFProxyFactoryHelper {
    /// @notice Determine the type of wallet an address represents
    function _getWalletType(address _wallet) internal view returns (WalletType) {
        if (_isDSProxy(_wallet)) {
            return WalletType.DSPROXY;
        }

        if (_isDSAProxy(_wallet)) {
            return WalletType.DSAPROXY;
        }

        if (_isSFProxy(_wallet)) {
            return WalletType.SFPROXY;
        }

        // Otherwise, we assume we are in context of Safe
        return WalletType.SAFE;
    }

    /// @notice Check if the wallet is a DSProxy
    function _isDSProxy(address _wallet) internal view returns (bool) {
        return IDSProxyFactory(PROXY_FACTORY_ADDR).isProxy(_wallet);
    }

    /// @notice Check if the wallet is a DSA Proxy Account
    function _isDSAProxy(address _wallet) internal view returns (bool) {
        return IInstaList(DSA_LIST_ADDR).accountID(_wallet) != 0;
    }

    /// @notice Check if the wallet is a Summerfi account
    function _isSFProxy(address _wallet) internal view returns (bool) {
        return _wallet.codehash == SF_PROXY_CODEHASH;
    }

    /// @notice Fetch the owner of the smart wallet or the wallet itself
    /// @dev For 1/1 Safe it returns the owner, otherwise it returns the wallet itself
    /// @dev Only supports Safe and DSProxy wallets because SFProxy and DSAProxy are not part of automation
    /// @param _wallet Address of the smart wallet
    /// @return Address of the owner or wallet
    function _fetchOwnerOrWallet(address _wallet) internal view returns (address) {
        if (_isDSProxy(_wallet)) return IDSProxy(_wallet).owner();

        // Otherwise, we assume we are in context of Safe
        address[] memory owners = ISafe(_wallet).getOwners();
        return owners.length == 1 ? owners[0] : _wallet;
    }
}

contracts/utils/addresses/MainnetUtilAddresses.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

contract MainnetUtilAddresses {
    address internal refillCaller = 0x8973f5e6142ed2e2F50EEE8Bb34a47C2DAa6624a;

    address internal constant FEE_RECIPIENT_ADDR = 0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A;
    address internal constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
    address internal constant UNI_V2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
    address internal constant MKR_PROXY_REGISTRY = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
    address internal constant AAVE_MARKET = 0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5;
    address internal constant AAVE_V3_MARKET = 0x2f39d218133AFaB8F2B819B1066c7E434Ad94E9e;
    address internal constant SPARK_MARKET = 0x02C3eA4e34C0cBd694D2adFa2c690EECbC1793eE;

    address internal constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address internal constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
    address internal constant WSTETH_ADDR = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;
    address internal constant STETH_ADDR = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;
    address internal constant EETH_ADDR = 0x35fA164735182de50811E8e2E824cFb9B6118ac2;
    address internal constant WEETH_ADDR = 0xCd5fE23C85820F7B72D0926FC9b05b43E359b7ee;
    address internal constant WBTC_ADDR = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
    address internal constant CHAINLINK_WBTC_ADDR = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;
    address internal constant DAI_ADDR = 0x6B175474E89094C44Da98b954EedeAC495271d0F;

    address internal constant ETHER_FI_LIQUIDITY_POOL = 0x308861A430be4cce5502d0A12724771Fc6DaF216;

    address internal constant FEE_RECEIVER_ADMIN_ADDR = 0xA74e9791D7D66c6a14B2C571BdA0F2A1f6D64E06;

    address internal constant UNI_V3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
    address internal constant UNI_V3_QUOTER = 0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6;

    address internal constant FEE_RECIPIENT = 0x39C4a92Dc506300c3Ea4c67ca4CA611102ee6F2A;

    // not needed on mainnet
    address internal constant DEFAULT_BOT = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    address internal constant CHAINLINK_FEED_REGISTRY = 0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf;

    address internal constant TX_SAVER_FEE_RECIPIENT = 0x0eD7f3223266Ca1694F85C23aBe06E614Af3A479;
}

contracts/utils/addresses/UtilAddresses.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

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

contract UtilAddresses is MainnetUtilAddresses { }

contracts/utils/addresses/dsProxyFactory/DSProxyFactoryHelper.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

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

contract DSProxyFactoryHelper is MainnetProxyFactoryAddresses { }

contracts/utils/addresses/dsProxyFactory/MainnetProxyFactoryAddresses.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

contract MainnetProxyFactoryAddresses {
    address internal constant PROXY_FACTORY_ADDR = 0xA26e15C895EFc0616177B7c1e7270A4C7D51C997;
}

contracts/utils/addresses/dsaProxyFactory/DSAProxyFactoryHelper.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

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

contract DSAProxyFactoryHelper is MainnetDSAProxyFactoryAddresses { }

contracts/utils/addresses/dsaProxyFactory/MainnetDSAProxyFactoryAddresses.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

contract MainnetDSAProxyFactoryAddresses {
    address internal constant DSA_LIST_ADDR = 0x4c8a1BEb8a87765788946D6B19C6C6355194AbEb;
}

contracts/utils/addresses/sfProxyFactory/MainnetSFProxyFactoryAddresses.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

contract MainnetSFProxyFactoryAddresses {
    address internal constant SF_PROXY_FACTORY_ADDR = 0xF7B75183A2829843dB06266c114297dfbFaeE2b6;
    address internal constant SF_PROXY_GUARD = 0xCe91349d2A4577BBd0fC91Fe6019600e047f2847;
    bytes32 internal constant SF_PROXY_CODEHASH =
        0x15b0c1a13812f0fce8291b8e7786ece58e0daab08d489cdfe2899fdac4f66045;
}

contracts/utils/addresses/sfProxyFactory/SFProxyFactoryHelper.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

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

contract SFProxyFactoryHelper is MainnetSFProxyFactoryAddresses { }

contracts/utils/fee/FeeRecipient.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

import { AdminAuth } from "../../auth/AdminAuth.sol";

/// @title Stores the fee recipient address and allows the owner to change it
contract FeeRecipient is AdminAuth {
    address public wallet;

    constructor(address _newWallet) {
        wallet = _newWallet;
    }

    function getFeeAddr() public view returns (address) {
        return wallet;
    }

    function changeWalletAddr(address _newWallet) public onlyOwner {
        wallet = _newWallet;
    }
}

contracts/utils/token/TokenUtils.sol

// SPDX-License-Identifier: MIT

pragma solidity =0.8.24;

import { IWETH } from "../../interfaces/token/IWETH.sol";
import { IERC20 } from "../../interfaces/token/IERC20.sol";
import { SafeERC20 } from "../../_vendor/openzeppelin/SafeERC20.sol";

library TokenUtils {
    using SafeERC20 for IERC20;

    address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    /// @dev Only approves the amount if allowance is lower than amount, does not decrease allowance
    function approveToken(address _tokenAddr, address _to, uint256 _amount) internal {
        if (_tokenAddr == ETH_ADDR) return;

        if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) {
            IERC20(_tokenAddr).safeApprove(_to, _amount);
        }
    }

    function removeAllowance(address _tokenAddr, address _to) internal {
        if (_tokenAddr == ETH_ADDR || IERC20(_tokenAddr).allowance(address(this), _to) == 0) {
            return;
        }

        IERC20(_tokenAddr).safeApprove(_to, 0);
    }

    function pullTokensIfNeeded(address _token, address _from, uint256 _amount)
        internal
        returns (uint256)
    {
        // handle max uint amount
        if (_amount == type(uint256).max) {
            _amount = getBalance(_token, _from);
        }

        if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) {
            IERC20(_token).safeTransferFrom(_from, address(this), _amount);
        }

        return _amount;
    }

    function withdrawTokens(address _token, address _to, uint256 _amount)
        internal
        returns (uint256)
    {
        if (_amount == type(uint256).max) {
            _amount = getBalance(_token, address(this));
        }

        if (_to != address(0) && _to != address(this) && _amount != 0) {
            if (_token != ETH_ADDR) {
                IERC20(_token).safeTransfer(_to, _amount);
            } else {
                (bool success,) = _to.call{ value: _amount }("");
                require(success, "Eth send fail");
            }
        }

        return _amount;
    }

    function depositWeth(uint256 _amount) internal {
        IWETH(WETH_ADDR).deposit{ value: _amount }();
    }

    function withdrawWeth(uint256 _amount) internal {
        IWETH(WETH_ADDR).withdraw(_amount);
    }

    function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) {
        if (_tokenAddr == ETH_ADDR) {
            return _acc.balance;
        } else {
            return IERC20(_tokenAddr).balanceOf(_acc);
        }
    }

    function getTokenDecimals(address _token) internal view returns (uint256) {
        if (_token == ETH_ADDR) return 18;

        return IERC20(_token).decimals();
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.