Перейти к содержимому
Проверенный контрактТочноеLicenseRef-Aktionariat

PaymentHub

Адрес0xe8beccbda21f702f0f1ef680669774a0c120d2e4
Баланс

0 ETH

 

Транзакций

6

 

Компилятор

solc 0.8.30

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.30+commit.73712a01
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
prague
Лицензия
LicenseRef-Aktionariat
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
24 945 519
Транзакция создания
0xd6443325b6…1edb63d142

project/contracts/brokerbot/PaymentHub.sol

/**
* SPDX-License-Identifier: LicenseRef-Aktionariat
*
* MIT License with Automated License Fee Payments
*
* Copyright (c) 2022 Aktionariat AG (aktionariat.com)
*
* Permission is hereby granted to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* - The above copyright notice and this permission notice shall be included in
*   all copies or substantial portions of the Software.
* - All automated license fee payments integrated into this and related Software
*   are preserved.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity >=0.8.0 <0.9.0;

import "../utils/Address.sol";
import "../ERC20/IERC20.sol";
import "../ERC20/IERC20Permit.sol";
import "./IUniswapV3.sol";
import "../utils/Ownable.sol";
import "./IBrokerbot.sol";
import "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
import "../utils/SafeERC20.sol";

/**
 * A hub for payments. This allows tokens that do not support ERC 677 to enjoy similar functionality,
 * namely interacting with a token-handling smart contract in one transaction, without having to set an allowance first.
 * Instead, an allowance needs to be set only once, namely for this contract.
 * Further, it supports automatic conversion from Ether to the payment currency through Uniswap or the reception of Ether
 * using the current exchange rate as found in the chainlink oracle.
 */
