ParadigmFoundation / zaidan-dealer-specification

Specification document's and scripts for the Zaidan Dealer JSONRPC specification.
Apache License 2.0
6 stars 3 forks source link

Notice: in development

This section will be removed when the public interface has stabilized.

Dealer JSONRPC v1.0

Definitions and specification for the Dealer JSONRPC (2.0) API. This document specifies the first public Dealer JSONRPC version, v1.0.

Methods under the dealer namespace (with the dealer_ prefix) comprise the public dealer API. Implementations MAY provide private administrative functionality through methods under a distinct namespace.

Methods under the feed namespace (with the feed_ prefix) specify an alternative/additional interaction model for trading with dealer implementations, and MAY be omitted by implementers.

The Dealer JSONRPC can be served over WebSockets, HTTP POST, or HTTP GET, or other transports at the discretion of implementers (see notes).

Be sure to see important notes and resources in the appendix.

Conventions

Contents

Requirements

In addition to notices in each section, each of the following must be true in order for an implementation to be considered in adherence with the specification.

These requirements are intended to motivate strong guarantees of compatibility between clients and servers and ensure maximum levels of safety for the operators of each: traders and dealers that implement this API.

Encoding

Quotes

Dealer implementations use the 0x contract system for asset settlement, and as such, the trading interface provided by the Dealer API is designed to foster helpful abstractions over the underlying settlement system.

For this reason, instead of providing a currency pair (base/quote and price denominated markets) interface for quote requests, traders are able to specify the makerAsset, takerAsset, and one of either makerAssetSize or takerAssetSize (the other is provided by the dealer as the quote). Price can then be calculated in terms of either asset at higher levels depending on the use case. Similarly, all asset sizes included in requests and responses from the dealer MUST be in integer base units.

Because there is no concept of a base or quote asset, quotes include no notion of price. Instead allowing clients to calculate the price in terms of either asset.

Implementations MAY choose what types of markets to support, to replicate more conventional trading systems.

In the example below, the mainnet (chain ID 1) address for the following assets are used:

Consider the following requests (syntax: [ MAKER_ASSET, TAKER_ASSET, MAKER_SIZE, TAKER_SIZE ]).

[
    [
        "0x6b175474e89094c44da98b954eedeac495271d0f",
        "0xe41d2489571d322189246dafa5ebde1f4699f498",
        null,
        "100000000000000000000"
    ],
    [
        "0xe41d2489571d322189246dafa5ebde1f4699f498",
        "0x6b175474e89094c44da98b954eedeac495271d0f",
        "100000000000000000000",
        null
    ],
    [
        "0xe41d2489571d322189246dafa5ebde1f4699f498",
        "0x6b175474e89094c44da98b954eedeac495271d0f",
        null,
        "10000000000000000000"
    ],
    [
        "0x6b175474e89094c44da98b954eedeac495271d0f",
        "0xe41d2489571d322189246dafa5ebde1f4699f498",
        "10000000000000000000",
        null
    ]
]
  1. Client requests to swap 100 ZRX for DAI (receiving the DAI, sending the ZRX)
    • If the market's quote asset is DAI this is a request to sell ZRX to the dealer.
    • If the market's quote asset is ZRX this is a request to buy DAI from the dealer.
  2. Client requests to swap 100 ZRX for DAI (receiving the ZRX, sending the DAI)
    • If the market's quote asset is DAI this is a request to buy ZRX from the dealer.
    • If the market's quote asset is ZRX this is a request to sell DAI to the dealer.
  3. Client requests to swap 10 DAI for ZRX (receiving the ZRX, sending the DAI)
    • If the market's quote asset is DAI this is a request to buy ZRX to the dealer.
    • If the market's quote asset is ZRX this is a request to sell DAI to the dealer.
  4. Client requests to swap 10 DAI for ZRX (receiving the DAI, sending the ZRX)
    • If the market's quote asset is DAI this is a request to sell ZRX to the dealer.
    • If the market's quote asset is ZRX this is a request to buy DAI from the dealer.

Quote feeds

Supplemental to the standard quote request mechanism described in this spec (dealer_getQuote), implementations MAY also provide a public "quote feed" subscription mechanism.

A quote feed provides a subscription to "quote stubs" for a given set of markets, where a stub indicates an available quantity of the maker or taker asset, and provides a range of prices between which a quote solicited by the a trader will lie. In other words, each stub represents a soft price commitment by a dealer implementation to a specific quantity of an asset. See the quote stub schema, the subscription method, and the method used to fetch a quote for a given stub. Conceptually, the quote feed can be considered a limit order book with soft price bounds.

