Skip to content
Verified contractExactMIT

ExecutionOracle

Address0x55ff6bff62daa08fe4861b0b9e1d2e2e256498fe
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 1 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,218,880
Creation transaction
0x62ca2877b8…52d3375083

src/ExecutionOracle.sol

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

import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {SignedOracle} from "./SignedOracle.sol";

/// @notice Signed market prints plus execution prices bound to one exact trader-signed order.
/// @dev The signer remains trusted for price accuracy and prompt, single-price execution. It must
///      persist the first execution quote for an order before releasing it, and must never sign a
///      second price for that order. Binding a quote to its full EIP-712 order digest prevents a
///      trader or operator from substituting an ordinary historical print or another order's quote.
///      No fixed pricing delay is imposed. Public prints still support liquidations and direct exits.
contract ExecutionOracle is SignedOracle {
    bytes32 public constant FILL_TYPEHASH = keccak256(
        "Fill(bytes32 feedId,bytes32 orderId,uint64 price,uint64 conf,uint64 publishTime,uint64 observedAt)"
    );
    uint256 private constant FILL_LENGTH = 288;
    bytes32 public constant TICK_TYPEHASH = keccak256(
        "Tick(bytes32 feedId,uint64 price,uint64 conf,uint64 publishTime,uint64 prevPublishTime,uint64 observedAt,uint64 prevObservedAt)"
    );

    constructor(address exchange_, address signer_) SignedOracle(exchange_, signer_) {}

    /// @notice Fixed wallet-signature validation, including ERC-1271 wallets. Kept here so the
    ///         Exchange's runtime remains within Ethereum's code-size limit. No signer setting
    ///         participates in this check: only the owner's actual wallet can authorize it.
    function checkWalletSignature(address owner, bytes32 digest, bytes calldata signature)
        external
        view
        returns (bool)
    {
        return SignatureChecker.isValidSignatureNow(owner, digest, signature);
    }

    /// @notice An execution price signed for this feed and this complete order digest.
    /// @dev `observedAt` is the source observation in milliseconds; public position times remain
    ///      seconds. The operator cannot turn a normal signed market print into an execution quote.
    function fill(bytes32 feedId, bytes32 orderId, bytes[] calldata update, uint64 minTime, uint64 maxTime)
        external
        view
        returns (uint64 price, uint64 conf, uint64 publishTime, uint64 observedAt)
    {
        if (update.length != 1 || update[0].length != FILL_LENGTH) revert BadUpdate();
        bytes32 feed;
        bytes32 order;
        uint8 v;
        bytes32 r;
        bytes32 s;
        (feed, order, price, conf, publishTime, observedAt, v, r, s) =
            abi.decode(update[0], (bytes32, bytes32, uint64, uint64, uint64, uint64, uint8, bytes32, bytes32));
        if (feed != feedId || order != orderId || orderId == bytes32(0)) revert NoPriceInWindow();
        if (price == 0) revert NonPositivePrice();
        if (publishTime < minTime || publishTime > maxTime || observedAt / 1000 != publishTime) {
            revert NoPriceInWindow();
        }
        bytes32 digest = keccak256(
            abi.encodePacked(
                "\x19\x01",
                domainSeparator(),
                keccak256(abi.encode(FILL_TYPEHASH, feed, order, price, conf, publishTime, observedAt))
            )
        );
        (address recovered, ECDSA.RecoverError error,) = ECDSA.tryRecover(digest, v, r, s);
        if (error != ECDSA.RecoverError.NoError || recovered != signer) revert BadSignature();
    }

    /// @notice Public tick with millisecond ordering, for proving a post-entry bust or trigger.
    function afterMs(bytes32 feedId, bytes[] calldata update, uint64 afterTime)
        external
        view
        returns (uint64 price, uint64 conf, uint64 publishTime, uint64 observedAt)
    {
        (price, conf, publishTime,, observedAt) = _tick(feedId, update);
        if (observedAt <= afterTime) revert NoPriceInWindow();
    }

    function read(bytes32 feedId, bytes[] calldata update)
        public
        view
        override
        returns (uint64 price, uint64 conf, uint64 publishTime, uint64 prevPublishTime)
    {
        (price, conf, publishTime, prevPublishTime,) = _tick(feedId, update);
    }

    function _tick(bytes32 feedId, bytes[] calldata update)
        private
        view
        returns (uint64 price, uint64 conf, uint64 publishTime, uint64 prevPublishTime, uint64 observedAt)
    {
        if (update.length != 1 || update[0].length != 320) revert BadUpdate();
        bytes32 feed;
        uint64 prevObservedAt;
        uint8 v;
        bytes32 r;
        bytes32 s;
        (feed, price, conf, publishTime, prevPublishTime, observedAt, prevObservedAt, v, r, s) = abi.decode(
            update[0], (bytes32, uint64, uint64, uint64, uint64, uint64, uint64, uint8, bytes32, bytes32)
        );
        if (feed != feedId) revert NoPriceInWindow();
        if (price == 0) revert NonPositivePrice();
        if (
            observedAt / 1000 != publishTime || prevObservedAt / 1000 != prevPublishTime
                || prevObservedAt >= observedAt
        ) revert BadUpdate();
        bytes32 digest = keccak256(
            abi.encodePacked(
                "\x19\x01",
                domainSeparator(),
                keccak256(abi.encode(TICK_TYPEHASH, feed, price, conf, publishTime, prevPublishTime, observedAt, prevObservedAt))
            )
        );
        (address recovered, ECDSA.RecoverError error,) = ECDSA.tryRecover(digest, v, r, s);
        if (error != ECDSA.RecoverError.NoError || recovered != signer) revert BadSignature();
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with _data
     */
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}

lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(
        bytes32 hash,
        bytes memory signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly ("memory-safe") {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/SignatureChecker.sol)

pragma solidity ^0.8.20;

import {ECDSA} from "./ECDSA.sol";
import {IERC1271} from "../../interfaces/IERC1271.sol";

/**
 * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
 * signatures from externally owned accounts (EOAs) as well as ERC-1271 signatures from smart contract wallets like
 * Argent and Safe Wallet (previously Gnosis Safe).
 */
library SignatureChecker {
    /**
     * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
     * signature is validated against that smart contract using ERC-1271, otherwise it's validated using `ECDSA.recover`.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
        if (signer.code.length == 0) {
            (address recovered, ECDSA.RecoverError err, ) = ECDSA.tryRecover(hash, signature);
            return err == ECDSA.RecoverError.NoError && recovered == signer;
        } else {
            return isValidERC1271SignatureNow(signer, hash, signature);
        }
    }

    /**
     * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
     * against the signer smart contract using ERC-1271.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidERC1271SignatureNow(
        address signer,
        bytes32 hash,
        bytes memory signature
    ) internal view returns (bool) {
        (bool success, bytes memory result) = signer.staticcall(
            abi.encodeCall(IERC1271.isValidSignature, (hash, signature))
        );
        return (success &&
            result.length >= 32 &&
            abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
    }
}

src/SignedOracle.sol

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

import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

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

/// @dev As much of the Exchange as this oracle asks of it.
interface IOwned {
    function owner() external view returns (address);
}

/// @title SignedOracle
/// @notice A price source for the Exchange whose prices are signed by one key: the price signer.
/// @dev The signer reads a market's price off-chain (at launch, Hyperliquid's order book through
///      its public API) and signs it, one print after another. This contract checks the signature
///      and the Exchange's two questions, and nothing else.
///
///      What that means, plainly: THE SIGNER IS TRUSTED. Whoever holds its key decides every fill,
///      every close and every bust. Nothing on-chain can tell a true price from a false one. The
///      key is kept apart from the operator's (it never sends a transaction and needs no ETH) and
///      the Exchange's owner can replace it at once (`setSigner`), which is the only remedy if it
///      leaks.
///
///      What is still enforced on-chain:
///      1. A print is for one feed, on one chain, for this contract: it cannot be replayed for
///         another market, on a fork, or against another deployment (EIP-712).
///      2. Each print names the publish time of the print before it. `pinned` takes only the
///         FIRST print at or after a second, so a trade signed for second T has one price, and
///         the operator who submits it cannot pick among the signer's prints.
///
///      A print is `abi.encode(feedId, price, conf, publishTime, prevPublishTime, v, r, s)`: the
///      price and its uncertainty scaled to 1e8, both times in unix seconds.
///
///      The contract holds no funds and has no owner of its own: its one setting follows the
///      Exchange's owner, so handing the Exchange over hands this over with it.
contract SignedOracle is IOracle {
    bytes32 private constant DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 private constant NAME_HASH = keccak256("SignedOracle");
    bytes32 private constant VERSION_HASH = keccak256("1");
    /// @notice The EIP-712 type the signer signs.
    bytes32 public constant PRINT_TYPEHASH =
        keccak256("Print(bytes32 feedId,uint64 price,uint64 conf,uint64 publishTime,uint64 prevPublishTime)");
    /// @dev Eight words: the feed, four numbers and a signature.
    uint256 private constant PRINT_LENGTH = 256;

    /// @notice The Exchange this prices for. Its owner is the one who may change the signer.
    address public immutable exchange;
    /// @notice The key whose prints are prices.
    address public signer;

    event SignerSet(address indexed signer);

    error ZeroAddress();
    error NotOwner();
    error BadUpdate();
    error BadSignature();
    error NonPositivePrice();
    error NoPriceInWindow();

    constructor(address exchange_, address signer_) {
        if (exchange_ == address(0) || signer_ == address(0)) revert ZeroAddress();
        exchange = exchange_;
        signer = signer_;
        emit SignerSet(signer_);
    }

    /// @notice Replaces the price signer. Every print the old key signed stops counting at once.
    function setSigner(address signer_) external {
        if (msg.sender != IOwned(exchange).owner()) revert NotOwner();
        if (signer_ == address(0)) revert ZeroAddress();
        signer = signer_;
        emit SignerSet(signer_);
    }

    /// @inheritdoc IOracle
    function pinned(bytes32 feedId, bytes[] calldata update, uint64 minTime, uint64 maxTime)
        external
        view
        override
        returns (uint64 price, uint64 conf, uint64 publishTime)
    {
        uint64 prevPublishTime;
        (price, conf, publishTime, prevPublishTime) = read(feedId, update);
        // The first print at or after `minTime`: the one before it was published earlier.
        if (prevPublishTime >= minTime || publishTime < minTime || publishTime > maxTime) revert NoPriceInWindow();
    }

    /// @inheritdoc IOracle
    function within(bytes32 feedId, bytes[] calldata update, uint64 minTime, uint64 maxTime)
        external
        view
        override
        returns (uint64 price, uint64 conf, uint64 publishTime)
    {
        (price, conf, publishTime,) = read(feedId, update);
        if (publishTime < minTime || publishTime > maxTime) revert NoPriceInWindow();
    }

    /// @notice The print in `update`, if it is for `feedId` and the signer signed it. Reverts
    ///         otherwise.
    function read(bytes32 feedId, bytes[] calldata update)
        public
        view
        virtual
        returns (uint64 price, uint64 conf, uint64 publishTime, uint64 prevPublishTime)
    {
        if (update.length != 1 || update[0].length != PRINT_LENGTH) revert BadUpdate();
        bytes32 feed;
        uint8 v;
        bytes32 r;
        bytes32 s;
        (feed, price, conf, publishTime, prevPublishTime, v, r, s) =
            abi.decode(update[0], (bytes32, uint64, uint64, uint64, uint64, uint8, bytes32, bytes32));
        // A print for another market is no price for this one.
        if (feed != feedId) revert NoPriceInWindow();
        if (price == 0) revert NonPositivePrice();
        // A print cannot come before the one it follows.
        if (prevPublishTime > publishTime) revert BadUpdate();

        bytes32 digest = keccak256(
            abi.encodePacked(
                "\x19\x01",
                domainSeparator(),
                keccak256(abi.encode(PRINT_TYPEHASH, feedId, price, conf, publishTime, prevPublishTime))
            )
        );
        // Rejects a malformed signature and the second form of a valid one.
        (address recovered, ECDSA.RecoverError error,) = ECDSA.tryRecover(digest, v, r, s);
        if (error != ECDSA.RecoverError.NoError || recovered != signer) revert BadSignature();
    }

    /// @notice The EIP-712 domain prints are signed under: this contract, on this chain.
    function domainSeparator() public view returns (bytes32) {
        return keccak256(abi.encode(DOMAIN_TYPEHASH, NAME_HASH, VERSION_HASH, block.chainid, address(this)));
    }
}

src/interfaces/IOracle.sol

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

/// @notice Price source for the Exchange. Every price is scaled to 1e8.
interface IOracle {
    /// @notice The FIRST price published at or after `minTime` (and no later than `maxTime`).
    ///         Deterministic: for a given feed and `minTime` there is exactly one answer.
    function pinned(bytes32 feedId, bytes[] calldata update, uint64 minTime, uint64 maxTime)
        external
        returns (uint64 price, uint64 conf, uint64 publishTime);

    /// @notice Any price published inside `[minTime, maxTime]`. Used to prove a price was touched.
    function within(bytes32 feedId, bytes[] calldata update, uint64 minTime, uint64 maxTime)
        external
        returns (uint64 price, uint64 conf, uint64 publishTime);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1,
    "details": {
      "yulDetails": {
        "optimizerSteps": "dhfoDgvulfnTUtnIf[xa[r]EscLMcCTUtTOntnfDIulLculVcul[j]Tpeulxa[rul]xa[r]cLgvifCTUca[r]LSsTFOtfDnca[r]Iulc]jmul[jul]VcTOculjmul:fDnTOcmu"
      }
    },
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.