contract PaymentHub {

    using SafeERC20 for IERC20;

    // Version history
    // Version 4: added path to pay with any ecr20 via uniswap
    // Version 5: added sell via permit
    // Version 6: added transferEther function
    // Version 7: added sell against eth and erc20, version, add permitinfo/swapinfo struct
    // Version 8: use SafeERC20 for transfers
    // Version 9: change payFromEther to include a swap path
    // Version 10: added checkAmount to prevent underpayment of shares, removed keep ether
    uint256 public constant VERSION = 10;

    uint256 private constant KEEP_ETHER = 0x4; // copied from brokerbot

    uint256 private constant DENOMINATOR = 1e8;
    address private constant XCHF_TOKEN = 0xB4272071eCAdd69d933AdcD19cA99fe80664fc08;
    address private constant ZCHF_TOKEN = 0xB58E61C3098d85632Df34EecfB899A1Ed80921cB;

    IQuoter private immutable uniswapQuoter;
    ISwapRouter private immutable uniswapRouter;
    AggregatorV3Interface internal immutable priceFeedCHFUSD;
    AggregatorV3Interface internal immutable priceFeedETHUSD;

    address public trustedForwarder;

    struct PermitInfo {
        uint256 exFee;
        uint256 deadline;
        uint8 v;
        bytes32 r;
        bytes32 s;
    }

    // event to when new forwarder is set
    event ForwarderChanged(address indexed _oldForwarder, address indexed _newForwarder);

	/*//////////////////////////////////////////////////////////////
                            Custom errors
    //////////////////////////////////////////////////////////////*/
    /// Failguard when an erc20 transfer returns false. 
    error PaymentHub_TransferFailed();
    /// Sender not trusted.
    /// @param sender The msg.sender of this transaction.
    error PaymentHub_InvalidSender(address sender);
    /// swap with less base token as required.
    /// @param amountBase Required amount.
    /// @param swappedAmount Swapped amount.
    error PaymentHub_SwapError(uint256 amountBase, uint256 swappedAmount);

    error InsufficientPayment(uint256 required, uint256 provided);

    constructor(address _trustedForwarder, IQuoter _quoter, ISwapRouter swapRouter, AggregatorV3Interface _aggregatorCHFUSD, AggregatorV3Interface _aggregatorETHUSD) {
        trustedForwarder = _trustedForwarder;
        uniswapQuoter = _quoter;
        uniswapRouter = swapRouter;
        priceFeedCHFUSD = _aggregatorCHFUSD;
        priceFeedETHUSD = _aggregatorETHUSD;
    }

    modifier onlySellerAndForwarder(address seller) {
        if (msg.sender != trustedForwarder && msg.sender != seller) {
            revert PaymentHub_InvalidSender(msg.sender);
        }
        _;
    }

    modifier onlyForwarder() {
        if (msg.sender != trustedForwarder) {
            revert PaymentHub_InvalidSender(msg.sender);
        }
        _;
    }

    /**
     * @notice Change the trusted forwarder.
     * @param newForwarder The new trusted forwarder.
     */
     function changeForwarder(address newForwarder) external onlyForwarder {
        trustedForwarder = newForwarder;
        emit ForwarderChanged(msg.sender, newForwarder);
    }

    /**  
     * Get price in ERC20
     * This is the method that the Brokerbot widget should use to quote the price to the user.
     * @param amountInBase The amount of the base currency for the exact output.
     * @param path The encoded path of the swap from erc20 to base.
     * @return amount quoted to pay
     */
    function getPriceInERC20(uint256 amountInBase, bytes memory path) public returns (uint256) {
        return getPriceERC20(amountInBase, path, true);
    }
    
    /**
     * @notice Get price for given amount and path swapped via uniswap. 
     * @param amount The exact amount which you want get out (exactOutput) or you put in (exactInput).
     * @param path The path of the swap (inreverse order for exactOutput).
     * @param exactOutput True if exactOutput should be used or false if exactInput should be used.
     */
    function getPriceERC20(uint256 amount, bytes memory path, bool exactOutput) public returns (uint256) {
        if (exactOutput) {
            return uniswapQuoter.quoteExactOutput(
                path,
                amount
            );
        } else {
            return uniswapQuoter.quoteExactInput(
                path,
                amount
            );
        }
    }

    /**
     * Get price in Ether depding on brokerbot setting.
     * If keep ETH is set price is from oracle.
     * This is the method that the Brokerbot widget should use to quote the price to the user.
     * @return The price in wei.
     */
    function getPriceInEther(uint256 amountInBase, IBrokerbot brokerBot, bytes calldata path) public returns (uint256) {
        if ((address(brokerBot) != address(0)) && hasSettingKeepEther(brokerBot)) {
            return getPriceInEtherFromOracle(amountInBase, IBrokerbot(brokerBot).base());
        } else {
            return getPriceERC20(amountInBase, path, true);
        }
    }

    /**
     * Price in ETH with 18 decimals
     */
    function getPriceInEtherFromOracle(uint256 amountInBase, IERC20 base) public view returns (uint256) {
        if(address(base) == XCHF_TOKEN || address(base) == ZCHF_TOKEN) {
            return getLatestPriceCHFUSD() * amountInBase / getLatestPriceETHUSD();
        } else {
            return amountInBase * DENOMINATOR / getLatestPriceETHUSD();
        }
    }

    /**
     * Returns the latest price of eth/usd pair from chainlink with 8 decimals
     */
    function getLatestPriceETHUSD() public view returns (uint256) {
        (, int256 price, , , ) = priceFeedETHUSD.latestRoundData();
        return uint256(price);
    }

    /**
     * Returns the latest price of chf/usd pair from chainlink with 8 decimals
     */
    function getLatestPriceCHFUSD() public view returns (uint256) {
        (, int256 price, , , ) = priceFeedCHFUSD.latestRoundData();
        return uint256(price);
    }

    /**
     * Convenience method to swap ether into base and pay a target address
     */
    function payFromEther(address recipient, uint256 amountInBase, bytes memory path) public payable returns (uint256 amountIn) {
        ISwapRouter swapRouter = uniswapRouter;
        // The parameter path is encoded as (tokenOut, fee, tokenIn/tokenOut, fee, tokenIn)
        ISwapRouter.ExactOutputParams memory params =
            ISwapRouter.ExactOutputParams({
                path: path,
                recipient: recipient,
                // solhint-disable-next-line not-rely-on-time
                deadline: block.timestamp,
                amountOut: amountInBase,
                amountInMaximum: msg.value
            });

        // Executes the swap, returning the amountIn actually spent.
        amountIn = swapRouter.exactOutput{value: msg.value}(params);

        // For exact output swaps, the amountInMaximum may not have all been spent.
        // If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0.
        if (amountIn < msg.value) {
            swapRouter.refundETH();
            (bool success, ) = msg.sender.call{value:msg.value - amountIn}(""); // return change
            if (!success) {
                revert PaymentHub_TransferFailed();
            }
        }
    }

    /// @dev The calling address must approve this contract to spend its ERC20 for this function to succeed. As the amount of input ERC20 is variable,
    /// the calling address will need to approve for a slightly higher or infinit amount, anticipating some variance.
    /// @param amountOut The desired amount of baseCurrency.
    /// @param amountInMaximum The maximum amount of ERC20 willing to be swapped for the specified amountOut of baseCurrency.
    /// @param erc20In The address of the erc20 token to pay with.
    /// @param path The encoded path of the swap from erc20 to base.
    /// @param recipient The reciving address - brokerbot.
    /// @return amountIn The amountIn of ERC20 actually spent to receive the desired amountOut.
    function payFromERC20(uint256 amountOut, uint256 amountInMaximum, address erc20In, bytes memory path, address recipient) public returns (uint256 amountIn) {
        ISwapRouter swapRouter = uniswapRouter;
        // Transfer the specified `amountInMaximum` to this contract.
        IERC20(erc20In).safeTransferFrom(msg.sender, address(this), amountInMaximum);

        // The parameter path is encoded as (tokenOut, fee, tokenIn/tokenOut, fee, tokenIn)
        ISwapRouter.ExactOutputParams memory params =
            ISwapRouter.ExactOutputParams({
                path: path,
                recipient: recipient,
                // solhint-disable-next-line not-rely-on-time
                deadline: block.timestamp,
                amountOut: amountOut,
                amountInMaximum: amountInMaximum
            });

        // Executes the swap, returning the amountIn actually spent.
        amountIn = swapRouter.exactOutput(params);

        // If the swap did not require the full amountInMaximum to achieve the exact amountOut then we refund msg.sender and approve the router to spend 0.
        if (amountIn < amountInMaximum) {
            IERC20(erc20In).safeTransfer(msg.sender, amountInMaximum - amountIn);
        }
    }

    ///This function appoves infinite allowance for Uniswap, this is safe as the paymenthub should never hold any token (see also recover() ).
    ///@dev This function needs to be called before using the PaymentHub the first time with a new ERC20 token.
    ///@param erc20In The erc20 addresse to approve.
    function approveERC20(address erc20In) external {
        IERC20(erc20In).approve(address(uniswapRouter), type(uint256).max);
    }

    function multiPay(IERC20 token, address[] calldata recipients, uint256[] calldata amounts) public {
        for (uint i=0; i<recipients.length; i++) {
            IERC20(token).safeTransferFrom(msg.sender, recipients[i], amounts[i]);
        }
    }

    /**
     * Can (at least in theory) save some gas as the sender balance only is touched in one transaction.
     */
    function multiPayAndNotify(IERC20 token, IBrokerbot[] calldata brokerbots, uint256[] calldata amounts, bytes calldata ref) external {
        for (uint i=0; i<brokerbots.length; i++) {
            payAndNotify(token, brokerbots[i], amounts[i], ref);
        }
    }

    /**
     * @notice Allows to make a base currency payment from the sender to the brokerbot, given an allowance to this contract.
     * @dev Equivalent to xchf.transferAndCall(brokerbot, amountInBase)
     * @param brokerbot The brokerbot to pay and receive the shares from.
     * @param amountInBase The amount of base currency used to buy shares.
     * @param ref The reference data blob.
     * @return The amount of shares bought
     */
    function payAndNotify(IBrokerbot brokerbot, uint256 amountInBase, bytes calldata ref) external returns (uint256) {
        return payAndNotify(brokerbot.base(), brokerbot, amountInBase, ref);
    }

    function payAndNotify(IERC20 token, IBrokerbot brokerbot, uint256 amount, bytes calldata ref) public returns (uint256) {
        token.safeTransferFrom(msg.sender, address(brokerbot), amount);
        uint256 shares = brokerbot.processIncoming(token, msg.sender, amount, ref);
        checkAmount(brokerbot, shares, amount);
        return shares;
    }

    function checkAmount(IBrokerbot brokerbot, uint256 shares, uint256 paid) internal view {
        uint256 price = brokerbot.getSellPrice(shares);
        if (price > paid) revert InsufficientPayment(price, paid);
    }

    /**
     * @notice Pay with Ether to buy shares.
     * @param brokerbot The brokerbot to pay and receive the shares from.
     * @param amountBase The amount of base currency used to buy shares.
     * @param ref The reference data blob.
     * @param path The Uniswap path from ETH to base currency (uses exactOuput => reverse order)
     * @return priceInEther The amount of Ether spent.
     * @return sharesOut The amount of shares bought.
     */
    function payFromEtherAndNotify(IBrokerbot brokerbot, uint256 amountBase, bytes calldata ref, bytes memory path) external payable returns (uint256 priceInEther, uint256 sharesOut) {
        IERC20 base = brokerbot.base();
       
        uint256 balanceBefore = IERC20(base).balanceOf(address(brokerbot));
        priceInEther = payFromEther(address(brokerbot), amountBase, path);
        uint256 balanceAfter = IERC20(base).balanceOf(address(brokerbot));
        if (amountBase != (balanceAfter - balanceBefore)) { // check that the swap was successful with correct currency
            revert PaymentHub_SwapError(amountBase, balanceAfter - balanceBefore);
        }    
        sharesOut = brokerbot.processIncoming(base, msg.sender, amountBase, ref); // not sending msg.value as this is already done in payFromEther function
        checkAmount(brokerbot, sharesOut, amountBase);
    }

    /***
     * @notice Pay from any ERC20 token (which has Uniswapv3 ERC20-ETH pool) and send swapped base currency to brokerbot.
     * @notice The needed amount needs to be approved at the ERC20 contract beforehand
     * @param brokerbot The brokerbot to pay and receive the shares from.
     * @param amountBase The amount of base currency used to buy shares.
     * @param erc20 The address of the ERC20 token to pay.
     * @param amountInMaximum The maximum amount of the ERC20 to pay (should include some slippage).
     * @param path The encoded path of the swap from erc20 to base currency.
     * @param ref Reference data blob.
     * @return amountIn The amount erc20 spent to buy shares.
     * @return amountOut The amount of shares received by the brokerbot.
     */
    function payFromERC20AndNotify(IBrokerbot brokerbot, uint256 amountBase, address erc20, uint256 amountInMaximum, bytes memory path, bytes calldata ref) external returns (uint256 amountIn, uint256 amountOut) {
        IERC20 base = brokerbot.base();
        uint256 balanceBefore = IERC20(base).balanceOf(address(brokerbot));
        amountIn = payFromERC20(amountBase, amountInMaximum, erc20, path, address(brokerbot));
        uint256 balanceAfter = IERC20(base).balanceOf(address(brokerbot));
        if (amountBase != (balanceAfter - balanceBefore)) {
            revert PaymentHub_SwapError(amountBase, balanceAfter - balanceBefore);
        }        
        amountOut = brokerbot.processIncoming(base, msg.sender, amountBase, ref);
        checkAmount(brokerbot, amountOut, amountBase);
    }

    /**
     * @notice Sell shares with permit
     * @param brokerbot The brokerbot to recive the shares.
     * @param seller The address of the seller.
     * @param recipient The address of the recipient of the sell preceeds.
     * @param amountToSell The amount the seller wants to sell.
     * @param ref Reference e.g. insider declaration and the type of sell.
     * @param permitInfo Information about the permit.
     * @return The base currency amount for the selling of the shares.
     */
    function sellSharesWithPermit(IBrokerbot brokerbot, IERC20Permit shares, address seller, address recipient, uint256 amountToSell, bytes calldata ref, PermitInfo calldata permitInfo) public onlySellerAndForwarder(seller) returns (uint256) {
        // Call permit to set allowance
        shares.permit(seller, address(this), amountToSell, permitInfo.deadline, permitInfo.v, permitInfo.r,permitInfo.s);
        // process sell
        if (permitInfo.exFee > 0){
            uint256 proceeds = _sellShares(brokerbot, shares, seller, address(this), amountToSell, ref);
            IERC20 currency = brokerbot.base();
            currency.safeTransfer(msg.sender, permitInfo.exFee);
            currency.safeTransfer(recipient, proceeds - permitInfo.exFee);
            return proceeds - permitInfo.exFee;
        } else {
            return _sellShares(brokerbot, shares, seller, recipient, amountToSell, ref);
        }
    }

    /**
     * @notice With this function a user can sell shares with permit and swap them to a desired token.
     * @param brokerbot The brokerbot of the shares to sell.
     * @param shares The (draggable)shares address.
     * @param seller The seller address.
     * @param amountToSell The amount of shares to sell.
     * @param ref Reference e.g. insider declaration and the type of sell.
     * @param permitInfo Information about the permit.
     * @param params Information about the swap.
     * @return The output amount of the swap to the desired token.
     */
    function sellSharesWithPermitAndSwap(IBrokerbot brokerbot, IERC20Permit shares, address seller,  uint256 amountToSell, bytes calldata ref, PermitInfo calldata permitInfo, ISwapRouter.ExactInputParams memory params, bool unwrapWeth) external onlySellerAndForwarder(seller) returns (uint256) {
        params.amountIn = sellSharesWithPermit(brokerbot, shares, seller, address(this), amountToSell, ref, permitInfo);
        return _swap(params, unwrapWeth);
    }

    /**
     * @notice With this function a user can sell shares and swap them to a desired token. The user has to approve the paymenthub before on the shares contract.
     * @param brokerbot The brokerbot of the shares to sell.
     * @param shares The (draggable)shares address.
     * @param amountToSell The amount of shares to sell.
     * @param ref Reference e.g. insider declaration and the type of sell.
     * @param params Information about the swap.
     * @return The output amount of the swap to the desired token.
     */
    function sellSharesAndSwap(IBrokerbot brokerbot, IERC20 shares, uint256 amountToSell,  bytes calldata ref, ISwapRouter.ExactInputParams memory params, bool unwrapWeth) external returns (uint256) {
        params.amountIn = _sellShares(brokerbot, shares, msg.sender, address(this), amountToSell, ref);
        return _swap(params, unwrapWeth);
    }

    /**
     * @notice Transfers shares to brokerbot and executes the selling.
     * @param brokerbot The brokerbot of the shares to sell.
     * @param shares The (draggable)shares address.
     * @param seller The seller address.
     * @param recipient The recipient of the base currency tokens. (this can be a 3rd party to off-ramp or the paymenthub itself if a swap will be done direct after)
     * @param amountToSell The amount of shares to sell.
     * @param ref Reference e.g. insider declaration and the type of sell.
     * @return The base currency amount for the selling of the shares.
     */ 
    function _sellShares(IBrokerbot brokerbot, IERC20 shares, address seller, address recipient, uint256 amountToSell, bytes calldata ref ) internal returns (uint256) {
        // send shares token to brokerbot
        shares.safeTransferFrom(seller, address(brokerbot), amountToSell);
        // process sell on brokerbot
        return brokerbot.processIncoming(shares, recipient, amountToSell, ref);
    }

    /**
     * @notice Swap (base currency) token according to given path and unwrap weth if needed.
     * @param params Information about the swap (includes path).
     * @return amountOut The output amount of the swap to the desired token.
     */
    function _swap(ISwapRouter.ExactInputParams memory params, bool unwrapWeth) internal returns(uint256 amountOut) {
        // if weth should be unwrapped, swap recipient is this contract and eth is send to seller
        if (unwrapWeth){
            address seller = params.recipient;
            params.recipient = address(this);
            amountOut = _swapToERC20(params);
            IWETH9(uniswapQuoter.WETH9()).withdraw(amountOut);
            (bool success, ) = payable(seller).call{value:amountOut}("");
            if (!success) revert PaymentHub_TransferFailed();
        } else {
            amountOut = _swapToERC20(params);
        }
    }

    /**
     * @notice Calls the Uniswap router to swap tokens according to given path.
     * @param params Information about the swap (includes path).
     * @return amountOut The output amount of the swap to the desired token.
     */
    function _swapToERC20(ISwapRouter.ExactInputParams memory params) internal returns(uint256 amountOut) {
        amountOut = uniswapRouter.exactInput(params);
        if (amountOut < params.amountOutMinimum){
            revert PaymentHub_SwapError(params.amountOutMinimum, amountOut);
        }
    }

    /**
     * Checks if the brokerbot has setting enabled to keep ether
     */
    function hasSettingKeepEther(IBrokerbot brokerbot) public view returns (bool) {
        return brokerbot.settings() & KEEP_ETHER == KEEP_ETHER;
    }

    /**
     * @notice In case tokens have been accidentally sent directly to this contract. Only Forwarder can withdraw, else a MEV bot will intercept it.
     * @param ercAddress The erc20 address.
     * @param to The address to transfer tokens to.
     * @param amount The amount of tokens to transfer.
     */
    function recover(IERC20 ercAddress, address to, uint256 amount) external onlyForwarder {
        ercAddress.safeTransfer(to, amount);
    }

    /**
     * @notice Transfer ether to a given address. Only Forwarder can withdraw, else a MEV bot will intercept it.
     * @param to The address to transfer ether to.
     */
    function withdrawEther(address to, uint256 amount) external onlyForwarder {
        (bool success, ) = payable(to).call{value:amount}("");
        if (!success) {
            revert PaymentHub_TransferFailed();
        }
    }

    /**
     * @notice Transfer ether to a given address.
     * @dev Used with the mutlisigwallet.
     * @param to The address to transfer ether to.
     */
    function transferEther(address to) external payable {
        (bool success, ) = payable(to).call{value:msg.value}("");
        if (!success) {
            revert PaymentHub_TransferFailed();
        }
    }

    // solhint-disable-next-line no-empty-blocks
    receive() external payable {
        // Important to receive ETH refund from Uniswap
    }
}

