tradingstate

package
v0.0.0-...-7037f4e Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2021 License: GPL-3.0 Imports: 22 Imported by: 0

Documentation

Overview

Package state provides a caching layer atop the Ethereum state trie.

Index

Constants

View Source
const (
	OrderStatusNew           = "NEW"
	OrderStatusOpen          = "OPEN"
	OrderStatusPartialFilled = "PARTIAL_FILLED"
	OrderStatusFilled        = "FILLED"
	OrderStatusCancelled     = "CANCELLED"
	OrderStatusRejected      = "REJECTED"
)
View Source
const (
	TradeStatusSuccess = "SUCCESS"

	TradeTakerOrderHash = "takerOrderHash"
	TradeMakerOrderHash = "makerOrderHash"
	TradeTimestamp      = "timestamp"
	TradeQuantity       = "quantity"
	TradeMakerExchange  = "makerExAddr"
	TradeMaker          = "uAddr"
	TradeBaseToken      = "bToken"
	TradeQuoteToken     = "qToken"
	TradePrice          = "tradedPrice"
	MakerOrderType      = "makerOrderType"
	MakerFee            = "makerFee"
	TakerFee            = "takerFee"
)
View Source
const DefaultFeeRate = 10 // 10 / SdxXBaseFee = 10 / 10000 = 0.1%
View Source
const (
	OrderCacheLimit = 10000
)

Variables

View Source
var (
	EmptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
	Ask       = "SELL"
	Bid       = "BUY"
	Market    = "MO"
	Limit     = "LO"
	Cancel    = "CANCELLED"
	OrderNew  = "NEW"
)
View Source
var (
	ErrInvalidSignature = errors.New("verify order: invalid signature")
	ErrInvalidPrice     = errors.New("verify order: invalid price")
	ErrInvalidQuantity  = errors.New("verify order: invalid quantity")
	ErrInvalidRelayer   = errors.New("verify order: invalid relayer")
	ErrInvalidOrderType = errors.New("verify order: unsupported order type")
	ErrInvalidOrderSide = errors.New("verify order: invalid order side")
	ErrInvalidStatus    = errors.New("verify order: invalid status")

	// supported order types
	MatchingOrderType = map[string]bool{
		Market: true,
		Limit:  true,
	}
)
View Source
var (
	TokenMappingSlot = map[string]uint64{
		"balances": 0,
	}
	RelayerMappingSlot = map[string]uint64{
		"CONTRACT_OWNER":       0,
		"MaximumRelayers":      1,
		"MaximumTokenList":     2,
		"RELAYER_LIST":         3,
		"RELAYER_COINBASES":    4,
		"RESIGN_REQUESTS":      5,
		"RELAYER_ON_SALE_LIST": 6,
		"RelayerCount":         7,
		"MinimumDeposit":       8,
	}
	RelayerStructMappingSlot = map[string]*big.Int{
		"_deposit":    big.NewInt(0),
		"_fee":        big.NewInt(1),
		"_fromTokens": big.NewInt(2),
		"_toTokens":   big.NewInt(3),
		"_index":      big.NewInt(4),
		"_owner":      big.NewInt(5),
	}
)
View Source
var EmptyExchangeOnject = tradingExchangeObject{
	Nonce:   0,
	AskRoot: EmptyHash,
	BidRoot: EmptyHash,
}
View Source
var EmptyHash = common.Hash{}
View Source
var EmptyOrder = OrderItem{
	Quantity: Zero,
}
View Source
var EmptyOrderList = orderList{
	Volume: nil,
	Root:   EmptyHash,
}
View Source
var ErrQuantityTradeTooSmall = errors.New("quantity trade too small")
View Source
var MaxTrieCacheGen = uint16(120)

Trie cache generation limit after which to evic trie nodes from memory.

View Source
var One = big.NewInt(1)
View Source
var Zero = big.NewInt(0)

Functions

func Add

func Add(x, y *big.Int) *big.Int

func AddTokenBalance

func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error

func CheckAddTokenBalance

func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error)

func CheckRelayerFee

func CheckRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateDB) error

func CheckSubRelayerFee

func CheckSubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateDB, mapBalances map[common.Address]*big.Int) (*big.Int, error)

func CheckSubTokenBalance

func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error)

