order

package
v0.5.9-beta7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 23, 2023 License: BlueOak-1.0.0 Imports: 14 Imported by: 2

Documentation

Overview

Package order defines the Order and Match types used throughout the DEX.

Package order defines the Order and Match types used throughout the DEX.

Index

Constants

View Source
const CommitmentSize = hashSize

CommitmentSize is the length of the Commitment, a 32-byte Blake-256 hash according to the DEX specification.

View Source
const MatchIDSize = blake256.Size

MatchIDSize defines the length in bytes of an MatchID.

View Source
const OrderIDSize = hashSize

OrderIDSize defines the length in bytes of an OrderID.

View Source
const PrefixLen = account.HashSize + 4 + 4 + 1 + 8 + 8 + CommitmentSize

PrefixLen is the length in bytes of the serialized order Prefix.

View Source
const PreimageSize = 32

PreimageSize defines the length of the preimage, which is a 32-byte value according to the DEX specification.

Variables

This section is empty.

Functions

func EncodeMatch

func EncodeMatch(match *UserMatch) []byte

EncodeMatch encodes the UserMatch to bytes suitable for binary storage or communications.

func EncodeOrder

func EncodeOrder(ord Order) []byte

EncodeOrder encodes the order to bytes suitable for wire communications or database storage. EncodeOrder accepts any type of Order.

func EncodePrefix

func EncodePrefix(p *Prefix) []byte

EncodePrefix encodes the order Prefix to a versioned blob.

func EncodeTrade

func EncodeTrade(ord *Trade) []byte

EncodeTrade encodes the MarketOrder information, but not the Prefix structure.

func ExtractAddress added in v0.4.0

func ExtractAddress(ord Order) string

ExtractAddress extracts the address from the order. If the order is a cancel order, an empty string is returned.

func ValidateOrder

func ValidateOrder(ord Order, status OrderStatus, lotSize uint64) error

ValidateOrder ensures that the order with the given status for the specified market is sensible. The ServerTime may not be set yet, so the OrderID cannot be computed.

Types

type CancelOrder

type CancelOrder struct {
	P
	TargetOrderID OrderID
}

CancelOrder defines a cancel order in terms of an order Prefix and the ID of the order to be canceled.

func (*CancelOrder) ID

func (o *CancelOrder) ID() OrderID

ID computes the order ID.

func (*CancelOrder) Serialize

func (o *CancelOrder) Serialize() []byte

Serialize marshals the CancelOrder into a []byte.

func (*CancelOrder) String

func (o *CancelOrder) String() string

String is the same as UID. It is defined to satisfy Stringer.

func (*CancelOrder) Trade

func (o *CancelOrder) Trade() *Trade

Trade returns a pointer to the orders embedded Trade.

func (*CancelOrder) UID

func (o *CancelOrder) UID() string

UID computes the order ID, returning the string representation.

type CoinID

type CoinID []byte

CoinID should be used to wrap a []byte so that it may be used as a map key.

func (CoinID) String

func (c CoinID) String() string

type Commitment

type Commitment hash

Commitment is the Blake-256 hash of the Preimage.

func (*Commitment) IsZero

func (c *Commitment) IsZero() bool

IsZero indicates if the Commitment is the zero-value for the type.

func (*Commitment) Scan

func (c *Commitment) Scan(src interface{}) error

Scan implements the sql.Scanner interface. NULL table values are scanned as the zero-value Commitment.

func (Commitment) String

func (c Commitment) String() string

String returns a hexadecimal representation of the Commitment. String implements fmt.Stringer.

func (Commitment) Value

func (c Commitment) Value() (driver.Value, error)

Value implements the sql/driver.Valuer interface. The zero-value Commitment returns nil rather than a byte slice of zeros.

type EpochID

type EpochID struct {
	Idx uint64
	Dur uint64
}

EpochID contains the uniquely-identifying information for an epoch: index and duration.

func (*EpochID) End

func (e *EpochID) End() time.Time

End is the end time of the epoch.

type LimitOrder

type LimitOrder struct {
	P
	T
	Rate  uint64 // price as atoms of quote asset, applied per 1e8 units of the base asset
	Force TimeInForce
}

LimitOrder defines a limit order in terms of a MarketOrder and limit-specific data including rate (price) and time in force.

func (*LimitOrder) ID

func (o *LimitOrder) ID() OrderID

ID computes the order ID.

func (*LimitOrder) Price

func (o *LimitOrder) Price() uint64

Price returns the limit order's price rate.