npm/@chainlink/[email protected]/src/v0.8/shared/interfaces/AggregatorV3Interface.sol

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

// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  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);
}

project/contracts/ERC20/IERC20.sol

/**
* SPDX-License-Identifier: MIT
*
* Copyright (c) 2016-2019 zOS Global Limited
*
*/
pragma solidity >=0.8.0 <0.9.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP. Does not include
 * the optional functions; to access them see `ERC20Detailed`.
 */

interface IERC20 {

    // Optional functions
    function name() external view returns (string memory);

    function symbol() external view returns (string memory);

    function decimals() external view returns (uint8);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a `Transfer` event.
     */
    function transfer(address recipient, uint256 amount) 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 `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * > 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a `Transfer` event.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /**
     * @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);

}

project/contracts/ERC20/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/draft-IERC20Permit.sol

pragma solidity >=0.8.0 <0.9.0;

import "./IERC20.sol";

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit is IERC20 {

    /*//////////////////////////////////////////////////////////////
                            Custom errors
	//////////////////////////////////////////////////////////////*/
    /// Block timestamp must to be before deadline.
    /// @param deadline The deadline of the permit.
    /// @param blockTimestamp The timestamp of the execution block.
    error Permit_DeadlineExpired(uint256 deadline, uint256 blockTimestamp);
    /// Recovered address must be owner and not zero address.
    /// @param signerAddress The recovered signer address.
    error Permit_InvalidSigner(address signerAddress);

    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

project/contracts/brokerbot/IBrokerbot.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;

import "../ERC20/IERC20.sol";
import "../ERC20/IERC20Permit.sol";

interface IBrokerbot {

	/*//////////////////////////////////////////////////////////////
                            Custom errors
  //////////////////////////////////////////////////////////////*/
  error Brokerbot_BuyingDisabled();
  error Brokerbot_SellingDisabled();
  /// Sender(msg.sender) has to be incoming token or paymenthub.
  /// @param sender The msg.sender.
  error Brokerbot_InvalidSender(address sender);
  /// target.call() wasn't successful.
  /// @param target The receiver of the Eth.
  /// @param amount The withdraw amount.
  error Brokerbot_WithdrawFailed(address target, uint256 amount);
  /// Sender(msg.sender) needs to be owner or paymenthub.
  /// @param sender The msg.sender.
  error Brokerbot_NotAuthorized(address sender);
  error Brokerbot_InsufficientPayment(uint256 required, uint256 provided);

  function paymenthub() external view returns (address);

  function base() external view returns (IERC20);

  function token() external view returns (IERC20Permit);
  
  function settings() external view returns (uint256);

  // @return The amount of shares bought on buying or how much in the base currency is transfered on selling
  function processIncoming(IERC20 token_, address from, uint256 amount, bytes calldata ref) external payable returns (uint256);

  function getBuyPrice(uint256 shares) external view returns (uint256);

  function getSellPrice(uint256 shares) external view returns (uint256);

}

project/contracts/brokerbot/IUniswapV3.sol

// SPDX-License-Identifier: MIT
// Copied from 
// https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/interfaces/IQuoter.sol
// https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/ISwapRouter.sol
pragma solidity >=0.8.0 <0.9.0;

import "../ERC20/IERC20.sol";

interface IQuoter {

    /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool
    /// @param tokenIn The token being swapped in
    /// @param tokenOut The token being swapped out
    /// @param fee The fee of the token pool to consider for the pair
    /// @param amountOut The desired output amount
    /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
    /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`
    function quoteExactOutputSingle(
        address tokenIn,
        address tokenOut,
        uint24 fee,
        uint256 amountOut,
        uint160 sqrtPriceLimitX96
    ) external returns (uint256 amountIn);