func CloneBigInt

func CloneBigInt(bigInt *big.Int) *big.Int

func DecodeBytesItem

func DecodeBytesItem(bytes []byte, val interface{}) error

func Div

func Div(x, y *big.Int) *big.Int

func EncodeBytesItem

func EncodeBytesItem(val interface{}) ([]byte, error)

func EncodeTxMatchesBatch

func EncodeTxMatchesBatch(txMatchBatch TxMatchBatch) ([]byte, error)

func Exp

func Exp(x, y *big.Int) *big.Int

func GetAllCoinbases

func GetAllCoinbases(statedb *state.StateDB) []common.Address

func GetAllTradingPairs

func GetAllTradingPairs(statedb *state.StateDB) (map[common.Hash]bool, error)

func GetBaseTokenAtIndex

func GetBaseTokenAtIndex(relayer common.Address, statedb *state.StateDB, index uint64) common.Address

func GetBaseTokenLength

func GetBaseTokenLength(relayer common.Address, statedb *state.StateDB) uint64

func GetExRelayerFee

func GetExRelayerFee(relayer common.Address, statedb *state.StateDB) *big.Int

func GetLocMappingAtKey

func GetLocMappingAtKey(key common.Hash, slot uint64) *big.Int

func GetMatchingResultCacheKey

func GetMatchingResultCacheKey(order *OrderItem) common.Hash

func GetOrderHistoryKey

func GetOrderHistoryKey(baseToken, quoteToken common.Address, orderHash common.Hash) common.Hash

use orderHash instead of orderId because both takerOrders don't have orderId

func GetQuoteTokenAtIndex

func GetQuoteTokenAtIndex(relayer common.Address, statedb *state.StateDB, index uint64) common.Address

func GetQuoteTokenLength

func GetQuoteTokenLength(relayer common.Address, statedb *state.StateDB) uint64

func GetRelayerCount

func GetRelayerCount(statedb *state.StateDB) uint64

func GetRelayerOwner

func GetRelayerOwner(relayer common.Address, statedb *state.StateDB) common.Address

func GetTokenBalance

func GetTokenBalance(addr common.Address, token common.Address, statedb *state.StateDB) *big.Int

func GetTradingOrderBookHash

func GetTradingOrderBookHash(baseToken common.Address, quoteToken common.Address) common.Hash

func IsResignedRelayer

func IsResignedRelayer(relayer common.Address, statedb *state.StateDB) bool

return true if relayer request to resign and have not withdraw locked fund

func IsValidRelayer

func IsValidRelayer(statedb *state.StateDB, address common.Address) bool

func Max

func Max(a, b *big.Int) *big.Int

func Mul

func Mul(x, y *big.Int) *big.Int

func Neg

func Neg(x *big.Int) *big.Int

func SetSubRelayerFee

func SetSubRelayerFee(relayer common.Address, balance *big.Int, fee *big.Int, statedb *state.StateDB)

func SetTokenBalance

func SetTokenBalance(addr common.Address, balance *big.Int, token common.Address, statedb *state.StateDB) error

func Sub

func Sub(x, y *big.Int) *big.Int

func SubRelayerFee

func SubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateDB) error

func SubTokenBalance

func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error

func ToBigInt

func ToBigInt(s string) *big.Int

func ToJSON

func ToJSON(object interface{}, args ...string) string

ToJSON : log json string

func VerifyBalance

func VerifyBalance(statedb *state.StateDB, sdxxStateDb *TradingStateDB, order *types.OrderTransaction, baseDecimal, quoteDecimal *big.Int) error

func VerifyPair

func VerifyPair(statedb *state.StateDB, exchangeAddress, baseToken, quoteToken common.Address) error

Types

type Database

type Database interface {
	// OpenTrie opens the main account trie.
	OpenTrie(root common.Hash) (Trie, error)

	// OpenStorageTrie opens the storage trie of an account.
	OpenStorageTrie(addrHash, root common.Hash) (Trie, error)

	// CopyTrie returns an independent copy of the given trie.
	CopyTrie(Trie) Trie

	// ContractCode retrieves a particular contract's code.
	ContractCode(addrHash, codeHash common.Hash) ([]byte, error)

	// ContractCodeSize retrieves a particular contracts code's size.
	ContractCodeSize(addrHash, codeHash common.Hash) (int, error)

	// TrieDB retrieves the low level trie database used for data storage.
	TrieDB() *trie.Database
}

