dex

package
v0.0.0-...-8768773 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2018 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AT_BUY            = "BUY"
	AT_SELL           = "SELL"
	AT_CANCEL         = "CANCEL"
	AT_CANCELLED      = "CANCELLED"
	AT_PARTIAL_FILLED = "PARTIAL_FILLED"
	AT_FILLED         = "FILLED"
	AT_CANCEL_TRADE   = "AT_CANCEL_TRADE"
	AT_DONE           = "DONE"
)
View Source
const (
	PLACE_ORDER            = "PLACE_ORDER"
	CANCEL_ORDER           = "CANCEL_ORDER"
	ORDER_PLACED           = "ORDER_PLACED"
	SIGNED_DATA            = "SIGNED_DATA"
	REQUEST_SIGNED_DATA    = "REQUEST_SIGNED_DATA"
	ORDER_PARTIALLY_FILLED = "ORDER_PARTIALLY_FILLED"
	ORDER_FILLED           = "ORDER_FILLED"
	ORDER_CANCELED         = "ORDER_CANCELED"
	ORDER_MATCHED          = "ORDER_MATCHED"
	ORDER_EXECUTED         = "ORDER_EXECUTED"
	ORDER_TX_SUCCESS       = "ORDER_TX_SUCCESS"
	ORDER_TX_ERROR         = "ORDER_TX_ERROR"
	TRADE_EXECUTED         = "TRADE_EXECUTED"
	TRADE_TX_SUCCESS       = "TRADE_TX_SUCCESS"
	TRADE_TX_ERROR         = "TRADE_TX_ERROR"
	DONE                   = "DONE"
)
View Source
const MAX_PRICE = 10000000

Variables

This section is empty.

Functions

func PrintCancelOrderLog

func PrintCancelOrderLog(log *interfaces.ExchangeLogCancelOrder) string

func PrintCancelTradeLog

func PrintCancelTradeLog(log *interfaces.ExchangeLogCancelTrade) string

func PrintErrorLog

func PrintErrorLog(log *interfaces.ExchangeLogError) string

func PrintTradeLog

func PrintTradeLog(log *interfaces.ExchangeLogTrade) string

func PrintWithdrawalErrorLog

func PrintWithdrawalErrorLog(log *interfaces.ExchangeLogWithdrawalError) string

Types

type Action

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

func NewBuyAction

func NewBuyAction(o *Order) *Action

func NewCancelAction

func NewCancelAction(hash common.Hash) *Action

func NewCancelTradeAction

func NewCancelTradeAction() *Action

func NewCancelledAction

func NewCancelledAction(hash common.Hash, pair TokenPair) *Action

func NewDoneAction

func NewDoneAction() *Action

func NewFilledAction

func NewFilledAction(order, fromOrder *Order, amount uint64) *Action

func NewPartialFilledAction

func NewPartialFilledAction(order, fromOrder *Order) *Action

func NewSellAction

func NewSellAction(o *Order) *Action

func (*Action) String

func (a *Action) String() string

type ActionType

type ActionType string

type CancelOrderMessage

type CancelOrderMessage struct {
	MessageType MessageType        `json:"messageType"`
	Payload     OrderCancelPayload `json:"payload"`
}

type Client

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

Client simulates the client websocket handler that will be used to perform trading. requests and responses are respectively the outbound and incoming messages. requestLogs and responseLogs are arrays of messages that denote the history of received messages wallet is the ethereum account used for orders and trades. mutex is used to prevent concurrent writes on the websocket connection

func NewClient

func NewClient(w *Wallet, s *Server) *Client

NewClient a default client struct connected to the given server

type ClientLogMessage

type ClientLogMessage struct {
	MessageType MessageType `json:"messageType"`
	Order       *Order      `json:"order"`
	Trade       *Trade      `json:"trade"`
	Tx          common.Hash `json:"tx"`
	ErrorID     int8        `json:"errorID"`
}

The client log is mostly used for testing. It optionally takes orders, trade, error ids and transaction hashes. All these parameters are optional in order to allow the client log message to take in a lot of different types of messages An error id of -1 means that there was no error.

func (*ClientLogMessage) String

func (m *ClientLogMessage) String() string

type Config

type Config struct {
	Accounts       []Address
	Admin          *Wallet
	Wallets        []*Wallet
	Constants      *Constants
	Exchange       Address
	Tokens         map[string]Address
	QuoteTokens    Tokens
	TokenPairs     TokenPairs
	Deployer       *Deployer
	OperatorParams *OperatorParams
}

Config holds the general configuration for the application Currently some parameters are redundant as different type of configurations need different (but similar) parameters - Accounts is a list of ethereum address - Admin is the ethereum account that is in charge of sending transactions to the exchange contract - Wallets is a list of ethereum accounts that can be used for testing purposes. These accounts must be unlocked - Exchange is the address of the Exchange.sol smart contract - Tokens is a mapping of token symbols to token addresses (ERC-20 tokens) - QuoteTokens is a list of tokens that have been registered as quote currencies for testing purposes. - TokenPairs is a list of token pairs (base token + quote token) to be registered for testing purposes.

func CreateConfiguration

func CreateConfiguration() *Config

CreateLocalhostConfiguration() deploys mock tokens and the decentralized exchange contract and returns a configuration object that includes accounts, contract addresses, etc. If contracts are already deployed, then use the NewLocalHostConfiguration instead.

func NewConfiguration

func NewConfiguration() *Config

NewLocalhostConfiguration() returns the configuration used for interacting with a localhost blockchain. ZRX, EOS, WETH token objects are created from the given addresses. The DEX, ZRX, EOS, WETH contracts (ZRX, EOS, WETH can be any ERC20 contracts) have to be already deployed. Otherwise, use the CreateLocalHostConfiguration contract.

func NewDefaultConfiguration

func NewDefaultConfiguration() *Config

NewDefaultConfiguration() returns the configuration used for testing. No contract is deployed and the data used does not exist on-chain.

func NewSimulatorConfiguration

func NewSimulatorConfiguration() *Config

NewSimulatorConfiguration() returns the configuration used for testing. Contracts are deployed on a go-ethereum simulated backend. ZRX, EOS, WETH tokens (which are actually only standard ERC20 tokens arbitrarily named for clarity purposes) are deployed and then added to the pair, quotes and token variables.

type Constants

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

type Deployer

type Deployer struct {
	Wallet  *Wallet
	Backend bind.ContractBackend
}

func NewDefaultDeployer

func NewDefaultDeployer() (*Deployer, error)

NewDefaultDeployer returns a deployer connected to the local node via HTTP (on port 8545) with the first wallet in the configuration

func NewDefaultSimulator

func NewDefaultSimulator() (*Deployer, error)

NewDefaultSimulator returns a simulated deployer useful for unit testing certain functions This simulator functions different from a standard deployer. It does not call a blockchain and uses a fake backend.

func NewDeployer

func NewDeployer(w *Wallet) (*Deployer, error)