func (*LimitOrder) Serialize

func (o *LimitOrder) Serialize() []byte

Serialize marshals the LimitOrder into a []byte.

func (*LimitOrder) String

func (o *LimitOrder) String() string

String is the same as UID. It is defined to satisfy Stringer.

func (*LimitOrder) UID

func (o *LimitOrder) UID() string

UID computes the order ID, returning the string representation.

type MarketOrder

type MarketOrder struct {
	P
	T
}

MarketOrder defines a market order in terms of a Prefix and the order details, including the backing Coins, the order direction/side, order quantity, and the address where the matched client will send funds. The order quantity is in atoms of the base asset, and must be an integral multiple of the asset's lot size, except for Market buy orders when it is in units of the quote asset and is not bound by integral lot size multiple constraints.

func (*MarketOrder) ID

func (o *MarketOrder) ID() OrderID

ID computes the order ID.

func (*MarketOrder) Serialize

func (o *MarketOrder) Serialize() []byte

Serialize marshals the LimitOrder into a []byte.

func (*MarketOrder) String

func (o *MarketOrder) String() string

String is the same as UID. It is defined to satisfy Stringer.

func (*MarketOrder) UID

func (o *MarketOrder) UID() string

UID computes the order ID, returning the string representation.

type Match

type Match struct {
	Taker    Order
	Maker    *LimitOrder
	Quantity uint64
	Rate     uint64

	// The following fields are not part of the serialization of Match.
	FeeRateBase  uint64
	FeeRateQuote uint64
	Epoch        EpochID
	Status       MatchStatus
	Sigs         Signatures
	// contains filtered or unexported fields
}

Match represents a match between two orders.

func (*Match) ID

func (match *Match) ID() MatchID

ID computes the match ID and stores it for future calls. BLAKE256([maker order id] + [taker order id] + [match qty] + [match rate])

type MatchID

type MatchID [MatchIDSize]byte

MatchID is the unique identifier for each match.

func DecodeMatchID

func DecodeMatchID(matchIDStr string) (MatchID, error)

DecodeMatchID checks a string as being both hex and the right length and returns its bytes encoded as an order.MatchID.

func (MatchID) Bytes

func (id MatchID) Bytes() []byte

Bytes returns the match ID as a []byte.

func (MatchID) MarshalJSON added in v0.2.0

func (id MatchID) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaller interface, and will marshal the id to a hex string.

func (*MatchID) Scan

func (id *MatchID) Scan(src interface{}) error

Scan implements the sql.Scanner interface.

func (MatchID) String

func (id MatchID) String() string

MatchID implements fmt.Stringer.

func (MatchID) Value

func (id MatchID) Value() (driver.Value, error)

Value implements the sql/driver.Valuer interface.

type MatchProof

type MatchProof struct {
	Epoch     EpochID
	Preimages []Preimage
	Misses    []Order
	CSum      []byte
	Seed      []byte
}

MatchProof contains the key results of an epoch's order matching.

type MatchSet

type MatchSet struct {
	Epoch        EpochID
	Taker        Order
	Makers       []*LimitOrder
	Amounts      []uint64
	Rates        []uint64
	Total        uint64
	FeeRateBase  uint64
	FeeRateQuote uint64
}

MatchSet represents the result of matching a single Taker order from the epoch queue with one or more standing limit orders from the book, the Makers. The Amounts and Rates of each standing order paired are stored. The Rates slice is for convenience since each rate must be the same as the Maker's rate. However, a amount in Amounts may be less than the full quantity of the corresponding Maker order, indicating a partial fill of the Maker. The sum of the amounts, Total, is provided for convenience.

func (*MatchSet) HighLowRates added in v0.2.0

func (set *MatchSet) HighLowRates() (high uint64, low uint64)

HighLowRates gets the highest and lowest rate from all matches.

func (*MatchSet) Matches

func (set *MatchSet) Matches() []*Match

Matches converts the MatchSet to a []*Match.

func (*MatchSet) QuoteVolume added in v0.2.0

func (set *MatchSet) QuoteVolume() (v uint64)

QuoteVolume is the matched quantity in terms of the quote asset.

type MatchSide

type MatchSide uint8

MatchSide is the client's side in a match. It will be one of Maker or Taker.

const (
	// Maker is the order that matches out of the epoch queue.
	Maker MatchSide = iota
	// Taker is the order from the order book.
	Taker
)

func (MatchSide) String

func (side MatchSide) String() string

type MatchStatus

type MatchStatus uint8

MatchStatus represents the current negotiation step for a match.