Database wraps access to tries and contract code.

func NewDatabase

func NewDatabase(db ethdb.Database) Database

NewDatabase creates a backing store for state. The returned database is safe for concurrent use and retains cached trie nodes in memory. The pool is an optional intermediate trie-node memory pool between the low level storage layer and the high level trie abstraction.

type DumpLendingBook

type DumpLendingBook struct {
	Volume       *big.Int
	LendingBooks map[common.Hash]DumpOrderList
}

type DumpOrderBookInfo

type DumpOrderBookInfo struct {
	LastPrice              *big.Int
	LendingCount           *big.Int
	MediumPrice            *big.Int
	MediumPriceBeforeEpoch *big.Int
	Nonce                  uint64
	TotalQuantity          *big.Int
	BestAsk                *big.Int
	BestBid                *big.Int
	LowestLiquidationPrice *big.Int
}

type DumpOrderList

type DumpOrderList struct {
	Volume *big.Int
	Orders map[*big.Int]*big.Int
}

type EpochPriceItem

type EpochPriceItem struct {
	Epoch     uint64      `bson:"epoch" json:"epoch"`
	Orderbook common.Hash `bson:"orderbook" json:"orderbook"`
	Hash      common.Hash `bson:"hash" json:"hash"`
	Price     *big.Int    `bson:"price" json:"price"`
}

func (*EpochPriceItem) ComputeHash

func (item *EpochPriceItem) ComputeHash() common.Hash

func (*EpochPriceItem) GetBSON

func (item *EpochPriceItem) GetBSON() (interface{}, error)

func (*EpochPriceItem) SetBSON

func (item *EpochPriceItem) SetBSON(raw bson.Raw) error

type EpochPriceItemBSON

type EpochPriceItemBSON struct {
	Epoch     string `bson:"epoch" json:"epoch"`
	Orderbook string `bson:"orderbook" json:"orderbook"`
	Hash      string `bson:"hash" json:"hash"` // Keccak256Hash of Epoch and orderbook, used as an index of this collection
	Price     string `bson:"price" json:"price"`
}

type MatchingResult

type MatchingResult struct {
	Trades  []map[string]string
	Rejects []*OrderItem
}

type OrderHistoryItem

type OrderHistoryItem struct {
	TxHash       common.Hash
	FilledAmount *big.Int
	Status       string
	UpdatedAt    time.Time
}

type OrderItem

type OrderItem struct {
	Quantity        *big.Int       `json:"quantity,omitempty"`
	Price           *big.Int       `json:"price,omitempty"`
	ExchangeAddress common.Address `json:"exchangeAddress,omitempty"`
	UserAddress     common.Address `json:"userAddress,omitempty"`
	BaseToken       common.Address `json:"baseToken,omitempty"`
	QuoteToken      common.Address `json:"quoteToken,omitempty"`
	Status          string         `json:"status,omitempty"`
	Side            string         `json:"side,omitempty"`
	Type            string         `json:"type,omitempty"`
	Hash            common.Hash    `json:"hash,omitempty"`
	TxHash          common.Hash    `json:"txHash,omitempty"`
	Signature       *Signature     `json:"signature,omitempty"`
	FilledAmount    *big.Int       `json:"filledAmount,omitempty"`
	Nonce           *big.Int       `json:"nonce,omitempty"`
	CreatedAt       time.Time      `json:"createdAt,omitempty"`
	UpdatedAt       time.Time      `json:"updatedAt,omitempty"`
	OrderID         uint64         `json:"orderID,omitempty"`
	ExtraData       string         `json:"extraData,omitempty"`
}

OrderItem : info that will be store in database

func (*OrderItem) GetBSON

func (o *OrderItem) GetBSON() (interface{}, error)

func (*OrderItem) SetBSON

func (o *OrderItem) SetBSON(raw bson.Raw) error

func (*OrderItem) VerifyBasicOrderInfo

func (o *OrderItem) VerifyBasicOrderInfo() error

VerifyBasicOrderInfo verify basic info

func (*OrderItem) VerifyOrder