NewDeployer returns a deployer connected to the local node via HTTP (on port 8545) with the first wallet in the configuration

func NewSimulator

func NewSimulator(wallet *Wallet, accounts []Address) (*Deployer, error)

NewSimulator returns a simulated deployer. The given wallet is used for signing transactions. Each ethereum address in the list of given accounts is funded with one ether

func NewWebsocketDeployer

func NewWebsocketDeployer(w *Wallet) (*Deployer, error)

NewWebsocketDeployer returns a deployer connected to the local node via websocket (on port 8546). The given wallet is used for signing transactions

func (Deployer) DeployExchange

func (d Deployer) DeployExchange(feeAccount Address) (*Exchange, *types.Transaction, error)

DeployExchange deploys and returns a new instance of the decentralized exchange contract. The exchange is deployed with the given fee account which will receive the trading fees.

func (Deployer) DeployToken

func (d Deployer) DeployToken(receiver Address, amount *big.Int) (*ERC20Token, *types.Transaction, error)

DeployToken deploys a mock ERC20 token. The given `receiver` address receives `amount` tokens. This function makes a complete deployment

func (Deployer) GetNonce

func (d Deployer) GetNonce() *big.Int

func (Deployer) NewExchange

func (d Deployer) NewExchange(address Address) (*Exchange, error)

NewExchange returns a new instance of the excha

func (Deployer) NewToken

func (d Deployer) NewToken(address Address) (*ERC20Token, error)

NewTokens returns a mock ERC20 instance from a given address. This does not deploy any new code on the chain

func (Deployer) WaitMined

func (d Deployer) WaitMined(tx *types.Transaction) (*types.Receipt, error)

type ERC20Token

type ERC20Token struct {
	Address       Address
	Contract      *interfaces.Token
	CallOptions   *bind.CallOpts
	TxOptions     *bind.TransactOpts
	DefaultSender *Wallet
}

func (*ERC20Token) Allowance

func (t *ERC20Token) Allowance(owner Address, spender Address) (*big.Int, error)

func (*ERC20Token) Approve

func (t *ERC20Token) Approve(spender Address, amount *big.Int) (*types.Transaction, error)

func (*ERC20Token) ApproveFrom

func (t *ERC20Token) ApproveFrom(wallet *Wallet, spender Address, amount *big.Int) (*types.Transaction, error)

func (*ERC20Token) BalanceOf

func (t *ERC20Token) BalanceOf(owner Address) (*big.Int, error)

func (*ERC20Token) ListenToTransferEvents

func (t *ERC20Token) ListenToTransferEvents() (chan *interfaces.TokenTransfer, error)

func (*ERC20Token) PrintTransferEvents

func (t *ERC20Token) PrintTransferEvents() error

func (*ERC20Token) SetCustomSender

func (t *ERC20Token) SetCustomSender(w *Wallet)

func (*ERC20Token) SetDefaultSender

func (t *ERC20Token) SetDefaultSender()

func (*ERC20Token) TotalSupply

func (t *ERC20Token) TotalSupply() (*big.Int, error)

func (*ERC20Token) Transfer

func (t *ERC20Token) Transfer(receiver Address, amount *big.Int) (*types.Transaction, error)

func (*ERC20Token) TransferFrom

func (t *ERC20Token) TransferFrom(sender, receiver Address, amount *big.Int) (*types.Transaction, error)

func (*ERC20Token) TransferFromCustomWallet

func (t *ERC20Token) TransferFromCustomWallet(wallet *Wallet, receiver Address, amount *big.Int) (*types.Transaction, error)

type Event

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

func NewDoneMessage

func NewDoneMessage() *Event

NewDoneMessage is used to close certain channels

func (*Event) String

func (e *Event) String() string

type EventType

type EventType string

type Exchange

type Exchange struct {
	Admin       *Wallet
	Address     Address
	Contract    *interfaces.Exchange
	CallOptions *bind.CallOpts
	TxOptions   *bind.TransactOpts
}

Exchange is an augmented interface to the Exchange.sol smart-contract. It uses the smart-contract bindings generated with abigen and adds additional functionality and simplifications to these bindings. Address is the Ethereum address of the exchange contract Contract is the original abigen bindings CallOptions are options for making read calls to the connected backend TxOptions are options for making write txs to the connected backend

func NewExchange

func NewExchange(admin *Wallet, contractAddress Address, backend bind.ContractBackend) (*Exchange, error)

Returns a new exchange interface for a given wallet, contract address and connected backend. The exchange contract need to be already deployed at the given address. The given wallet will be used by default when sending transactions with this object.

func (*Exchange) DepositEther

func (e *Exchange) DepositEther(value *big.Int) (*types.Transaction, error)

DepositEther deposits ether into the exchange smart-contract.

func (*Exchange) DepositEtherFrom

func (e *Exchange) DepositEtherFrom(wallet *Wallet, value *big.Int) (*types.Transaction, error)

DepositEtherFrom deposits ether from a custom address. The transaction sender is reset after the transaction is carried out.

func (*Exchange) DepositToken

func (e *Exchange) DepositToken(token Address, amount *big.Int) (*types.Transaction, error)

DepositToken deposits tokens into the exchange smart-contract.

func (*Exchange) DepositTokenFrom

func (e *Exchange) DepositTokenFrom(wallet *Wallet, token Address, amount *big.Int) (*types.Transaction, error)

DepositEtherFrom deposits ether from a custom address. The transaction sender is reset after the transaction is carried out.

func (*Exchange) EtherBalance

func (e *Exchange) EtherBalance(trader Address) (*big.Int, error)

EtherBalance returns the Exchange ether balance of the given account address. Note: This is not the current ether balance of the given ether address. It's the balance of ether that has been deposited in the exchange smart contract.

func (*Exchange) FeeAccount

func (e *Exchange) FeeAccount() (Address, error)

FeeAccount is the Ethereum towards the exchange trading fees are sent

func (*Exchange) GetErrorEvents

func (e *Exchange) GetErrorEvents(logs chan *interfaces.ExchangeLogError) error

func (*Exchange) GetTrades

func (e *Exchange) GetTrades(logs chan *interfaces.ExchangeLogTrade) error

func (*Exchange) ListenToDeposits

func (e *Exchange) ListenToDeposits() (chan *interfaces.ExchangeLogDeposit, error)

ListenToTrades returns a channel that receivs deposit logs (events) from the underlying exchange smart contract

func (*Exchange) ListenToErrorEvents

func (e *Exchange) ListenToErrorEvents() (chan *interfaces.ExchangeLogError, error)

ListenToErrorEvents returns a channel that receives errors logs (events) from the exchange smart contract. The error IDs correspond to the following codes: 1. MAKER_INSUFFICIENT_BALANCE, 2. TAKER_INSUFFICIENT_BALANCE, 3. WITHDRAW_INSUFFICIENT_BALANCE, 4. WITHDRAW_FEE_TO_HIGH, 5. ORDER_EXPIRED, 6. WITHDRAW_ALREADY_COMPLETED, 7. TRADE_ALREADY_COMPLETED, 8. TRADE_AMOUNT_TOO_BIG, 9. SIGNATURE_INVALID, 10. MAKER_SIGNATURE_INVALID, 11. TAKER_SIGNATURE_INVALID