const (
	// NewlyMatched: DEX has sent match notifications, but the maker has not yet
	// acted.
	NewlyMatched MatchStatus = iota // 0
	// MakerSwapCast: Maker has acknowledged their match notification and
	// broadcast their swap notification. The DEX has validated the swap
	// notification and sent the details to the taker.
	MakerSwapCast // 1
	// TakerSwapCast: Taker has acknowledged their match notification and
	// broadcast their swap notification. The DEX has validated the swap
	// notification and sent the details to the maker.
	TakerSwapCast // 2
	// MakerRedeemed: Maker has acknowledged their audit request and broadcast
	// their redemption transaction. The DEX has validated the redemption and
	// sent the details to the taker.
	MakerRedeemed // 3
	// MatchComplete: Taker has acknowledged their audit request and broadcast
	// their redemption transaction. The DEX has validated the redemption and
	// sent the details to the maker.
	MatchComplete // 4
)

The different states of order execution.

func (MatchStatus) String

func (status MatchStatus) String() string

String satisfies fmt.Stringer.

type Order

type Order interface {
	// Prefix returns the order *Prefix.
	Prefix() *Prefix

	// Trade returns the order *Trade if a limit or market order, else nil.
	Trade() *Trade

	// ID computes the Order's ID from its serialization. Serialization is
	// detailed in the 'Client Order Management' section of the DEX
	// specification.
	ID() OrderID

	// UID gives the string representation of the order ID. It is named to
	// reflect the intent of providing a unique identifier.
	UID() string

	// User gives the user's account ID.
	User() account.AccountID

	// Serialize marshals the order. Serialization is detailed in the 'Client
	// Order Management' section of the DEX specification.
	Serialize() []byte

	// Type indicates the Order's type (e.g. LimitOrder, MarketOrder, etc.).
	Type() OrderType

	// Time returns the Order's server time in milliseconds, when it was received by the server.
	Time() int64

	// SetTime sets the ServerTime field of the prefix.
	SetTime(time.Time)

	// Base returns the unique integer identifier of the base asset as defined
	// in the asset package.
	Base() uint32

	// Quote returns the unique integer identifier of the quote asset as defined
	// in the asset package.
	Quote() uint32

	// Commitment returns the order's preimage commitment.
	Commitment() Commitment
}

Order specifies the methods required for a type to function as a DEX order. See the concrete implementations of MarketOrder, LimitOrder, and CancelOrder.

func DecodeOrder

func DecodeOrder(b []byte) (ord Order, err error)

DecodeOrder decodes the byte-encoded order. DecodeOrder accepts any type of order.

type OrderID

type OrderID hash

OrderID is the unique identifier for each order. It is defined as the Blake256 hash of the serialized order.

func IDFromBytes added in v0.5.0

func IDFromBytes(b []byte) (OrderID, error)

IDFromBytes converts a byte slice to an OrderID.

func IDFromHex

func IDFromHex(sid string) (OrderID, error)

IDFromHex decodes an OrderID from a hexadecimal string.

func (OrderID) Bytes

func (oid OrderID) Bytes() []byte

Bytes returns the order ID as a []byte.

func (OrderID) IsZero

func (oid OrderID) IsZero() bool

IsZero returns true if the order ID is zeros.

func (OrderID) MarshalJSON added in v0.2.0

func (oid OrderID) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaller interface, and will marshal the id to a hex string.

func (*OrderID) Scan

func (oid *OrderID) Scan(src interface{}) error

Scan implements the sql.Scanner interface.

func (OrderID) String

func (oid OrderID) String() string

String returns a hexadecimal representation of the OrderID. String implements fmt.Stringer.

func (OrderID) Value

func (oid OrderID) Value() (driver.Value, error)

Value implements the sql/driver.Valuer interface.

type OrderStatus

type OrderStatus uint16

OrderStatus indicates the state of an order.