func (o *OrderItem) VerifyOrder(state *state.StateDB) error

VerifyOrder verify orderItem

type OrderItemBSON

type OrderItemBSON struct {
	Quantity        string           `json:"quantity,omitempty" bson:"quantity"`
	Price           string           `json:"price,omitempty" bson:"price"`
	ExchangeAddress string           `json:"exchangeAddress,omitempty" bson:"exchangeAddress"`
	UserAddress     string           `json:"userAddress,omitempty" bson:"userAddress"`
	BaseToken       string           `json:"baseToken,omitempty" bson:"baseToken"`
	QuoteToken      string           `json:"quoteToken,omitempty" bson:"quoteToken"`
	Status          string           `json:"status,omitempty" bson:"status"`
	Side            string           `json:"side,omitempty" bson:"side"`
	Type            string           `json:"type,omitempty" bson:"type"`
	Hash            string           `json:"hash,omitempty" bson:"hash"`
	TxHash          string           `json:"txHash,omitempty" bson:"txHash"`
	Signature       *SignatureRecord `json:"signature,omitempty" bson:"signature"`
	FilledAmount    string           `json:"filledAmount,omitempty" bson:"filledAmount"`
	Nonce           string           `json:"nonce,omitempty" bson:"nonce"`
	CreatedAt       time.Time        `json:"createdAt,omitempty" bson:"createdAt"`
	UpdatedAt       time.Time        `json:"updatedAt,omitempty" bson:"updatedAt"`
	OrderID         string           `json:"orderID,omitempty" bson:"orderID"`
	ExtraData       string           `json:"extraData,omitempty" bson:"extraData"`
}

type SdxXManagedState

type SdxXManagedState struct {
	*TradingStateDB
	// contains filtered or unexported fields
}

func ManageState

func ManageState(statedb *TradingStateDB) *SdxXManagedState

SdxXManagedState returns a new managed state with the statedb as it's backing layer

func (*SdxXManagedState) GetNonce

func (ms *SdxXManagedState) GetNonce(addr common.Hash) uint64

GetNonce returns the canonical nonce for the managed or unmanaged orderId.

Because GetNonce mutates the DB, we must take a write lock.

func (*SdxXManagedState) HasAccount

func (ms *SdxXManagedState) HasAccount(addr common.Hash) bool

HasAccount returns whether the given address is managed or not

func (*SdxXManagedState) NewNonce

func (ms *SdxXManagedState) NewNonce(addr common.Hash) uint64

NewNonce returns the new canonical nonce for the managed orderId

func (*SdxXManagedState) RemoveNonce

func (ms *SdxXManagedState) RemoveNonce(addr common.Hash, n uint64)

RemoveNonce removed the nonce from the managed state and all future pending nonces

func (*SdxXManagedState) SetNonce

func (ms *SdxXManagedState) SetNonce(addr common.Hash, nonce uint64)

SetNonce sets the new canonical nonce for the managed state

func (*SdxXManagedState) SetState

func (ms *SdxXManagedState) SetState(statedb *TradingStateDB)

SetState sets the backing layer of the managed state

type SdxXTrie

type SdxXTrie struct {
	// contains filtered or unexported fields
}

SdxXTrie wraps a trie with key hashing. In a secure trie, all access operations hash the key using keccak256. This prevents calling code from creating long chains of nodes that increase the access time.

Contrary to a regular trie, a SdxXTrie can only be created with New and must have an attached database. The database also stores the preimage of each key.

SdxXTrie is not safe for concurrent use.

func NewSdxXTrie

func NewSdxXTrie(root common.Hash, db *trie.Database) (*SdxXTrie, error)

NewSdxXTrie creates a trie with an existing root node from a backing database and optional intermediate in-memory node pool.

If root is the zero hash or the sha3 hash of an empty string, the trie is initially empty. Otherwise, New will panic if db is nil and returns MissingNodeError if the root node cannot be found.

Accessing the trie loads nodes from the database or node pool on demand. Loaded nodes are kept around until their 'cache generation' expires. A new cache generation is created by each call to Commit. cachelimit sets the number of past cache generations to keep.

func (*SdxXTrie) Commit

func (t *SdxXTrie) Commit(onleaf trie.LeafCallback) (root common.Hash, err error)