    /// @notice Returns the amount in required for a given exact output swap without executing the swap
    /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order
    /// @param amountOut The amount of the last token to receive
    /// @return amountIn The amount of first token required to be paid
    function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn);

    /// @notice Returns the amount out received for a given exact input swap without executing the swap
    /// @param path The path of the swap, i.e. each token pair and the pool fee
    /// @param amountIn The amount of the first token to swap
    /// @return amountOut The amount of the last token that would be received
    function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut);

    /// @notice Returns the amount out received for a given exact input but for a swap of a single pool
    /// @param tokenIn The token being swapped in
    /// @param tokenOut The token being swapped out
    /// @param fee The fee of the token pool to consider for the pair
    /// @param amountIn The desired input amount
    /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
    /// @return amountOut The amount of `tokenOut` that would be received
    function quoteExactInputSingle(
        address tokenIn,
        address tokenOut,
        uint24 fee,
        uint256 amountIn,
        uint160 sqrtPriceLimitX96
    ) external returns (uint256 amountOut);
    
    // solhint-disable-next-line func-name-mixedcase
    function WETH9() external view returns (address);
}

interface ISwapRouter {
    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);

    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);

    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
    
    function refundETH() external payable;
}

/// @title Interface for WETH9
interface IWETH9 is IERC20 {
    /// @notice Deposit ether to get wrapped ether
    function deposit() external payable;