func (*Exchange) ListenToTrades

func (e *Exchange) ListenToTrades() (chan *interfaces.ExchangeLogTrade, error)

ListenToTrades returns a channel that receivs trade logs (events) from the underlying exchange smart contract

func (*Exchange) Operator

func (e *Exchange) Operator(address Address) (bool, error)

Operator returns true if the given address is an operator of the exchange and returns false otherwise

func (*Exchange) PrintErrors

func (e *Exchange) PrintErrors() error

func (*Exchange) PrintTrades

func (e *Exchange) PrintTrades() error

func (*Exchange) SecurityWithdraw

func (e *Exchange) SecurityWithdraw(wallet *Wallet, token Address, amount *big.Int) (*types.Transaction, error)

SecurityWithdraw executes a security withdraw transaction. Security withdraw transactions can only be executed after the security withdrawal period has ended.

func (*Exchange) SetCustomSender

func (e *Exchange) SetCustomSender(wallet *Wallet)

SetCustomSender updates the sender address address to the exchange contract

func (*Exchange) SetDefaultSender

func (e *Exchange) SetDefaultSender()

SetDefaultSender sets the default sender address that will be used when sending a transcation to the exchange contract

func (*Exchange) SetDefaultTxOptions

func (e *Exchange) SetDefaultTxOptions()

SetDefaultTxOptions resets the transaction value to 0

func (*Exchange) SetFeeAccount

func (e *Exchange) SetFeeAccount(account Address) (*types.Transaction, error)

SetFeeAccount sets the fee account of the exchange contract. The fee account receives the trading fees whenever a trade is settled.

func (*Exchange) SetOperator

func (e *Exchange) SetOperator(account Address, isOperator bool) (*types.Transaction, error)

SetOperator updates the operator settings of the given address. Only addresses with an operator access can execute Withdraw and Trade transactions to the Exchange smart contract

func (*Exchange) SetTxValue

func (e *Exchange) SetTxValue(value *big.Int)

SetTxValue sets the transaction ether value

func (*Exchange) SetWithdrawalSecurityPeriod

func (e *Exchange) SetWithdrawalSecurityPeriod(p *big.Int) (*types.Transaction, error)

SetWithdrawalSecurityPeriod sets the period after which a non-operator address can send a transaction to the exchange smart-contract to withdraw their funds. This acts as security mechanism to prevent the operator of the exchange from holding funds

func (*Exchange) TokenBalance

func (e *Exchange) TokenBalance(trader Address, token Address) (*big.Int, error)

TokenBalance returns the Exchange token balance of the given token at the given account address. Note: This is not the token BalanceOf() function, it's the balance of tokens that have been deposited in the exchange smart contract.

func (*Exchange) Trade

func (e *Exchange) Trade(o *Order, t *Trade) (*types.Transaction, error)

Trade executes a settlements transaction. The order and trade payloads need to be signed respectively by the Maker and the Taker of the trade. Only the operator account can send a Trade function to the Exchange smart contract.

func (*Exchange) Withdraw

func (e *Exchange) Withdraw(w *Withdrawal) (*types.Transaction, error)

Withdraw executes a normal withdraw transaction. This withdraws tokens or ether from the exchange and returns them to the payload Receiver. Only an operator account can send a withdraw transaction

func (*Exchange) WithdrawalSecurityPeriod

func (e *Exchange) WithdrawalSecurityPeriod() (*big.Int, error)

WithdrawalSecurityPeriod is the period after which a non-operator account can withdraw their funds from the exchange smart contract.

type Fee

type Fee *big.Int

Fee alias represents a feeTake or a feeMake in an Order object

type Message

type Message struct {
	MessageType MessageType `json:"messageType"`
	Payload     Payload     `json:"payload"`
}

func (*Message) String

func (m *Message) String() string

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(b []byte) error

type MessageType

type MessageType string

type Nonce

type Nonce *big.Int

Nonce alias type represents the number of transactions of an Ethereum account

type Operator

type Operator struct {
	Admin              *Wallet
	Exchange           *Exchange
	Engine             *TradingEngine
	EthereumClient     *ethclient.Client
	Params             *OperatorParams
	Chain              bind.ContractBackend
	TxQueue            []Hash
	ErrorChannel       chan *interfaces.ExchangeLogError
	TradeChannel       chan *interfaces.ExchangeLogTrade
	CancelOrderChannel chan *interfaces.ExchangeLogCancelOrder
	OrderTradePairs    map[Hash]*OrderTradePair
}

Operator manages the transaction queue that will eventually be sent to the exchange contract. The Operator Wallet must be equal to the account that initially deployed the exchange contract or an address with operator rights on the contract - Admin is the wallet that sends the transactions to the exchange smart-contract - EthereumClient contains - Params contains the - Chain seems to be deprecated - TxLogs seems to be deprecated - ErrorChannel, TradeChannel and CancelOrderChannel listen and pipes smart-contract to the engine handler goroutine - ErrorLogs, TradeLogs and CancelOrderLogs listen on the - OrderTradePairs contains a mapping of the current trade hashes that have been sent to the contract. - ErrorLogs, TradeLogs and CancelOrderLogs don't seem to be used as of now

func NewOperator

func NewOperator(config *OperatorConfig) (*Operator, error)

NewOperator creates a new operator struct. It creates an exchange contract instance from the provided address. The error and trade events are received in the ErrorChannel and TradeChannel. Upon receiving errors and trades in their respective channels, event payloads are sent to the associated order maker and taker sockets through the through the event channel on the Order and Trade struct. In addition, an error event cancels the trade in the trading engine and makes the order available again.

func (*Operator) AddTradeToExecutionList

func (op *Operator) AddTradeToExecutionList(o *Order, t *Trade) error

AddTradeToExecutionList adds a new trade to the execution list. If the execution list is empty (= contains 1 element after adding the transaction hash), the given order/trade pair gets executed. If the tranasction queue is full, we return an error. Ultimately we want to account send the transaction to another queue that is handled by another ethereum account

func (*Operator) DepositEther

func (op *Operator) DepositEther(val *big.Int) (*types.Transaction, error)

DepositEther deposits ether into the exchange smart-contract. A priori this function is not supposed to be called by the exchange operator

func (*Operator) DepositToken

func (op *Operator) DepositToken(token Address, amount *big.Int) (*types.Transaction, error)

DepositToken deposits tokens into the exchange smart-contract. A priori this function is not supposed to be called by the exchange operator

func (*Operator) EtherBalance

func (op *Operator) EtherBalance(account Address) (*big.Int, error)

EtherBalance returns the Exchange ether balance of the given account address. Note: This is not the current ether balance of the given ether address. It's the balance of ether that has been deposited in the exchange smart contract.

