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

EtherMindReserve

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

0 ETH

 

Транзакций

11

 

Компилятор

solc 0.8.24

 

Тот же код

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

 

Подробности

Компилятор
solc 0.8.24+commit.e11b9ed9
Язык
solidity
Оптимизация
Да, 200 прогонов
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 458 140
Транзакция создания
0x5964c50c7a…b1f8ffb91b

src/EtherMindReserve.sol

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

/// @title EtherMind Reserve
/// @notice An in-house swap venue: EtherMind holds a reserve of several tokens and is itself the
///         counterparty to every swap. No external DEX/aggregator is used. A user swaps one
///         listed token for another against the reserve, priced from Chainlink USD feeds plus a
///         spread. Combined with a one-time approval + the server's trade-only executor key, this
///         gives pop-up-free ("1-click") swaps for every listed token.
///
/// IMPORTANT — this makes the operator a market maker:
///  - You must fund the reserve with every token, and rebalance as inventory drifts.
///  - The spread + limits below protect the reserve from arbitrage, but do not remove inventory
///    risk. Size limits and the spread conservatively, and watch balances.
///  - Being the counterparty may be a regulated activity in your jurisdiction.
///
/// Safety built in:
///  - Only listed tokens, each with an 8-decimal Chainlink USD feed; stale/invalid price reverts.
///  - Output is always sent to `user`; there is no path that moves a user's funds elsewhere, so a
///    one-time (even unlimited) approval cannot be drained by a leaked executor key.
///  - Per-user per-trade and daily USD caps; a global per-trade cap; owner pause.
///  - The reserve only ever pays out tokens it already holds (inventory bounds every swap).
contract EtherMindReserve {
    struct Token {
        bool listed;
        uint8 decimals;
        address feed; // Chainlink <TOKEN>/USD, 8 decimals
    }

    struct Permission {
        uint64 maxTradeUsd; // 6 decimals (index 0)
        uint64 dailyLimitUsd; // 6 decimals (index 1)
        uint40 expiry; // (index 2)
        uint64 spentToday; // (index 3)
        uint40 day; // (index 4)
    }

    // Max age of a Chainlink answer before it's rejected. Owner-settable because feeds differ a
    // lot: ETH/USD updates ~hourly, but stablecoin feeds (USDC/USD, DAI/USD) only ~daily (24h
    // heartbeat). The default covers a 24h-heartbeat feed plus margin; tune per your listed feeds.
    uint256 public oracleMaxAge = 26 hours;
    uint16 public constant MAX_SPREAD_BPS = 500; // 5% hard ceiling on the owner-set spread

    address public owner;
    address public executor; // server trade-only key (swaps on behalf of users)
    bool public paused;
    uint16 public spreadBps = 30; // 0.30% default: the reserve keeps this on every swap
    uint64 public globalMaxTradeUsd = 25_000_000000; // 25,000 USD hard cap per swap (6 decimals)

    mapping(address => Token) public tokens;
    mapping(address => Permission) public permissions;
    uint256 private _lock = 1;

    event TokenListed(address indexed token, address feed, uint8 decimals);
    event TokenDelisted(address indexed token);
    event Swapped(address indexed user, address indexed tokenIn, address indexed tokenOut, uint256 amountIn, uint256 amountOut, uint256 usdValue);
    event Authorized(address indexed user, uint64 maxTradeUsd, uint64 dailyLimitUsd, uint40 expiry);
    event Revoked(address indexed user);
    event Deposited(address indexed token, uint256 amount);
    event Withdrawn(address indexed token, uint256 amount, address to);
    event ExecutorSet(address executor);
    event PausedSet(bool paused);
    event SpreadSet(uint16 bps);
    event GlobalMaxSet(uint64 usd);
    event OracleMaxAgeSet(uint256 seconds_);
    event OwnershipTransferred(address owner);

    error NotOwner();
    error NotExecutor();
    error IsPaused();
    error NotListed();
    error SameToken();
    error NotAuthorized();
    error TradeTooLarge();
    error DailyLimit();
    error BadAmount();
    error BadParam();
    error BadOracle();
    error Slippage();
    error ShortReserve();
    error TransferFailed();
    error Reentrant();

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

    modifier nonReentrant() {
        if (_lock != 1) revert Reentrant();
        _lock = 2;
        _;
        _lock = 1;
    }

    constructor(address executor_) {
        if (executor_ == address(0)) revert BadParam();
        owner = msg.sender;
        executor = executor_;
        emit OwnershipTransferred(msg.sender);
        emit ExecutorSet(executor_);
    }

    // ------------------------------------------------------------------ user
    /// @notice Allow the AI/server to swap on your behalf within these limits (one-time). The
    ///         contract can only ever swap your listed tokens and return the result to you.
    function authorize(uint64 maxTradeUsd, uint64 dailyLimitUsd, uint40 expiry) external {
        if (maxTradeUsd == 0 || dailyLimitUsd == 0 || expiry <= block.timestamp) revert BadParam();
        Permission storage p = permissions[msg.sender];
        p.maxTradeUsd = maxTradeUsd;
        p.dailyLimitUsd = dailyLimitUsd;
        p.expiry = expiry;
        emit Authorized(msg.sender, maxTradeUsd, dailyLimitUsd, expiry);
    }

    function revoke() external {
        delete permissions[msg.sender];
        emit Revoked(msg.sender);
    }

    // ------------------------------------------------------------------ swap
    /// @param user     the account whose tokens are swapped and who receives the output
    /// @param minOut   the caller's own minimum acceptable output
    /// @dev Callable by the executor (no user signature; uses the user's approval) or by the user.
    function swap(address user, address tokenIn, address tokenOut, uint256 amountIn, uint256 minOut)
        external
        nonReentrant
        returns (uint256 amountOut)
    {
        if (msg.sender != executor && msg.sender != user) revert NotExecutor();
        if (paused) revert IsPaused();
        if (amountIn == 0) revert BadAmount();
        if (tokenIn == tokenOut) revert SameToken();
        Token memory tin = tokens[tokenIn];
        Token memory tout = tokens[tokenOut];
        if (!tin.listed || !tout.listed) revert NotListed();

        uint256 priceIn = price(tin.feed);
        uint256 priceOut = price(tout.feed);

        // USD value of the input (6 decimals), checked against the limits.
        uint256 usdValue = (_wad(amountIn, tin.decimals) * priceIn) / 1e20; // 1e18 * 1e8 / 1e20 = 1e6
        if (usdValue == 0) revert BadAmount();
        if (usdValue > globalMaxTradeUsd) revert TradeTooLarge();

        Permission storage p = permissions[user];
        if (p.expiry <= block.timestamp) revert NotAuthorized();
        if (usdValue > p.maxTradeUsd) revert TradeTooLarge();
        uint40 today = uint40(block.timestamp / 1 days);
        if (p.day != today) {
            p.day = today;
            p.spentToday = 0;
        }
        if (uint256(p.spentToday) + usdValue > p.dailyLimitUsd) revert DailyLimit();
        p.spentToday += uint64(usdValue);

        // amountOut in tokenOut units, minus the spread the reserve keeps.
        uint256 outWad = (_wad(amountIn, tin.decimals) * priceIn) / priceOut; // token-count, 1e18
        amountOut = (_unwad(outWad, tout.decimals) * (10_000 - spreadBps)) / 10_000;
        if (amountOut < minOut || amountOut == 0) revert Slippage();
        if (_balance(tokenOut) < amountOut) revert ShortReserve();

        _transferFrom(tokenIn, user, address(this), amountIn);
        _transfer(tokenOut, user, amountOut);
        emit Swapped(user, tokenIn, tokenOut, amountIn, amountOut, usdValue);
    }

    // ------------------------------------------------------------------ views
    /// @notice Preview the output for a swap (after spread), without limits/inventory checks.
    function quote(address tokenIn, address tokenOut, uint256 amountIn) external view returns (uint256) {
        Token memory tin = tokens[tokenIn];
        Token memory tout = tokens[tokenOut];
        if (!tin.listed || !tout.listed || tokenIn == tokenOut || amountIn == 0) return 0;
        uint256 outWad = (_wad(amountIn, tin.decimals) * price(tin.feed)) / price(tout.feed);
        return (_unwad(outWad, tout.decimals) * (10_000 - spreadBps)) / 10_000;
    }

    function reserveOf(address token) external view returns (uint256) {
        return _balance(token);
    }

    function remainingToday(address user) external view returns (uint256) {
        Permission storage p = permissions[user];
        if (p.expiry <= block.timestamp) return 0;
        uint256 spent = (p.day == uint40(block.timestamp / 1 days)) ? p.spentToday : 0;
        return p.dailyLimitUsd > spent ? p.dailyLimitUsd - spent : 0;
    }

    function price(address feed) public view returns (uint256) {
        (bool ok, bytes memory ret) = feed.staticcall(abi.encodeWithSignature("latestRoundData()"));
        if (!ok || ret.length < 160) revert BadOracle();
        (uint80 roundId, int256 answer,, uint256 updatedAt, uint80 answeredInRound) =
            abi.decode(ret, (uint80, int256, uint256, uint256, uint80));
        if (answer <= 0 || updatedAt == 0 || answeredInRound < roundId) revert BadOracle();
        if (block.timestamp - updatedAt > oracleMaxAge) revert BadOracle();
        return uint256(answer);
    }

    // ------------------------------------------------------------------ owner: tokens & reserve
    function listToken(address token, address feed) external onlyOwner {
        if (token == address(0) || feed == address(0)) revert BadParam();
        (bool fok, bytes memory fret) = feed.staticcall(abi.encodeWithSignature("decimals()"));
        if (!fok || fret.length < 32 || abi.decode(fret, (uint8)) != 8) revert BadOracle();
        (bool tok, bytes memory tret) = token.staticcall(abi.encodeWithSignature("decimals()"));
        if (!tok || tret.length < 32) revert BadParam();
        uint8 dec = abi.decode(tret, (uint8));
        tokens[token] = Token({listed: true, decimals: dec, feed: feed});
        emit TokenListed(token, feed, dec);
    }

    function delistToken(address token) external onlyOwner {
        delete tokens[token];
        emit TokenDelisted(token);
    }

    /// @notice Fund the reserve. (You can also just transfer tokens to this contract.)
    function deposit(address token, uint256 amount) external onlyOwner {
        _transferFrom(token, msg.sender, address(this), amount);
        emit Deposited(token, amount);
    }

    /// @notice Withdraw from the reserve to rebalance or remove liquidity.
    function withdraw(address token, uint256 amount, address to) external onlyOwner {
        if (to == address(0)) revert BadParam();
        _transfer(token, to, amount);
        emit Withdrawn(token, amount, to);
    }

    // ------------------------------------------------------------------ owner: config
    function setExecutor(address executor_) external onlyOwner {
        if (executor_ == address(0)) revert BadParam();
        executor = executor_;
        emit ExecutorSet(executor_);
    }

    function setPaused(bool paused_) external onlyOwner {
        paused = paused_;
        emit PausedSet(paused_);
    }

    function setSpreadBps(uint16 bps) external onlyOwner {
        if (bps > MAX_SPREAD_BPS) revert BadParam();
        spreadBps = bps;
        emit SpreadSet(bps);
    }

    function setGlobalMaxTradeUsd(uint64 usd) external onlyOwner {
        if (usd == 0) revert BadParam();
        globalMaxTradeUsd = usd;
        emit GlobalMaxSet(usd);
    }

    /// @notice Max age of a Chainlink answer before swaps reject it. Set it to cover the slowest
    /// heartbeat among your listed feeds (stablecoin USD feeds are typically 24h). Min 5 minutes.
    function setOracleMaxAge(uint256 seconds_) external onlyOwner {
        if (seconds_ < 5 minutes) revert BadParam();
        oracleMaxAge = seconds_;
        emit OracleMaxAgeSet(seconds_);
    }

    function transferOwnership(address owner_) external onlyOwner {
        if (owner_ == address(0)) revert BadParam();
        owner = owner_;
        emit OwnershipTransferred(owner_);
    }

    // ------------------------------------------------------------------ internal
    function _wad(uint256 amount, uint8 decimals) private pure returns (uint256) {
        return decimals == 18 ? amount : (decimals < 18 ? amount * (10 ** (18 - decimals)) : amount / (10 ** (decimals - 18)));
    }

    function _unwad(uint256 wad, uint8 decimals) private pure returns (uint256) {
        return decimals == 18 ? wad : (decimals < 18 ? wad / (10 ** (18 - decimals)) : wad * (10 ** (decimals - 18)));
    }

    function _balance(address token) private view returns (uint256) {
        (bool ok, bytes memory ret) = token.staticcall(abi.encodeWithSelector(0x70a08231, address(this)));
        if (!ok || ret.length < 32) revert TransferFailed();
        return abi.decode(ret, (uint256));
    }

    function _transfer(address token, address to, uint256 amount) private {
        (bool ok, bytes memory ret) = token.call(abi.encodeWithSelector(0xa9059cbb, to, amount));
        if (!ok || (ret.length != 0 && !abi.decode(ret, (bool)))) revert TransferFailed();
    }

    function _transferFrom(address token, address from, address to, uint256 amount) private {
        (bool ok, bytes memory ret) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, amount));
        if (!ok || (ret.length != 0 && !abi.decode(ret, (bool)))) revert TransferFailed();
    }
}
Настройки компилятораПоказать
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": [
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "forge-std/=lib /forge-std/src/",
    "forge-std/=lib/forge-std/src/"
  ]
}

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

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