    /// @notice Withdraw wrapped ether to get ether
    function withdraw(uint256) external;
}

project/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol
// and modified it.

pragma solidity >=0.8.0 <0.9.0;

library Address {

    /// @param target Target address to call the function on.
    error Address_NotTransferNorContract(address target);

    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.
        return account.code.length > 0;
    }
    
    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    function functionCallWithValue(address target, bytes memory data, uint256 weiValue) internal returns (bytes memory) {
        if (data.length != 0 && !isContract(target)) {
            revert Address_NotTransferNorContract(target);
        }
        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
        if (success) {
            return returndata;
        } else if (returndata.length > 0) {
            assembly{
                revert (add (returndata, 0x20), mload (returndata))
            }
        } else {
           revert("failed");
        }
    }
}

project/contracts/utils/Ownable.sol

// SPDX-License-Identifier: MIT
//
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
//
// Modifications:
// - Replaced Context._msgSender() with msg.sender
// - Made leaner
// - Extracted interface

pragma solidity >=0.8.0 <0.9.0;

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
contract Ownable {

    address public owner;

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

    error Ownable_NotOwner(address sender);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor (address initialOwner) {
        owner = initialOwner;
        emit OwnershipTransferred(address(0), owner);
    }

    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) external onlyOwner {
        emit OwnershipTransferred(owner, newOwner);
        owner = newOwner;
    }

    function _checkOwner() internal view {
        if (msg.sender != owner) {
            revert Ownable_NotOwner(msg.sender);
        }
    }
}

project/contracts/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// coppied and adjusted from OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity >=0.8.0 <0.9.0;

import {IERC20} from "../ERC20/IERC20.sol";
import {IERC20Permit} from "../ERC20/IERC20Permit.sol";
import {Address} from "./Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 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 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @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 Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        if (nonceAfter != nonceBefore + 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).
     */
    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);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            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 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;
    }
}
Настройки компилятораПоказать
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "project/:@chainlink/contracts/=npm/@chainlink/[email protected]/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.