func (*Operator) ExecuteTrade

func (op *Operator) ExecuteTrade(o *Order, t *Trade) (*types.Transaction, error)

Trade executes a settlements transaction. The order and trade payloads need to be signed respectively by the Maker and the Taker of the trade. Only the operator account can send a Trade function to the Exchange smart contract.

func (*Operator) FeeAccount

func (op *Operator) FeeAccount() (Address, error)

FeeAccount is the Ethereum towards the exchange trading fees are sent

func (*Operator) Operator

func (op *Operator) Operator(addr Address) (bool, error)

Operator returns true if the given address is an operator of the exchange and returns false otherwise

func (*Operator) SecurityWithdraw

func (op *Operator) SecurityWithdraw(w *Wallet, token Address, amount *big.Int) (*types.Transaction, error)

SecurityWithdraw executes a security withdraw transaction. Security withdraw transactions can only be executed after the security withdrawal period has ended. A priori, this function should not be called by the operator account itself

func (*Operator) SetCustomSender

func (op *Operator) SetCustomSender(w *Wallet)

SetCustomSender updates the sender address address to the exchange contract

func (*Operator) SetDefaultTxOptions

func (op *Operator) SetDefaultTxOptions()

SetDefaultTxOptions resets the transaction value to 0

func (*Operator) SetFeeAccount

func (op *Operator) SetFeeAccount(account Address) (*types.Transaction, error)

SetFeeAccount sets the fee account of the exchange contract. The fee account receives the trading fees whenever a trade is settled.

func (*Operator) SetOperator

func (op *Operator) SetOperator(account Address, isOperator bool) (*types.Transaction, error)

SetOperator updates the operator settings of the given address. Only addresses with an operator access can execute Withdraw and Trade transactions to the Exchange smart contract

func (*Operator) SetTxValue

func (op *Operator) SetTxValue(value *big.Int)

SetTxValue sets the transaction ether value

func (*Operator) SetWithdrawalSecurityPeriod

func (op *Operator) SetWithdrawalSecurityPeriod(p *big.Int) (*types.Transaction, error)

SetWithdrawalSecurityPeriod sets the period after which a non-operator address can send a transaction to the exchange smart-contract to withdraw their funds. This acts as security mechanism to prevent the operator of the exchange from holding funds

func (*Operator) TokenBalance

func (op *Operator) TokenBalance(account Address, token Address) (*big.Int, error)

TokenBalance returns the Exchange token balance of the given token at the given account address. Note: This is not the token BalanceOf() function, it's the balance of tokens that have been deposited in the exchange smart contract.

func (*Operator) Validate

func (op *Operator) Validate() error

Validate checks that the operator configuration is sufficient.

func (*Operator) WaitMined

func (op *Operator) WaitMined(tx *types.Transaction) (*types.Receipt, error)

WaitMined blocks the current the current goroutine execution until the given transaction gets mined on the blockchain the operator is connected to

func (*Operator) Withdraw

func (op *Operator) Withdraw(w *Withdrawal) (*types.Transaction, error)

Withdraw executes a normal withdraw transaction. This withdraws tokens or ether from the exchange and returns them to the payload Receiver. Only an operator account can send a withdraw transaction

func (*Operator) WithdrawalSecurityPeriod

func (op *Operator) WithdrawalSecurityPeriod() (*big.Int, error)

WithdrawalSecurityPeriod is the period after which a non-operator account can withdraw their funds from the exchange smart contract.

type OperatorConfig

type OperatorConfig struct {
	Admin          *Wallet         `json:"admin"`
	Exchange       common.Address  `json:"exchange"`
	OperatorParams *OperatorParams `json:"operatorParams"`
}

func (*OperatorConfig) String

func (c *OperatorConfig) String() string

type OperatorParams

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

OperatorParams contains numerical values that define how the operator should send transcations. rpcURL is the url of the ethereum node. By default it is ws://localhost:8546. For non-websocket (not supported a priori) http://localhost:8545

type Order

type Order struct {
	Id        uint64    `json:"id,omitempty"`
	OrderType OrderType `json:"orderType,omitempty"`

	ExchangeAddress Address    `json:"exchangeAddress,omitempty"`
	Maker           Address    `json:"maker,omitempty"`
	TokenBuy        Address    `json:"tokenBuy,omitempty"`
	TokenSell       Address    `json:"tokenSell,omitempty"`
	SymbolBuy       string     `json:"symbolBuy,omitempty"`
	SymbolSell      string     `json:"symbolSell,omitempty"`
	AmountBuy       *big.Int   `json:"amountBuy,omitempty"`
	AmountSell      *big.Int   `json:"amountSell,omitempty"`
	Expires         *big.Int   `json:"expires,omitempty"`
	Nonce           *big.Int   `json:"nonce,omitempty"`
	FeeMake         *big.Int   `json:"feeMake,omitempty"`
	FeeTake         *big.Int   `json:"feeTake,omitempty"`
	Signature       *Signature `json:"signature,omitempty"`
	PairID          Hash       `json:"pairID,omitempty"`
	Hash            Hash       `json:"hash,omitempty"`
	Price           uint64     `json:"price,omitempty"`
	Amount          uint64     `json:"amount,omitempty"`
	// contains filtered or unexported fields
}

func (*Order) ComputeHash

func (o *Order) ComputeHash() Hash

ComputeHash calculates the order hash

func (*Order) Decode

func (o *Order) Decode(order map[string]interface{}) error

func (*Order) DecodeOrderPayload

func (o *Order) DecodeOrderPayload(p Payload) error

DecodeOrderPayload takes a payload retrieved from a JSON and decodes it into an Order structure

func (*Order) MarshalJSON

func (o *Order) MarshalJSON() ([]byte, error)

func (*Order) NewOrderCanceledEvent

func (o *Order) NewOrderCanceledEvent() *Event

NewOrderCanceled is called when an order is called

func (*Order) NewOrderExecutedEvent

func (o *Order) NewOrderExecutedEvent(tx *types.Transaction) *Event

NewOrderExecuted is called when an order is executed meaning that the operator has performed a blockchain transaction and is currently waiting for the transaction to resolve.

func (*Order) NewOrderFilledEvent

func (o *Order) NewOrderFilledEvent(t *Trade) *Event

NewOrderPartiallyFilledEvent is called when an order is mached (as taker) This does not mean that the order is executed on the blockchain as of yet.

func (*Order) NewOrderMatchedEvent

func (o *Order) NewOrderMatchedEvent() *Event

NewOrderMatchedEvent is called when an order is matched (as taker) in the orderbook. This does not mean that the order is executed on the blockchain as of yet.

func (*Order) NewOrderPartiallyFilledEvent

func (o *Order) NewOrderPartiallyFilledEvent() *Event

NewOrderPartiallyFilledEvent is called when an order is mached (as taker) partially. This does not mean that the order is executed on the blockchain as of yet.

func (*Order) NewOrderPlacedEvent