Quote feeds provide takers an additional means for takers to gather price information from a dealer. Notably, the quote feed allows a taker to remain anonymous during the dealer's initial price setting process. More formally, the quote feed provides quote stubs that represent upper and lower cost limits for a specific quantity of an asset. In the context of an order book, these cost limits could be considered bounded price levels.

When a potential taker fetches a quote corresponding to particular quote stub, they will receive an exact cost/price for the trade size specified by the taker (in units of either the maker asset or the taker asset). This value will fall somewhere in the range defined in the quote stub. The value's positioning in the range will depend on a taker's specific relationship to the dealer. Thus, this scheme also provides takers an additional metric on which to evaluate a dealer.

In addition to providing direct subscription to a quote feed via the feed_subscribe, dealers MAY choose to post quote stubs (either all, or a subset) to arbitrary venues. This includes IPFS, a conventional DB/REST API, or perhaps eventually, a peer-to-peer liquidity sharing network such as 0x Mesh (arbitrary messages are not current supported by mesh).

The number of quote stubs alive at a current time SHOULD be equal to:

(# of quote stubs) = 2 * (# of quantity levels per pair) * (# of pairs)

Note: (# of pairs) for dealers that support arbitrary swap functionality is equal to n * (n - 1) where n is the number of supported assets. For dealers that only support markets between unique base assets and a standard quote currency (# of pairs) is equal to n.

Pagination

Paginated methods MUST implement pagination in accordance with this section. If page is not specified, the default MUST be 0. The value for perPage MAY be implementation specific.

Paginated methods MUST include two additional parameters in the params array (where n is the number of request parameters). The response parameters MUST match the table below.

Errors

Implementations MUST support the reserved error codes specified in the JSONRPC 2.0 specification, in addition to any method-specific errors. Be sure to see the error codes appendix.

Implementations MAY omit specific error codes (in the -42000 range) entirely, but MUST support the ones specified by JSONRPC if no specific codes are provided.

Implementations MAY add their own error codes and messages, and may use the data field provided by the JSONRPC specification.

Implementations MUST only adhere to the defined codes for the defined scenarios. The exact message text MAY not match the specification exactly, and implementations MAY omit certain specified codes.

Implementations MUST NOT used any defined error code to mean something contrary to what the specification defines.

Dealer methods

Method: dealer_authStatus

Get dealer-specific authorization status for a given taker address.

If the dealer is operating a blacklist or whitelist, this endpoint can inform the client why (or why not) they are able to trade.

Implementation MAY use arbitrary mechanisms to determine a taker's authorization, or place no restriction upon takers.

Method: dealer_getMarkets

Fetch information about currently supported markets. This method is paginated.

This method, with no parameters, MUST return a paginated array of all supported markets.

All parameters to this method (with the exception of page and perPage) act as filter parameters, returning only results that match all specified parameters.

Implementations MUST return an empty array for records if no results match the query.

Implementations MAY return an error (e.g. -42002) if conflicting query parameters are provided.

Method: dealer_getQuote

Primary method for requesting a quote from the dealer. Be sure to see the quotes section.

To request a quote, a client MUST specify the maker and taker asset (by address) and either a maker size or a taker size (but not both).

Implementations SHOULD NOT allow traders to specify both the maker and taker asset sizes, as this is highly illogical in most scenarios, and would amount to the trader setting the price.

Implementations MAY choose to support arbitrary swap quotes or simply return the corresponding error code (-42008 or -42009) if the quote requested by the trader is unsupported.

Clients SHOULD leave at least one size field (either makerAssetSize or takerAssetSize) as null or not specified that the dealer will fill-in to provide the price quote.

Method: dealer_submitFill

Submit a previously-fetched quote for settlement. Can be thought of as a "request-to-fill" a quote by a trader.

This method MUST support executing the signed 0x fill transaction from the client, according to ZEIP-18.

Implementations MAY use the validityParameters from previously-submitted quotes to reject fills based on external parameters.

The order or 0x fill transaction data, associated hash, and the original quote/order MAY be stored by implementations and associated with the quote ID so the data received by the client can be additionally verified prior to submitting for execution.

Method: dealer_time

Fetch the current time from the dealer server as a UNIX timestamp (in milliseconds).

Optionally provide a time in the request (clientTime) to get the difference (useful for clock synchronization and estimating network latency).

Feed methods

Method: feed_subscribe

Allows the caller to subscribe to a feed of quote stubs for a set of maker and taker asset denominated markets for live-updating offers in the form of QuoteStub and StubUpdate messages.

If no parameters after are provided, the subscription MUST include quote stubs for all markets that support quote feeds. Upon creation of a new subscription, a snapshot is provided to the subscriber of all active stubs that match their query filter. Subsequent messages sent in the subscription MUST contain only new stubs, and updates to existing stubs (including cancellations).

To subscribe to multiple markets with different maker and taker assets, multiple subscriptions SHOULD be used.

Method: feed_getQuoteFromStub

Fetch a full quote and signed 0x order for a given quote stub (see feed_subscribe).

To request a quote from a stub, either the makerSize or the takerSize MUST be included. Dealer implementations SHOULD allow traders to request a quote by specifying either the makerSize or the takerSize, filling in the value omitted in the request to create the price.

Method: feed_unsubscribe

Terminate an open feed subscription, identified by the subscription UUID provided when the subscription was created.

Schemas

Schematics and data structures used in the public API (JSON shown).

Fields indicated Yes in the Required column for each scheme MUST be implemented, while fields indicated No MAY be omitted.

All schemas in this section MUST be supported to the degree indicated in each section if required to implement a required method.

Schema: Time

All times are specified in milliseconds since the UNIX epoch as an integer Number.

Implementations MUST represent timestamps as whole integer numbers of milliseconds, without further decimal precision.

Note: the one exception is the expirationTimeSeconds field in 0x orders which are UNIX seconds and represented as a String.

Schema: UUID

A universally unique identifier (UUID), according to UUID version 4.0 as a String.

Schema: TradeInfo

Defines information about trades – settlement transactions sent to the 0x exchange contract.

Implementations MAY include implementation-specific fields in this section.

The value for gasPrice MUST match the value ultimately included in any 0x fill transaction by dealer implementations for a given market.

Schema: QuoteInfo

Defines information about quote parameters for a given market. Does NOT included specific validity parameters (ValidityParameter) generated for individual quotes.

Schema: ValidityParameter

An implementation-specific quote validation parameter used to enforce "soft cancels" (rejection to fill quotes).

These parameters are NOT cryptographically enforced, and MAY be used by implementations to enforce custom "soft" cancellation parameters.

Implementations MAY provide additional fields in this schema (such as a link to a price feed, etc.).

Schema: Market

Defines a market: a trading venue that supports a maker asset (provided by the dealer) and at least one taker asset (provided by the trader).

The concept of a base and quote asset are intentionally omitted, and left for definition at higher levels based on the trading and market scenario.

Schema: Order

A JSON representation of a dealer-signed 0x order.

MUST be implemented according to the 0x specification. Operations with 0x order messages SHOULD be carried out with official 0x libraries (Go implementations here).

Schema: Quote

Defines a price quote from a dealer for a given maker and taker asset, and other quote parameters.

Implementations MAY use the validityParameters field to specify custom "soft cancel" parameters for served quotes.

Schema: QuoteStub

Defines a public "quote stub," indicating a price bound and quantity limit for a given maker/taker asset pair that a trader may request a full quote for at a later time (see dealer_getQuoteFromStub).

When requesting a quote based on a price stub the trader can denominate the size in either the asset they are sending (the taker asset) or the asset they are receiving (the maker asset). The dealer implementation MUST fill in the other value, similar to how regular quotes work. Thus, dealer's MUST service quote requests denominated in a quantity of either the maker or taker asset.

By using either the makerSizeLimit or the takerSizeLimit, dealers are able to choose whether to restrict price levels based on a quantity of either the maker or taker asset, which is generally useful to simplify internal accounting. For example, consider the following two quote stub:

[
    {
        "stubId": "2b769dc1-87f3-4814-a2df-252d514188e8",
        "makerAssetAddress": "0x6b175474e89094c44da98b954eedeac495271d0f",
        "takerAssetAddress": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
        "makerSizeLimit": null,
        "takerSizeLimit": "10000000000000000000",
        "makerPriceBand": [122.5, 124.1],
        "takerPriceBand": null
    },
    {
        "stubId": "2e58f94f-3e9f-4830-b775-1fd1483a199a",
        "makerAssetAddress": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
        "takerAssetAddress": "0x6b175474e89094c44da98b954eedeac495271d0f",
        "makerSizeLimit": "10000000000000000000",
        "takerSizeLimit": null,
        "makerPriceBand": null,
        "takerPriceBand": [123.8, 125.2]
    }
]

Either makerSizeLimit and takerPriceBand or takerSizeLimit and makerPriceBand MUST be included in each stub — whichever fields are not present MUST be null and dealers MUST NOT include both makerSizeLimit and takerSizeLimit or both makerPriceBand and takerPriceBand.

More formally, the following MUST be true for each stub:

The dealer providing the stubs above has chosen to always represent prices on WETH/DAI markets in terms of the amount of DAI received or provided per unit of WETH. Dealers MAY choose to always represent priced in terms of the maker asset, taker asset, or a common "quote" asset (DAI in the example above).

Schema: StubUpdate

Dealers can indicate a change to an existing quote stub’s makerSizeLimit or takerSizeLimit with StubUpdate messages (sent to subscribing traders, or posted to a public venue), which reference the stub’s original ID and a new makerSizeLimit or takerSizeLimit.

If the respective value is set to 0, this indicates the stub has been canceled. Dealer’s MUST only provide updates that modify the max size for the maker or taker asset; to change price bounds for a stub, it MUST be cancelled and a new one SHOULD be issued.

Individual stub update messages MUST ONLY specify the makerSizeLimit or takerSizeLimit (not both), which MUST match the limit used in the original stub. For example, if a quote stub with ID X initially specifies a makerSizeLimit, updates to that stub MUST ONLY specify updated makerSizeLimit values. A stub update with ID X that specified a takerSizeLimit would be in violation of this specification and MUST NOT occur.

Appendix

Important resources

Notes

  1. This definition of a market makes an intentional departure from conventional currency-pair based markets in which their is a single quote asset and a single base asset. Defining only the maker and taker assets for a market allows greater flexibility for implementers, and allows pricing to be defined in terms of either asset at higher levels.
  2. If the dealer is operating on the main Ethereum network, they MUST treat the chainId of 1 as the Ethereum mainnet, as specified in EIP-155. Private and test networks may use any chain ID, but SHOULD use conventions established by public test networks (e.g. Ropsten is 3).
  3. The default value SHOULD be the null address (20 null bytes) represented as a hex string. Implementations MAY require takers to specify a takerAddress.
  4. Quotes indicated as includeOrder as false can be seen as traders checking if a dealer's prices are favorable at a given time for a certain market and trade size.
    • Implementations MAY treat these types of quotes separately in internal tracking and/or pricing mechanisms.
  5. Due to confusion between the word "transaction" referring to either an Ethereum transaction or a 0x ZEIP-18 transaction (ZeroExTransaction), wherever the word refers to an Ethereum transaction, it is explicitly stated. Similarly, wherever "transaction" refers to a ZEIP-18 message, it is explicitly described as a "0x transaction" or a "0x fill transaction" (the same goes for transaction hashes).

Error codes

A table of all specified error codes, which MAY be used in methods other than where they are specified, if applicable.

Code Description Notes
-32700 Parse error. Invalid JSON was received by the server. MUST be implemented.
-32600 Invalid request. The JSON sent is not a valid request object (see JSONRPC spec). MUST be implemented.
-32601 Method not found. The method does not exist or is not available.
-32602 Invalid parameters. Invalid method parameters. MAY be omitted in favor of more specific codes.
-32603 Internal error. Internal JSON-RPC error. MAY be used as generic internal error code.
-42002 Invalid filter selection. Returned when conflicting or incompatible filters are requested.
-42003 Invalid address. Returned when an invalid Ethereum address is provided.
-42004 Invalid asset. Generic code that MAY be used to indicate unsupported asset, or an address that is not an ERC-20 asset.
-42005 Two size requests. Occurs when a client specifies makerAssetSize and takerAssetSize.
-42006 Taker not authorized. Occurs when the taker's address is not authorized for trading.
-42007 Invalid side. Available for implementations to indicate lack of support for arbitrary swaps.
-42008 Temporary restriction. Available for implementations to indicate taker-specific temporary restrictions.
-42009 Unsupported market. Occurs when the specified market (quote and base pair) is not supported.
-42010 Unsupported taker asset for market. Available for implementations to indicate lack of support for arbitrary swaps.
-42011 Quote too large. Occurs when a quote would exceed the market maximum or the dealer's balance.
-42012 Quote too small. Occurs when a quote would be smaller than the market's minimum size.
-42013 Quote unavailable at this time. Reserved for various states where dealers may not be serving quotes.
-42014 Quote expired. MUST be implemented and used ONLY when a request-to-fill is received after the quotes expiration.
-42015 Unknown quote. Available to allow implementations differentiate expired from never-quoted.
-42016 Order already filled. Available to allow implementations to indicate specific double-fill attempts.
-42017 Fill validation failed. Available to indicate current chain state simulation validation failure.
-42018 Insufficient taker balance. Available to indicate specific validation failure.
-42019 Insufficient taker allowance. Available to indicate specific validation failure.
-42020 Quote validation failure. Available to indicate implementation-specific failures of extra quote data.
-42021 Invalid transaction ID. Available to indicate an invalid Ethereum transaction hash in a request.
-42022 Invalid order hash. Available to indicate an order transaction hash in a request.
-42023 Invalid UUID. Available to indicate failure to validate a universally unique identifier (UUID).
-42024 Request rate limit reached. Available to indicate a implementation-specific request rate limit has been reached.
-42025 Stub no longer available. Available to indicate that a quote stub has expired or is no longer supported for another reason.