Skip to content
Verified contractExactMIT

SignedOracle

Address0xff47ac101b51332a0549d07406741083fbc09d3f
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,343,725
Creation transaction
0x915ae9b17a…6f1b19b614

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

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

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
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.