func (o *Order) NewOrderPlacedEvent() *Event

NewOrderPlacedEvent is called when an order is first placed in the orderbook.

func (*Order) NewOrderTxError

func (o *Order) NewOrderTxError(t *Trade, errorId uint8) *Event

NewOrderTransactionError is called when the operator receives an error event from the exchange smart contract.

func (*Order) NewOrderTxSuccess

func (o *Order) NewOrderTxSuccess(t *Trade, tx *types.Transaction) *Event

NewOrderTransactionSuccessful is called when the operator receives confirmation that a trade was carried out successfully.

func (*Order) PriceInfo

func (o *Order) PriceInfo() string

PriceInfo prints the following information: -ID -BuyTokenAmount -SellTokenAmount -Price -Amount -Type

func (*Order) Sign

func (o *Order) Sign(w *Wallet) error

Sign first calculates the order hash, then computes a signature of this hash with the given wallet

func (*Order) String

func (o *Order) String() string

Stringer method for order

func (*Order) TokenInfo

func (o *Order) TokenInfo() string

TokenInfo prints the following information: -BuyToken (address) -SellToken (address) -BuyToken Symbol -SellToken Symbol

func (*Order) UnmarshalJSON

func (o *Order) UnmarshalJSON(b []byte) error

func (*Order) ValidateOrder

func (o *Order) ValidateOrder() (bool, error)

ValidateOrder checks the following elements: Order Type needs to be equal to BUY or SELL Exchange Address needs to be correct AmountBuy and AmountSell need to be positive OrderHash needs to be correct

func (*Order) VerifySignature

func (o *Order) VerifySignature() (bool, error)

VerifySignature checks that the order signature corresponds to the address in the maker field

type OrderBook

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

The orderbook keeps track of the maximum bid and minimum ask The orderIndex is a mapping of OrderIDs to pointers so that we can easily cancel outstanding orders prices is an array of all possible pricepoints actions is a channels to report some action to a handler as they occur

func NewOrderBook

func NewOrderBook(actions chan *Action) *OrderBook

NewOrderbook returns a default orderbook struct

func (*OrderBook) AddOrder

func (ob *OrderBook) AddOrder(o *Order)

AddOrder adds a new order to the orderbook. First it checks whether the order is a buy or a sell Depending on the order type, the orderbook tries to fill the order against the existing orders of the opposite type in the orderbook. If any amount is left, the orderbook opens an additional order with the remaining amount

func (*OrderBook) CancelOrder

func (ob *OrderBook) CancelOrder(h Hash)

CancelOrder removes an order from the orderbook

func (*OrderBook) CancelTrade

func (ob *OrderBook) CancelTrade(t *Trade)

CancelTrade is called when a blockchain transaction execution fails. Then the order needs to be re-added to the orderbook.

func (*OrderBook) Done

func (ob *OrderBook) Done()

func (*OrderBook) FillBuy

func (ob *OrderBook) FillBuy(o *Order)

FillBuy tries to fill a BUY order with the existing sell orders. In the case, the order price is under the ask price, no orders will be found and the loops thus ends Otherwise, FillBuy loops through the different pricepoints by increasing the ask price whenever an order is matched

func (*OrderBook) FillSell

func (ob *OrderBook) FillSell(o *Order)

FillSell functions similarly to the FillBuy function

func (*OrderBook) GetLogs

func (ob *OrderBook) GetLogs() []*Action

func (*OrderBook) String

func (ob *OrderBook) String() string

type OrderCancel

type OrderCancel struct {
	OrderId   uint64     `json:"orderId"`
	PairID    Hash       `json:"pair"`
	OrderHash Hash       `json:"orderHash"`
	Hash      Hash       `json:"hash"`
	Signature *Signature `json:"signature"`
}

OrderCancel is a group of params used for canceling an order previously sent to the matching engine. The OrderId and OrderHash must correspond to the same order. To be valid and be able to be processed by the matching engine, the OrderCancel must include a signature by the Maker of the order corresponding to the OrderHash.

func NewOrderCancel

func NewOrderCancel() *OrderCancel

NewOrderCancel returns a new empty OrderCancel object

func (*OrderCancel) ComputeHash

func (oc *OrderCancel) ComputeHash() Hash

func (*OrderCancel) Decode

func (oc *OrderCancel) Decode(orderCancel map[string]interface{}) error

Decode takes a payload previously unmarshalled from a JSON byte string and decodes it into an OrderCancel object

func (*OrderCancel) MarshalJSON

func (oc *OrderCancel) MarshalJSON() ([]byte, error)

MarshalJSON returns the json encoded byte array representing the OrderCancel struct

func (*OrderCancel) Sign

func (oc *OrderCancel) Sign(w *Wallet) error

Sign first computes the order cancel hash, then signs and sets the signature

func (*OrderCancel) String

func (oc *OrderCancel) String() string

func (*OrderCancel) UnmarshalJSON

func (oc *OrderCancel) UnmarshalJSON(b []byte) error

UnmarshalJSON creates an OrderCancel object from a json byte string

func (*OrderCancel) VerifySignature

func (oc *OrderCancel) VerifySignature(o *Order) (bool, error)

VerifySignature returns a true value if the OrderCancel object signature corresponds to the Maker of the given order

type OrderCancelPayload

type OrderCancelPayload struct {
	OrderCancel *OrderCancel `json:"orderCancel"`
}

CancelOrderPayload contains both an OrderId and the pairID of the corresponding orderbook/token pair

func NewOrderCancelPayload

func NewOrderCancelPayload() *OrderCancelPayload

NewOrderCancelPayload creates a new empty OrderCancelPayload

func (*OrderCancelPayload) DecodeOrderCancelPayload

func (ocp *OrderCancelPayload) DecodeOrderCancelPayload(p Payload) error

DecodeOrderCancelPayload takes a payload that was previously unmarshalled from a JSON byte string and decodes it into an OrderCancelPayload

type OrderExecutedMessage

type OrderExecutedMessage struct {
	MessageType MessageType          `json:"messageType"`
	Payload     OrderExecutedPayload `json:"payload"`
}

type OrderExecutedPayload

type OrderExecutedPayload struct {
	Order *Order      `json:"order"`
	Tx    common.Hash `json:"tx"`
}

OrderExecutedPayload contains the order that was just matched and a transaction hash. The client can use this payload to follow the state of the transaction. This payload may change in the future

func NewOrderExecutedPayload

func NewOrderExecutedPayload() *OrderExecutedPayload

NewOrderExecutedPayload creates a new empty OrderExecutedPayload

func (*OrderExecutedPayload) DecodeOrderExecutedPayload

func (oep *OrderExecutedPayload) DecodeOrderExecutedPayload(p Payload) error

DecodeOrderExecutedPayload takes a payload that was previously unmarshalled from a JSON byte string and decodes it into a OrderExecutedPayload

type OrderFactory