const (
	// OrderStatusUnknown is a sentinel value to be used when the status of an
	// order cannot be determined.
	OrderStatusUnknown OrderStatus = iota

	// OrderStatusEpoch is for orders that have been received and validated, but
	// not processed yet by the epoch order matcher.
	OrderStatusEpoch

	// OrderStatusBooked is for orders that have been put on the book
	// ("standing" time in force). This includes partially filled orders. As
	// such, when an order with this "booked" status is matched with another
	// order, it should have its filled amount updated, and its status should
	// only be changed to OrderStatusExecuted if the remaining quantity becomes
	// less than the lot size, or perhaps to OrderStatusRevoked if the swap has
	// failed and DEX conduct policy requires that it be removed from the order
	// book.
	OrderStatusBooked

	// OrderStatusExecuted is for orders that have been successfully processed
	// and taken off the book. An order may reach this state if it is (1)
	// matched one or more times and removed from the books, or (2) unmatched in
	// epoch processing and with a time-in-force that forbids the order from
	// entering the books. Orders in the first category (matched and
	// subsequently removed from the book) include: a matched cancel order, a
	// completely filled limit or market order, or a partially filled market
	// buy order. Market and limit orders in the second category will not
	// necessarily be completely unfilled. Partially filled orders that are
	// still on the order book remain in OrderStatusBooked.
	//
	// Note: The DB driver must be able to distinguish cancel orders that have
	// not matched from those that were not matched, but OrderStatusExecuted
	// will be returned for both such orders, although a new exported status may
	// be added so the consumer can query this information (TODO). The DB knows
	// the match status for cancel orders and how the cancel order was finalized
	// (ExecuteOrder for matched, and FailCancelOrder for unmatched).
	OrderStatusExecuted

	// OrderStatusCanceled is for orders that were on the book, but matched with
	// a cancel order. This does not mean the order is completely unfilled.
	OrderStatusCanceled

	// OrderStatusRevoked is DEX-revoked orders that were not canceled by
	// matching with the client's cancel order but by DEX policy. This includes
	// standing limit orders that were matched but have failed to swap (neither
	// executed nor canceled), and preimage misses.
	OrderStatusRevoked
)

There are two general classes of orders: ACTIVE and ARCHIVED. Orders with one of the ACTIVE order statuses that follow are likely to be updated.

func (OrderStatus) IsActive added in v0.4.0

func (s OrderStatus) IsActive() bool

IsActive returns whether the status is considered active.

func (OrderStatus) String

func (s OrderStatus) String() string

String implements Stringer.

type OrderType

type OrderType uint8

OrderType distinguishes the different kinds of orders (e.g. limit, market, cancel).

const (
	UnknownOrderType OrderType = iota
	LimitOrderType
	MarketOrderType
	CancelOrderType
)

The different OrderType values.

func (*OrderType) Scan

func (ot *OrderType) Scan(src interface{}) error

Scan implements the sql.Scanner interface.

func (OrderType) String

func (ot OrderType) String() string

String returns a string representation of the OrderType.

func (OrderType) Value

func (ot OrderType) Value() (driver.Value, error)

Value implements the sql/driver.Valuer interface.

type P

type P = Prefix

P is an alias for Prefix. Embedding with the alias allows us to define a method on the interface called Prefix that returns the *Prefix.

type Prefix

type Prefix struct {
	AccountID  account.AccountID
	BaseAsset  uint32
	QuoteAsset uint32
	OrderType  OrderType
	ClientTime time.Time
	ServerTime time.Time
	Commit     Commitment
	// contains filtered or unexported fields
}

Prefix is the order prefix containing data fields common to all orders.

func DecodePrefix

func DecodePrefix(b []byte) (prefix *Prefix, err error)

DecodePrefix decodes the versioned blob to a *Prefix.

func (*Prefix) Base

func (p *Prefix) Base() uint32

Base returns the base asset integer ID.

func (*Prefix) Commitment

func (p *Prefix) Commitment() Commitment

Commitment returns the order Commitment.

func (*Prefix) Prefix

func (p *Prefix) Prefix() *Prefix

func (*Prefix) Quote

func (p *Prefix) Quote() uint32

Quote returns the quote asset integer ID.

func (*Prefix) Serialize

func (p *Prefix) Serialize() []byte

Serialize marshals the Prefix into a []byte.

func (*Prefix) SetTime

func (p *Prefix) SetTime(t time.Time)

SetTime sets the order prefix's server time.

func (*Prefix) Time

func (p *Prefix) Time() int64

Time returns the order prefix's server time as a UNIX epoch time in milliseconds.

func (*Prefix) Type

func (p *Prefix) Type() OrderType

Type returns the order type.

func (*Prefix) User

func (p *Prefix) User() account.AccountID

User gives the user's account ID.

type Preimage

type Preimage [PreimageSize]byte

Preimage represents the 32-byte preimage as a byte slice.

func (*Preimage) Commit

func (pi *Preimage) Commit() Commitment

Commit computes the preimage commitment as the Blake-256 hash of the Preimage.

func (*Preimage) IsZero

func (pi *Preimage) IsZero() bool