Commit writes all nodes and the secure hash pre-images to the trie's database. Nodes are stored with their sha3 hash as the key.

Committing flushes nodes from memory. Subsequent Get calls will load nodes from the database.

func (*SdxXTrie) Copy

func (t *SdxXTrie) Copy() *SdxXTrie

func (*SdxXTrie) Delete

func (t *SdxXTrie) Delete(key []byte)

Delete removes any existing value for key from the trie.

func (*SdxXTrie) Get

func (t *SdxXTrie) Get(key []byte) []byte

Get returns the value for key stored in the trie. The value bytes must not be modified by the caller.

func (*SdxXTrie) GetKey

func (t *SdxXTrie) GetKey(shaKey []byte) []byte

GetKey returns the sha3 preimage of a hashed key that was previously used to store a value.

func (*SdxXTrie) Hash

func (t *SdxXTrie) Hash() common.Hash

func (*SdxXTrie) NodeIterator

func (t *SdxXTrie) NodeIterator(start []byte) trie.NodeIterator

NodeIterator returns an iterator that returns nodes of the underlying trie. Iteration starts at the key after the given start key.

func (*SdxXTrie) Prove

func (t *SdxXTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error

Prove constructs a merkle proof for key. The result contains all encoded nodes on the path to the value at key. The value itself is also included in the last node and can be retrieved by verifying the proof.

If the trie does not contain a value for key, the returned proof contains all nodes of the longest existing prefix of the key (at least the root node), ending with the node that proves the absence of the key.

func (*SdxXTrie) TryDelete

func (t *SdxXTrie) TryDelete(key []byte) error

TryDelete removes any existing value for key from the trie. If a node was not found in the database, a MissingNodeError is returned.

func (*SdxXTrie) TryGet

func (t *SdxXTrie) TryGet(key []byte) ([]byte, error)

TryGet returns the value for key stored in the trie. The value bytes must not be modified by the caller. If a node was not found in the database, a MissingNodeError is returned.

func (*SdxXTrie) TryGetAllLeftKeyAndValue

func (t *SdxXTrie) TryGetAllLeftKeyAndValue(limit []byte) ([][]byte, [][]byte, error)

func (*SdxXTrie) TryGetBestLeftKeyAndValue

func (t *SdxXTrie) TryGetBestLeftKeyAndValue() ([]byte, []byte, error)

TryGetBestLeftKey returns the value of max left leaf If a node was not found in the database, a MissingNodeError is returned.

func (*SdxXTrie) TryGetBestRightKeyAndValue

func (t *SdxXTrie) TryGetBestRightKeyAndValue() ([]byte, []byte, error)

TryGetBestRightKey returns the value of max left leaf If a node was not found in the database, a MissingNodeError is returned.

func (*SdxXTrie) TryUpdate

func (t *SdxXTrie) TryUpdate(key, value []byte) error

TryUpdate associates key with value in the trie. Subsequent calls to Get will return value. If value has length zero, any existing value is deleted from the trie and calls to Get will return nil.

The value bytes must not be modified by the caller while they are stored in the trie.

If a node was not found in the database, a MissingNodeError is returned.

func (*SdxXTrie) Update

func (t *SdxXTrie) Update(key, value []byte)

Update associates key with value in the trie. Subsequent calls to Get will return value. If value has length zero, any existing value is deleted from the trie and calls to Get will return nil.

The value bytes must not be modified by the caller while they are stored in the trie.

type SettleBalance

type SettleBalance struct {
	Taker TradeResult
	Maker TradeResult
}

func GetSettleBalance

func GetSettleBalance(quotePrice *big.Int, takerSide string, takerFeeRate *big.Int, baseToken, quoteToken common.Address, makerPrice *big.Int, makerFeeRate *big.Int, baseTokenDecimal *big.Int, quoteTokenDecimal *big.Int, quantityToTrade *big.Int) (*SettleBalance, error)

func (*SettleBalance) String

func (settleBalance *SettleBalance) String() string

type Signature

type Signature struct {
	V byte
	R common.Hash
	S common.Hash
}

Signature struct

func (*Signature) MarshalSignature

func (s *Signature) MarshalSignature() ([]byte, error)

MarshalSignature marshals the signature struct to []byte

func (*Signature) Verify

func (s *Signature) Verify(hash common.Hash) (common.Address, error)

Verify returns the address that corresponds to the given signature and signed message

type SignatureRecord

type SignatureRecord struct {
	V byte   `json:"V" bson:"V"`
	R string `json:"R" bson:"R"`
	S string `json:"S" bson:"S"`
}

type Trade

type Trade struct {
	Taker          common.Address `json:"taker" bson:"taker"`
	Maker          common.Address `json:"maker" bson:"maker"`
	BaseToken      common.Address `json:"baseToken" bson:"baseToken"`
	QuoteToken     common.Address `json:"quoteToken" bson:"quoteToken"`
	MakerOrderHash common.Hash    `json:"makerOrderHash" bson:"makerOrderHash"`
	TakerOrderHash common.Hash    `json:"takerOrderHash" bson:"takerOrderHash"`
	MakerExchange  common.Address `json:"makerExchange" bson:"makerExchange"`
	TakerExchange  common.Address `json:"takerExchange" bson:"takerExchange"`
	Hash           common.Hash    `json:"hash" bson:"hash"`
	TxHash         common.Hash    `json:"txHash" bson:"txHash"`
	PricePoint     *big.Int       `json:"pricepoint" bson:"pricepoint"`
	Amount         *big.Int       `json:"amount" bson:"amount"`
	MakeFee        *big.Int       `json:"makeFee" bson:"makeFee"`
	TakeFee        *big.Int       `json:"takeFee" bson:"takeFee"`
	Status         string         `json:"status" bson:"status"`
	CreatedAt      time.Time      `json:"createdAt" bson:"createdAt"`
	UpdatedAt      time.Time      `json:"updatedAt" bson:"updatedAt"`
	TakerOrderSide string         `json:"takerOrderSide" bson:"takerOrderSide"`
	TakerOrderType string         `json:"takerOrderType" bson:"takerOrderType"`
	MakerOrderType string         `json:"makerOrderType" bson:"makerOrderType"`
}

func (*Trade) ComputeHash

func (t *Trade) ComputeHash() common.Hash

ComputeHash returns hashes the trade The OrderHash, Amount, Taker and TradeNonce attributes must be set before attempting to compute the trade orderBookHash

func (*Trade) GetBSON

func (t *Trade) GetBSON() (interface{}, error)

func (*Trade) SetBSON

func (t *Trade) SetBSON(raw bson.Raw) error

type TradeBSON

type TradeBSON struct {
	Taker          string    `json:"taker" bson:"taker"`
	Maker          string    `json:"maker" bson:"maker"`
	BaseToken      string    `json:"baseToken" bson:"baseToken"`
	QuoteToken     string    `json:"quoteToken" bson:"quoteToken"`
	MakerOrderHash string    `json:"makerOrderHash" bson:"makerOrderHash"`
	TakerOrderHash string    `json:"takerOrderHash" bson:"takerOrderHash"`
	MakerExchange  string    `json:"makerExchange" bson:"makerExchange"`
	TakerExchange  string    `json:"takerExchange" bson:"takerExchange"`
	Hash           string    `json:"hash" bson:"hash"`
	TxHash         string    `json:"txHash" bson:"txHash"`
	Amount         string    `json:"amount" bson:"amount"`
	MakeFee        string    `json:"makeFee" bson:"makeFee"`
	TakeFee        string    `json:"takeFee" bson:"takeFee"`
	PricePoint     string    `json:"pricepoint" bson:"pricepoint"`
	Status         string    `json:"status" bson:"status"`
	CreatedAt      time.Time `json:"createdAt" bson:"createdAt"`
	UpdatedAt      time.Time `json:"updatedAt" bson:"updatedAt"`
	TakerOrderSide string    `json:"takerOrderSide" bson:"takerOrderSide"`
	TakerOrderType string    `json:"takerOrderType" bson:"takerOrderType"`
	MakerOrderType string    `json:"makerOrderType" bson:"makerOrderType"`
}

type TradeResult

type TradeResult struct {
	Fee      *big.Int
	InToken  common.Address
	InTotal  *big.Int
	OutToken common.Address
	OutTotal *big.Int
}

type TradingStateDB

type TradingStateDB struct {
	// contains filtered or unexported fields
}

StateDBs within the ethereum protocol are used to store anything within the merkle trie. StateDBs take care of caching and storing nested states. It's the general query interface to retrieve: * Contracts * Accounts

func New

func New(root common.Hash, db Database) (*TradingStateDB, error)

Create a new state from a given trie.

func (*TradingStateDB) CancelOrder

func (self *TradingStateDB) CancelOrder(orderBook common.Hash, order *OrderItem) error

func (*TradingStateDB) Commit

func (s *TradingStateDB) Commit() (root common.Hash, err error)

Commit writes the state to the underlying in-memory trie database.

func (*TradingStateDB) Copy

func (self *TradingStateDB) Copy() *TradingStateDB

Copy creates a deep, independent copy of the state. Snapshots of the copied state cannot be applied to the copy.

func (*TradingStateDB) Database

func (self *TradingStateDB) Database() Database

Database retrieves the low level database supporting the lower level trie ops.

func (*TradingStateDB) DumpAskTrie

func (self *TradingStateDB) DumpAskTrie(orderBook common.Hash) (map[*big.Int]DumpOrderList, error)

func (*TradingStateDB) DumpBidTrie

func (self *TradingStateDB) DumpBidTrie(orderBook common.Hash) (map[*big.Int]DumpOrderList, error)

func (*TradingStateDB) DumpLiquidationPriceTrie

func (self *TradingStateDB) DumpLiquidationPriceTrie(orderBook common.Hash) (map[*big.Int]DumpLendingBook, error)

func (*TradingStateDB) DumpOrderBookInfo

func (self *TradingStateDB) DumpOrderBookInfo(orderBook common.Hash) (*DumpOrderBookInfo, error)

func (*TradingStateDB) Empty

func (self *TradingStateDB) Empty(addr common.Hash) bool

Empty returns whether the state object is either non-existent or empty according to the EIP161 specification (balance = nonce = code = 0)

func (*TradingStateDB) Error

func (self *TradingStateDB) Error() error

func (*TradingStateDB) Exist

func (self *TradingStateDB) Exist(addr common.Hash) bool

Exist reports whether the given orderId address exists in the state. Notably this also returns true for suicided exchanges.

func (*TradingStateDB) Finalise

func (s *TradingStateDB) Finalise()

Finalise finalises the state by removing the self destructed objects and clears the journal as well as the refunds.

func (*TradingStateDB) GetAllLowerLiquidationPriceData

func (self *TradingStateDB) GetAllLowerLiquidationPriceData(orderBook common.Hash, limit *big.Int) map[*big.Int]map[common.Hash][]common.Hash

func (*TradingStateDB) GetAsks

func (self *TradingStateDB) GetAsks(orderBook common.Hash) (map[*big.Int]*big.Int, error)

func (*TradingStateDB) GetBestAskPrice

func (self *TradingStateDB) GetBestAskPrice(orderBook common.Hash) (*big.Int, *big.Int)

func (*TradingStateDB) GetBestBidPrice

func (self *TradingStateDB) GetBestBidPrice(orderBook common.Hash) (*big.Int, *big.Int)

func (*TradingStateDB) GetBestOrderIdAndAmount

func (self *TradingStateDB) GetBestOrderIdAndAmount(orderBook common.Hash, price *big.Int, side string) (common.Hash, *big.Int, error)

func (*TradingStateDB) GetBids

func (self *TradingStateDB) GetBids(orderBook common.Hash) (map[*big.Int]*big.Int, error)

func (*TradingStateDB) GetHighestLiquidationPriceData

func (self *TradingStateDB) GetHighestLiquidationPriceData(orderBook common.Hash, price *big.Int) (*big.Int, map[common.Hash][]common.Hash)

func (*TradingStateDB) GetLastPrice

func (self *TradingStateDB) GetLastPrice(addr common.Hash) *big.Int

func (*TradingStateDB) GetMediumPriceAndTotalAmount

func (self *TradingStateDB) GetMediumPriceAndTotalAmount(addr common.Hash) (*big.Int, *big.Int)

func (*TradingStateDB) GetMediumPriceBeforeEpoch

func (self *TradingStateDB) GetMediumPriceBeforeEpoch(addr common.Hash) *big.Int

func (*TradingStateDB) GetNonce

func (self *TradingStateDB) GetNonce(addr common.Hash) uint64

func (*TradingStateDB) GetOrNewStateExchangeObject

func (self *TradingStateDB) GetOrNewStateExchangeObject(addr common.Hash) *tradingExchanges

Retrieve a state object or create a new state object if nil.

func (*TradingStateDB) GetOrder

func (self *TradingStateDB) GetOrder(orderBook common.Hash, orderId common.Hash) OrderItem

func (*TradingStateDB) GetVolume

func (self *TradingStateDB) GetVolume(orderBook common.Hash, price *big.Int, orderType string) *big.Int

func (*TradingStateDB) InsertLiquidationPrice

func (self *TradingStateDB) InsertLiquidationPrice(orderBook common.Hash, price *big.Int, lendingBook common.Hash, tradeId uint64)

func (*TradingStateDB) InsertOrderItem

func (self *TradingStateDB) InsertOrderItem(orderBook common.Hash, orderId common.Hash, order OrderItem)

func (*TradingStateDB) IntermediateRoot

func (s *TradingStateDB) IntermediateRoot() common.Hash

IntermediateRoot computes the current root orderBookHash of the state trie. It is called in between transactions to get the root orderBookHash that goes into transaction receipts.

func (*TradingStateDB) MarkStateExchangeObjectDirty

func (self *TradingStateDB) MarkStateExchangeObjectDirty(addr common.Hash)

MarkStateAskObjectDirty adds the specified object to the dirty map to avoid costly state object cache iteration to find a handful of modified ones.

func (*TradingStateDB) RemoveLiquidationPrice

func (self *TradingStateDB) RemoveLiquidationPrice(orderBook common.Hash, price *big.Int, lendingBook common.Hash, tradeId uint64) error

func (*TradingStateDB) RevertToSnapshot

func (self *TradingStateDB) RevertToSnapshot(revid int)

RevertToSnapshot reverts all state changes made since the given revision.

func (*TradingStateDB) SetLastPrice

func (self *TradingStateDB) SetLastPrice(addr common.Hash, price *big.Int)

func (*TradingStateDB) SetMediumPrice

func (self *TradingStateDB) SetMediumPrice(addr common.Hash, price *big.Int, quantity *big.Int)

func (*TradingStateDB) SetMediumPriceBeforeEpoch

func (self *TradingStateDB) SetMediumPriceBeforeEpoch(addr common.Hash, price *big.Int)

func (*TradingStateDB) SetNonce

func (self *TradingStateDB) SetNonce(addr common.Hash, nonce uint64)

func (*TradingStateDB) Snapshot

func (self *TradingStateDB) Snapshot() int

Snapshot returns an identifier for the current revision of the state.

func (*TradingStateDB) SubAmountOrderItem

func (self *TradingStateDB) SubAmountOrderItem(orderBook common.Hash, orderId common.Hash, price *big.Int, amount *big.Int, side string) error

type Trie

type Trie interface {
	TryGet(key []byte) ([]byte, error)
	TryGetBestLeftKeyAndValue() ([]byte, []byte, error)
	TryGetAllLeftKeyAndValue(limit []byte) ([][]byte, [][]byte, error)
	TryGetBestRightKeyAndValue() ([]byte, []byte, error)
	TryUpdate(key, value []byte) error
	TryDelete(key []byte) error
	Commit(onleaf trie.LeafCallback) (common.Hash, error)
	Hash() common.Hash
	NodeIterator(startKey []byte) trie.NodeIterator
	GetKey([]byte) []byte // TODO(fjl): remove this when SdxXTrie is removed
	Prove(key []byte, fromLevel uint, proofDb ethdb.KeyValueWriter) error
}

Trie is a Ethereum Merkle Trie.

type TxDataMatch

type TxDataMatch struct {
	Order []byte // serialized data of order has been processed in this tx
}

func (TxDataMatch) DecodeOrder

func (tx TxDataMatch) DecodeOrder() (*OrderItem, error)

type TxMatchBatch

type TxMatchBatch struct {
	Data      []TxDataMatch
	Timestamp int64
	TxHash    common.Hash
}

func DecodeTxMatchesBatch

func DecodeTxMatchesBatch(data []byte) (TxMatchBatch, error)

Jump to

Keyboard shortcuts

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