type OrderFactory struct {
	Client         *ethclient.Client
	Pair           *TokenPair
	Wallet         *Wallet
	Exchange       common.Address
	Params         *OrderParams
	TradeNonce     uint64
	OrderNonce     uint64
	CurrentOrderID uint64
	NonceGenerator *rand.Rand
}

Orderfactory simplifies creating orders, trades and cancelOrders objects Pair is the token pair for which the order is created Exchange is the Ethereum address of the exchange smart contract CurrentOrderID increments for each new order

func NewOrderFactory

func NewOrderFactory(p *TokenPair, w *Wallet) *OrderFactory

NewOrderFactory returns an order factory from a given token pair and a given wallet TODO: Refactor this function to send back an error

func (*OrderFactory) NewBuyOrder

func (f *OrderFactory) NewBuyOrder(price uint64, amount uint64) (*Order, error)

NewBuyOrder returns a new order with the given params. The order is signed by the factory wallet NewBuyOrder computes the AmountBuy and AmountSell parameters from the given amount and price. Currently, the amount, price and order type are also kept. This could be amended in the future (meaning we would let the engine compute OrderBuy, Amount and Price. Ultimately this does not really matter except maybe for convenience/readability purposes)

func (*OrderFactory) NewBuyOrderWithEvent

func (f *OrderFactory) NewBuyOrderWithEvent(price uint64, amount uint64) (*Order, error)

NewSellOrderWithEvents adds an event channel to the trade returned by NewSellOrder

func (*OrderFactory) NewCancelOrderMessage

func (f *OrderFactory) NewCancelOrderMessage(o *Order) (*Message, error)

NewCancelOrderMessage creates a new OrderCancelMessage from a given order

func (*OrderFactory) NewOrder

func (f *OrderFactory) NewOrder(tokenBuy Token, amountBuy int64, tokenSell Token, amountSell int64) (*Order, error)

NewOrder returns a new order with the given params. The order is signed by the factory wallet. Currently the nonce is chosen randomly which will be changed in the future

func (*OrderFactory) NewOrderCancel

func (f *OrderFactory) NewOrderCancel(o *Order) (*OrderCancel, error)

NewOrderCancel creates a new OrderCancel object from a given order

func (*OrderFactory) NewOrderMessage

func (f *OrderFactory) NewOrderMessage(tokenBuy Token, amountBuy int64, tokenSell Token, amountSell int64) (*Message, *Order, error)

NewOrderMessage creates an order with the given params and returns a new PLACE_ORDER message

func (*OrderFactory) NewOrderWithEvents

func (f *OrderFactory) NewOrderWithEvents(tokenBuy Token, amountBuy int64, tokenSell Token, amountSell int64) (*Order, error)

func (*OrderFactory) NewSellOrder

func (f *OrderFactory) NewSellOrder(price uint64, amount uint64) (*Order, error)

NewBuyOrder returns a new order with the given params. The order is signed by the factory wallet NewBuyOrder computes the AmountBuy and AmountSell parameters from the given amount and price. Currently, the amount, price and order type are also kept. This could be amended in the future (meaning we would let the engine compute OrderBuy, Amount and Price. Ultimately this does not really matter except maybe for convenience/readability purposes)

func (*OrderFactory) NewSellOrderWithEvent

func (f *OrderFactory) NewSellOrderWithEvent(price uint64, amount uint64) (*Order, error)

NewSellOrderWithEvents adds an event channel to the trade returned by NewSellOrder

func (*OrderFactory) NewTrade

func (f *OrderFactory) NewTrade(o *Order, amount int64) (*Trade, error)

NewTrade returns a new trade with the given params. The trade is signed by the factory wallet. Currently the nonce is chosen randomly which will be changed in the future

func (*OrderFactory) NewTradeWithEvents

func (f *OrderFactory) NewTradeWithEvents(o *Order, amount int64) (*Trade, error)

NewTradeWithEvents adds an event channel to the trade returned by NewTrade

func (*OrderFactory) SetExchangeAddress

func (f *OrderFactory) SetExchangeAddress(exchange common.Address) error

SetExchangeAddress changes the default exchange address for orders created by this factory

type OrderFilledMessage

type OrderFilledMessage struct {
	MessageType MessageType  `json:"messageType"`
	Payload     OrderPayload `json:"payload"`
}

type OrderFilledPayload

type OrderFilledPayload struct {
	TakerOrder *Order `json:"takerOrder"`
	MakerOrder *Order `json:"makerOrder"`
}

OrderFilledPayload contains a TakerOrder and MakerOrder that corresponds to an order pair that was just matched by the matching engine

func NewOrderFilledPayload

func NewOrderFilledPayload() *OrderFilledPayload

NewOrderFilledPayload creates a new empty OrderFilledPayload

func (*OrderFilledPayload) DecodeOrderFilledPayload

func (d *OrderFilledPayload) DecodeOrderFilledPayload(p Payload) error

DecodeOrderFilledPayload takes a payload unmarshalled from a JSON byte string and decodes it into an OrderFilledPayload

type OrderParams

type OrderParams struct {
	FeeMake *big.Int
	FeeTake *big.Int
	Nonce   *big.Int
	Expires *big.Int
}

OrderParams groups FeeMake, FeeTake, Nonce, Exipres FeeMake and FeeTake are the default fees imposed on makers and takers Nonce is the ethereum account nonce that tracks the numbers of transactions for the order factory account Expires adds a timeout after which an order can no longer be matched

type OrderPartiallyFilledMessage

type OrderPartiallyFilledMessage struct {
	MessageType MessageType  `json:"messageType"`
	Payload     OrderPayload `json:"payload"`
}

type OrderPayload

type OrderPayload struct {
	Order *Order `json:"order"`
}

OrderPayload is a simple payload which consists of a single order

type OrderPlacedMessage

type OrderPlacedMessage struct {
	MessageType MessageType  `json:"messageType"`
	Payload     OrderPayload `json:"payload"`
}

Messages from server to client

type OrderStatus

type OrderStatus int
const (
	NEW OrderStatus = iota
	OPEN
	PARTIAL_FILLED
	FILLED
	CANCELLED
	PENDING
)

func (*OrderStatus) MarshalJSON

func (orderStatus *OrderStatus) MarshalJSON() ([]byte, error)

func (*OrderStatus) UnmarshalJSON

func (orderStatus *OrderStatus) UnmarshalJSON(data []byte) error

type OrderTradePair

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

type OrderType

type OrderType int
const (
	BUY OrderType = iota
	SELL
)

func (*OrderType) MarshalJSON

func (orderType *OrderType) MarshalJSON() ([]byte, error)

func (*OrderType) UnmarshalJSON

func (orderType *OrderType) UnmarshalJSON(data []byte) error

type Payload

type Payload interface{}

Payload is the generic that represents websocket messages

type PlaceOrderMesage

type PlaceOrderMesage struct {
	MessageType MessageType  `json:"messageType"`
	Payload     OrderPayload `json:"payload"`
}

Messages from client to server

type PricePoint

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

Pricepoint contains pointers to the first and the last order entered at that price

func (*PricePoint) Insert

func (p *PricePoint) Insert(order *Order)

Insert adds a new order to a pricepoint in the orderbook.

type Server

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

Server type handles a mapping of socket structs and the trading engine

func NewServer

func NewServer() *Server

NewServer returns a a new empty Server instance. Note: Currently note sure whether actionLogs and txLogs are still used

func (*Server) OpenWebsocketConnection

func (s *Server) OpenWebsocketConnection(w http.ResponseWriter, r *http.Request)

OpenWebsocketConnection opens a new websocket connection

func (*Server) RegisterNewPair

func (s *Server) RegisterNewPair(w http.ResponseWriter, r *http.Request)

RegisterNewPair registers a new pair on the trading engine In the final version, the token pair will be written to the database

func (*Server) RegisterNewQuoteToken

func (s *Server) RegisterNewQuoteToken(w http.ResponseWriter, r *http.Request)

RegisterNewQuoteToken registers a new quote token on the trading engine In the final version, the quote token will be written to the database

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) SetupCurrencies

func (s *Server) SetupCurrencies(quotes Tokens, pairs TokenPairs, done chan bool)

Setup registers a list of quote tokens and token pairs

func (*Server) SetupTradingEngine

func (s *Server) SetupTradingEngine(config *OperatorConfig, quotes Tokens, pairs TokenPairs, done chan bool) error

func (*Server) Start

func (s *Server) Start()

type Signature

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

asdfasdf

func NewSignature

func NewSignature(b []byte) (*Signature, error)

func Sign

func Sign(hash common.Hash, privKey *ecdsa.PrivateKey) (*Signature, error)

Sign calculates the EDCSA signature corresponding of a hashed message from a given private key

func SignHash

func SignHash(hash common.Hash, privKey *ecdsa.PrivateKey) (*Signature, error)

SignHash also calculates the EDCSA signature of a message but adds an "Ethereum Signed Message" prefix https://github.com/ethereum/EIPs/issues/191

func (*Signature) MarshalSignature

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

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 SignedDataMessage

type SignedDataMessage struct {
	MessageType MessageType       `json:"messageType"`
	Payload     SignedDataPayload `json:"payload"`
}

type SignedDataPayload

type SignedDataPayload struct {
	Trade *Trade `json:"trade"`
}

SignedDataPayload contains a trade that was just signed by the client

type Socket

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

Socket acts as a hub that handles messages from the client application and responses from the server matching engine.

type Token

type Token struct {
	Symbol  string  `json:"symbol"`
	Address Address `json:"address"`
}

type TokenAmount

type TokenAmount *big.Int

TokenAmount alias represents the number of tokens (for a certain Token in a certain Address)

type TokenPair

type TokenPair struct {
	QuoteToken Token `json:"quoteToken"`
	BaseToken  Token `json:"baseToken"`
	ID         Hash  `json:"id"`
}

func NewPair

func NewPair(baseToken, quoteToken Token) TokenPair

func (*TokenPair) ComputeID

func (p *TokenPair) ComputeID() Hash

func (*TokenPair) ComputeOrderPrice

func (p *TokenPair) ComputeOrderPrice(o *Order) error

ComputeOrderPrice calculates the (Amount, Price) tuple corresponding to the (AmountBuy, TokenBuy, AmountSell, TokenSell) quadruplet

func (*TokenPair) String

func (p *TokenPair) String() string

type TokenPairs

type TokenPairs map[string]TokenPair

type Tokens

type Tokens map[string]Token

type Trade

type Trade struct {
	OrderHash  Hash       `json:"orderHash"`
	Amount     *big.Int   `json:"amount"`
	TradeNonce *big.Int   `json:"tradeNonce"`
	Taker      Address    `json:"taker"`
	Signature  *Signature `json:"signature"`
	Hash       Hash       `json:"hash"`
	PairID     Hash       `json:"pairID"`
	// contains filtered or unexported fields
}

Trade struct holds arguments corresponding to a "Taker Order" To be valid an accept by the matching engine (and ultimately the exchange smart-contract), the trade signature must be made from the trader Maker account

func NewTrade

func NewTrade(o *Order, amount *big.Int, taker Address) *Trade

NewTrade returns a new unsigned trade corresponding to an Order, amount and taker address

func (*Trade) ComputeHash

func (t *Trade) ComputeHash() Hash

ComputeTradeHash returns hashes the trade

The OrderHash, Aounot, Taker and TradeNonce attributes must be set before attempting to compute the trade hash

func (*Trade) Decode

func (t *Trade) Decode(trade map[string]interface{}) error

DecodeTrade takes a payload previously unmarshalled from a JSON byte string and decodes it into an Trade object

func (*Trade) MarshalJSON

func (t *Trade) MarshalJSON() ([]byte, error)

MarshalJSON returns the json encoded byte array representing the trade struct

func (*Trade) NewTradeExecutedEvent

func (t *Trade) NewTradeExecutedEvent(tx *types.Transaction) *Event

NewTradeExecutedEvent is called when a blockchain transaction is created with the trade as input

func (*Trade) NewTradeTxError

func (t *Trade) NewTradeTxError(o *Order, errId uint8) *Event

NewTradeTransactionError is called when the operator receives a error event meaning that the transaction was interrupted.

func (*Trade) NewTradeTxSuccess

func (t *Trade) NewTradeTxSuccess(o *Order, tx *types.Transaction) *Event

NewTradeTransactionSuccessful is called when the operator receives a trade event meaning that the exchange was performed successfully on the chain.

func (*Trade) Sign

func (t *Trade) Sign(w *Wallet) error

Sign calculates ands sets the trade hash and signature with the given wallet

func (*Trade) String

func (t *Trade) String() string

String return the standard trade format string

func (*Trade) UnmarshalJSON

func (t *Trade) UnmarshalJSON(b []byte) error

UnmarshalJSON creates a trade object from a json byte string

func (*Trade) Validate

func (t *Trade) Validate() error

Valid verifies that all the fields of a struct are set and not null

func (*Trade) VerifySignature

func (t *Trade) VerifySignature() (bool, error)

VerifySignature verifies that the trade is correct and corresponds to the trade Taker address

type TradeExecutedMessage

type TradeExecutedMessage struct {
	MessageType MessageType          `json:"messageType"`
	Payload     TradeExecutedPayload `json:"payload"`
}

type TradeExecutedPayload

type TradeExecutedPayload struct {
	Trade *Trade      `json:"trade"`
	Tx    common.Hash `json:tx"`
}

TradeExecutedPayload contains a trade that matched and a transaction hash associated with the transaction on that trade. The client can use this paylaod to follow the state of the transaction. This payload may change in the future to include the order in addition to the trade.

func NewTradeExecutedPayload

func NewTradeExecutedPayload() *TradeExecutedPayload

NewTradeExecutedPayload creates a new empty TradeExecutedPayload

func (*TradeExecutedPayload) DecodeTradeExecutedPayload

func (tep *TradeExecutedPayload) DecodeTradeExecutedPayload(p Payload) error

DecodeTradeExecutedPayload takes a payload that was previously unmarshalled from a JSON byte string and decodes it into a TradeExecutedPayload. Developer note: For some reason there is currently a difference between DecodeTradeExecutedPayload and DeodeOrderExecutedPayload In the first one, the transaction hash is saved under the "tx" key while it is saved under the "Tx" on the second one.

type TradePayload

type TradePayload struct {
	Order *Order `json:"order"`
	Trade *Trade `json:"trade"`
}

TradePayload contains both an order and a trade object corresponding to that order.

func NewTradePayload

func NewTradePayload() *TradePayload

NewTradePayload creates a new empty TradePayload

func (*TradePayload) DecodeTradePayload

func (tp *TradePayload) DecodeTradePayload(p Payload) error

DecodeTradePayload takes a payload retrieved from a JSON file and decodes it into a Trade struct

type TradingEngine

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

TradingEngine manages all the different orderbooks through a TokenPair->OrderBook It also holds the list of current quote tokens and token pairs quoteTokens is a mapping of token addresses to Token structs (address + symbol) pairs is a mapping of token pair ID to corresponding TokenPair structs

func NewTradingEngine

func NewTradingEngine() *TradingEngine

NewTradingEngine returns an empty TradingEngine struct

func (*TradingEngine) AddOrder

func (e *TradingEngine) AddOrder(o *Order) error

AddOrder computes the order price point

func (*TradingEngine) CancelOrder

func (e *TradingEngine) CancelOrder(oc *OrderCancel) error

CancelOrder cancels an order that was previously sent to the orderbook. To be valid, the orderCancel struct, need to correspond an existing token pair and order. The orderCancel's signature needs to be a valid signature from the order Maker.

func (*TradingEngine) CancelTrade

func (e *TradingEngine) CancelTrade(t *Trade) error

func (*TradingEngine) CloseOrderBook

func (e *TradingEngine) CloseOrderBook(pairID Hash) (bool, error)

CloseOrderBook closes the orderbook associated to a pair ID

func (*TradingEngine) ComputeOrderPrice

func (e *TradingEngine) ComputeOrderPrice(o *Order) error

ComputeOrderPrice calculates the (Amount, Price) tuple corresponding to the (AmountBuy, TokenBuy, AmountSell, TokenSell) quadruplet

func (*TradingEngine) ExecuteOrder

func (e *TradingEngine) ExecuteOrder(t *Trade) error

Execute Order adds the order to the blockchain transaction execution queue

func (*TradingEngine) PrintLogs

func (e *TradingEngine) PrintLogs()

PrintLogs prints the logs for each token pair registered in the orderbook

func (*TradingEngine) RegisterNewPair

func (e *TradingEngine) RegisterNewPair(p TokenPair, done chan<- bool) error

RegisterNewPair registers a new token pair on the engine To be valid, the quote token of the new token pair needs to be registered in the quote tokens of the engine

func (*TradingEngine) RegisterNewQuoteToken

func (e *TradingEngine) RegisterNewQuoteToken(t Token) error

RegisterNewQuoteToken registers a new quote token on the engine Only an authorized user should be allowed to register a new token on the engine (TODO)

func (*TradingEngine) RegisterOperator

func (e *TradingEngine) RegisterOperator(config *OperatorConfig) error

RegisterOperator registers a new operator on the engine. The operator is the account that sends the blockchain transaction associated to an order/trade to the exchange smart contract

func (*TradingEngine) TokenBalance

func (e *TradingEngine) TokenBalance(owner Address, token Address) (*big.Int, error)

type TxErrorPayload

type TxErrorPayload struct {
	Order   *Order `json:"order"`
	Trade   *Trade `json:"trade"`
	ErrorId uint8  `json:"errorId"`
}

TxErrorPayload contains and order, a trade and an error id. The error id corresponds to the error id

func NewTxErrorPayload

func NewTxErrorPayload() *TxErrorPayload

NewTxErrorPayload creates a new empty TxErrorPayload

func (*TxErrorPayload) DecodeTxErrorPayload

func (d *TxErrorPayload) DecodeTxErrorPayload(p Payload) error

DecodeTxErrorPayload takes a payload that was previously unmarshalled from a JSON byte string and decodes it into a TxErrorPayload.

type TxSuccessPayload

type TxSuccessPayload struct {
	Order *Order      `json:"order"`
	Trade *Trade      `json:"trade"`
	Tx    common.Hash `json:"tx"`
}

TxSuccessPayload contains an order, a trade and the transaction hash of the successful blockchain transaction.

func NewTxSuccessPayload

func NewTxSuccessPayload() *TxSuccessPayload

NewTxSuccessPayload creates a new empty TxSuccessPayload

func (*TxSuccessPayload) DecodeTxSuccessPayload

func (d *TxSuccessPayload) DecodeTxSuccessPayload(p Payload) error

type Wallet

type Wallet struct {
	Address    Address
	PrivateKey *ecdsa.PrivateKey
}

Wallet holds both the address and the private key of an ethereum account

func NewWallet

func NewWallet() *Wallet

NewWallet returns a new wallet object corresponding to a random private key

func NewWalletFromPrivateKey

func NewWalletFromPrivateKey(key string) *Wallet

NewWalletFromPrivateKey returns a new wallet object corresponding to a given private key

func (*Wallet) GetAddress

func (w *Wallet) GetAddress() string

GetAddress returns the wallet address

func (*Wallet) GetPrivateKey

func (w *Wallet) GetPrivateKey() string

GetPrivateKey returns the wallet private key

func (*Wallet) NewOrder

func (w *Wallet) NewOrder(id, amountBuy, amountSell uint64, p TokenPair, ot OrderType) (*Order, error)

NewOrder (DEPRECATED - use the order factory instead) creates a new order from a wallet, compute the order hash and signs it with the wallet private key

func (*Wallet) NewTrade

func (w *Wallet) NewTrade(o *Order, amount uint64) (*Trade, error)

NewTrade (DEPRECATED - use the order factory instead) creates a new trade from a wallet and a given order, compute the trade hash and signs it with the wallet private key

func (*Wallet) SignHash

func (w *Wallet) SignHash(h Hash) (*Signature, error)

SignHash signs a hashed message with a wallet private key and returns it as a Signature object

func (*Wallet) SignTrade

func (w *Wallet) SignTrade(t *Trade) error

SignTrade signs and sets the signature of a trade with a wallet private key

type Withdrawal

type Withdrawal struct {
	ExchangeAddress Address
	Hash            Hash
	Token           Address
	Amount          *big.Int
	Trader          Address
	Receiver        Address
	Nonce           *big.Int
	Fee             *big.Int
	Signature       *Signature
}

func (*Withdrawal) ComputeWithdrawalHash

func (w *Withdrawal) ComputeWithdrawalHash() Hash

func (*Withdrawal) Sign

func (w *Withdrawal) Sign(wallet *Wallet) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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