IsZero checks if the Preimage is the zero Preimage.

func (*Preimage) Scan

func (pi *Preimage) Scan(src interface{}) error

Scan implements the sql.Scanner interface.

func (Preimage) Value

func (pi Preimage) Value() (driver.Value, error)

Value implements the sql/driver.Valuer interface.

type Signatures

type Signatures struct {
	TakerMatch  []byte
	MakerMatch  []byte
	TakerAudit  []byte
	MakerAudit  []byte
	TakerRedeem []byte
	MakerRedeem []byte
}

Signatures holds the acknowledgement signatures required for swap negotiation.

type T

type T = Trade

T is an alias for Trade. Embedding with the alias allows us to define a method on the interface called Trade that returns the *Trade.

type TimeInForce

type TimeInForce uint8

TimeInForce indicates how limit order execution is to be handled. That is, when the order is not immediately matched during processing of the order's epoch, the order may become a standing order or be revoked without a fill.

const (
	ImmediateTiF TimeInForce = iota
	StandingTiF
)

The TimeInForce is either ImmediateTiF, which prevents the order from becoming a standing order if there is no match during epoch processing, or StandingTiF, which allows limit orders to enter the order book if not immediately matched during epoch processing.

func (TimeInForce) String

func (t TimeInForce) String() string

String satisfies the Stringer interface.

type Trade

type Trade struct {
	Coins    []CoinID
	Sell     bool
	Quantity uint64
	Address  string // TODO: provide later, maybe in the match ack

	FillAmt uint64 // use Filled and AddFill methods for thread-safe access
	// contains filtered or unexported fields
}

Trade is information about a trade-type order. Both limit and market orders are trade-type orders.

func DecodeTrade

func DecodeTrade(b []byte) (trade *Trade, err error)

DecodeTrade decodes the versioned-blob market order, but does not populate the embedded Prefix.

func (*Trade) AddFill

func (t *Trade) AddFill(amt uint64)

AddFill increases the filled amount.

func (*Trade) BaseAccount added in v0.5.0

func (t *Trade) BaseAccount() string

BaseAccount is the account address associated with the base asset for the order. Only useful for account-based assets. Use of this method assumes that account coin has already been added (when sell = true).

func (*Trade) Copy

func (t *Trade) Copy() *Trade

Copy makes a shallow copy of a Trade. This is useful when attempting to assign a newly-created trade to an order's field without a linter warning about copying a mutex (e.g. MarketOrder{T: *aNewTrade.Copy()}).

func (*Trade) Filled

func (t *Trade) Filled() uint64

Filled returns the filled amount.

func (*Trade) FromAccount added in v0.5.0

func (t *Trade) FromAccount() string

FromAccount is the account that the order originates from. Only useful for account-based assets. Use of this method assumes that account coin has already been added.

func (*Trade) QuoteAccount added in v0.5.0

func (t *Trade) QuoteAccount() string

QuoteAccount is the account address associated with the quote asset for the order. Only useful for account-based assets. Use of this method assumes that account coin has already been added (when sell = false).

func (*Trade) Remaining

func (t *Trade) Remaining() uint64

Remaining returns the remaining order amount.

func (*Trade) Serialize

func (t *Trade) Serialize() []byte

Serialize marshals the Trade into a []byte.

func (*Trade) SetFill

func (t *Trade) SetFill(amt uint64)

SetFill sets the filled amount.

func (*Trade) SwapAddress

func (t *Trade) SwapAddress() string

SwapAddress returns the order's payment address.

func (*Trade) ToAccount added in v0.5.0

func (t *Trade) ToAccount() string

ToAccount is the account that the order pays to. Only useful for account-based assets.

func (*Trade) Trade

func (t *Trade) Trade() *Trade

Trade returns a pointer to the orders embedded Trade.

type UserMatch

type UserMatch struct {
	OrderID     OrderID
	MatchID     MatchID
	Quantity    uint64
	Rate        uint64
	Address     string
	Status      MatchStatus
	Side        MatchSide
	FeeRateSwap uint64
}

A UserMatch is similar to a Match, but contains less information about the counter-party, and it clarifies which side the user is on. This is the information that might be provided to the client when they are resyncing their matches after a reconnect.

func DecodeMatch

func DecodeMatch(b []byte) (match *UserMatch, err error)

DecodeMatch decodes the versioned blob into a UserMatch.

func (*UserMatch) String added in v0.2.0

func (m *UserMatch) String() string

String is the match ID string, implements fmt.Stringer.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL