Skip to content

Commit

Permalink
Merge pull request ethereum#695 from thanhnguyennguyen/adding-exchang…
Browse files Browse the repository at this point in the history
…es-to-trades

Adding exchanges to trades
  • Loading branch information
thanhnguyennguyen authored Sep 14, 2019
2 parents f1f62b9 + 59da526 commit cff7e12
Show file tree
Hide file tree
Showing 31 changed files with 194 additions and 4,761 deletions.
8 changes: 4 additions & 4 deletions core/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,16 +296,16 @@ func ApplyTomoXMatchedTransaction(config *params.ChainConfig, statedb *state.Sta
baseFee := common.TomoXBaseFee

for i := 0; i < len(txMatch.Trades); i++ {
price := tomox.ToBigInt(txMatch.Trades[i][tomox.TradedPrice])
quantityString := txMatch.Trades[i][tomox.TradedQuantity]
price := tomox.ToBigInt(txMatch.Trades[i][tomox.TradePrice])
quantityString := txMatch.Trades[i][tomox.TradeQuantity]
quantity := tomox.ToBigInt(quantityString)
if price.Cmp(big.NewInt(0)) <= 0 || quantity.Cmp(big.NewInt(0)) <= 0 {
return nil, 0, fmt.Errorf("trade misses important information. tradedPrice %v, tradedQuantity %v", price, quantity), false
}
makerExAddr := common.HexToAddress(txMatch.Trades[i][tomox.TradedMakerExchangeAddress])
makerExAddr := common.HexToAddress(txMatch.Trades[i][tomox.TradeMakerExchange])
makerExfee := tomox.GetExRelayerFee(makerExAddr, statedb)
makerExOwner := tomox.GetRelayerOwner(makerExAddr, statedb)
makerAddr := common.HexToAddress(txMatch.Trades[i][tomox.TradedMaker])
makerAddr := common.HexToAddress(txMatch.Trades[i][tomox.TradeMaker])
log.Debug("ApplyTomoXMatchedTransaction : trades quantityString", "i", i, "trade", txMatch.Trades[i], "price", price)
if makerExAddr != (common.Address{}) && makerAddr != (common.Address{}) {
// take relayer fee
Expand Down
7 changes: 3 additions & 4 deletions tomox/mongodb.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/hashicorp/golang-lru"
"github.com/tomochain/tomox-sdk/types"
"strings"
"time"
)
Expand Down Expand Up @@ -157,9 +156,9 @@ func (db *MongoDatabase) Put(key []byte, val interface{}, dryrun bool, blockHash
db.cacheItems.Add(cacheKey, val)

switch val.(type) {
case *types.Trade:
case *Trade:
// Put trade into "trades" collection
if err := db.CommitTrade(val.(*types.Trade)); err != nil {
if err := db.CommitTrade(val.(*Trade)); err != nil {
log.Error(err.Error())
return err
}
Expand Down Expand Up @@ -265,7 +264,7 @@ func (db *MongoDatabase) CommitOrder(cacheKey string, o *OrderItem) error {
return nil
}

func (db *MongoDatabase) CommitTrade(t *types.Trade) error {
func (db *MongoDatabase) CommitTrade(t *Trade) error {

sc := db.Session.Copy()
defer sc.Close()
Expand Down
26 changes: 13 additions & 13 deletions tomox/mongodb_encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,24 @@ package tomox
import (
"fmt"
"strconv"
"strings"
"time"

"github.com/ethereum/go-ethereum/common"
"github.com/globalsign/mgo/bson"
"github.com/tomochain/tomox-sdk/utils/math"
)

func (o *OrderItem) GetBSON() (interface{}, error) {
or := OrderItemBSON{
PairName: o.PairName,
ExchangeAddress: o.ExchangeAddress.Hex(),
UserAddress: o.UserAddress.Hex(),
BaseToken: o.BaseToken.Hex(),
QuoteToken: o.QuoteToken.Hex(),
ExchangeAddress: strings.ToLower(o.ExchangeAddress.Hex()),
UserAddress: strings.ToLower(o.UserAddress.Hex()),
BaseToken: strings.ToLower(o.BaseToken.Hex()),
QuoteToken: strings.ToLower(o.QuoteToken.Hex()),
Status: o.Status,
Side: o.Side,
Type: o.Type,
Hash: o.Hash.Hex(),
Hash: strings.ToLower(o.Hash.Hex()),
Quantity: o.Quantity.String(),
Price: o.Price.String(),
Nonce: o.Nonce.String(),
Expand Down Expand Up @@ -82,25 +82,25 @@ func (o *OrderItem) SetBSON(raw bson.Raw) error {
o.UserAddress = common.HexToAddress(decoded.UserAddress)
o.BaseToken = common.HexToAddress(decoded.BaseToken)
o.QuoteToken = common.HexToAddress(decoded.QuoteToken)
o.FilledAmount = math.ToBigInt(decoded.FilledAmount)
o.Nonce = math.ToBigInt(decoded.Nonce)
o.MakeFee = math.ToBigInt(decoded.MakeFee)
o.TakeFee = math.ToBigInt(decoded.TakeFee)
o.FilledAmount = ToBigInt(decoded.FilledAmount)
o.Nonce = ToBigInt(decoded.Nonce)
o.MakeFee = ToBigInt(decoded.MakeFee)
o.TakeFee = ToBigInt(decoded.TakeFee)
o.Status = decoded.Status
o.Side = decoded.Side
o.Type = decoded.Type
o.Hash = common.HexToHash(decoded.Hash)

if decoded.Quantity != "" {
o.Quantity = math.ToBigInt(decoded.Quantity)
o.Quantity = ToBigInt(decoded.Quantity)
}

if decoded.FilledAmount != "" {
o.FilledAmount = math.ToBigInt(decoded.FilledAmount)
o.FilledAmount = ToBigInt(decoded.FilledAmount)
}

if decoded.Price != "" {
o.Price = math.ToBigInt(decoded.Price)
o.Price = ToBigInt(decoded.Price)
}

if decoded.Signature != nil {
Expand Down
8 changes: 8 additions & 0 deletions tomox/order.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ import (
"github.com/ethereum/go-ethereum/log"
)

const (
OrderStatusNew = "NEW"
OrderStatusOpen = "OPEN"
OrderStatusPartialFilled = "PARTIAL_FILLED"
OrderStatusFilled = "FILLED"
OrderStatusCancelled = "CANCELLED"
)

// Signature struct
type Signature struct {
V byte
Expand Down
29 changes: 9 additions & 20 deletions tomox/orderbook.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,6 @@ const (
// as sequential id
SlotSegment = common.AddressLength
orderbookItemPrefix = "OB"

// trade struct field
TradedTakerOrderHash = "takerOrderHash"
TradedMakerOrderHash = "makerOrderHash"
TradedTimestamp = "timestamp"
TradedQuantity = "quantity"
TradedMakerExchangeAddress = "makerExAddr"
TradedMaker = "uAddr"
TradedBaseToken = "bToken"
TradedQuoteToken = "qToken"
TradedPrice = "tradedPrice"
)

var ErrDoesNotExist = errors.New("order doesn't exist in ordertree")
Expand Down Expand Up @@ -432,18 +421,18 @@ func (orderBook *OrderBook) processOrderList(side string, orderList *OrderList,
}

transactionRecord := make(map[string]string)
transactionRecord[TradedTakerOrderHash] = hex.EncodeToString(order.Hash.Bytes())
transactionRecord[TradedMakerOrderHash] = hex.EncodeToString(headOrder.Item.Hash.Bytes())
transactionRecord[TradedTimestamp] = strconv.FormatUint(orderBook.Timestamp, 10)
transactionRecord[TradedQuantity] = tradedQuantity.String()
transactionRecord[TradedMakerExchangeAddress] = headOrder.Item.ExchangeAddress.String()
transactionRecord[TradedMaker] = headOrder.Item.UserAddress.String()
transactionRecord[TradedBaseToken] = headOrder.Item.BaseToken.String()
transactionRecord[TradedQuoteToken] = headOrder.Item.QuoteToken.String()
transactionRecord[TradeTakerOrderHash] = hex.EncodeToString(order.Hash.Bytes())
transactionRecord[TradeMakerOrderHash] = hex.EncodeToString(headOrder.Item.Hash.Bytes())
transactionRecord[TradeTimestamp] = strconv.FormatUint(orderBook.Timestamp, 10)
transactionRecord[TradeQuantity] = tradedQuantity.String()
transactionRecord[TradeMakerExchange] = headOrder.Item.ExchangeAddress.String()
transactionRecord[TradeMaker] = headOrder.Item.UserAddress.String()
transactionRecord[TradeBaseToken] = headOrder.Item.BaseToken.String()
transactionRecord[TradeQuoteToken] = headOrder.Item.QuoteToken.String()
// maker price is actual price
// taker price is offer price
// tradedPrice is always actual price
transactionRecord[TradedPrice] = headOrder.Item.Price.String()
transactionRecord[TradePrice] = headOrder.Item.Price.String()

trades = append(trades, transactionRecord)
}
Expand Down
29 changes: 15 additions & 14 deletions tomox/tomox.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"errors"
"fmt"
"github.com/ethereum/go-ethereum/core/state"
sdktypes "github.com/tomochain/tomox-sdk/types"
"math/big"
"runtime"
"strings"
Expand Down Expand Up @@ -1232,7 +1231,7 @@ func (tomox *TomoX) SyncDataToSDKNode(txDataMatch TxDataMatch, txHash common.Has
log.Error("SDK node decode order failed", "txDataMatch", txDataMatch)
return fmt.Errorf("SDK node decode order failed")
}
order.Status = sdktypes.OrderStatusOpen
order.Status = OrderStatusOpen
log.Debug("Put processed order", "order", order)
if err := db.Put(order.Hash.Bytes(), order, false, common.Hash{}); err != nil {
return fmt.Errorf("SDKNode: failed to put processed order. Error: %s", err.Error())
Expand All @@ -1244,9 +1243,9 @@ func (tomox *TomoX) SyncDataToSDKNode(txDataMatch TxDataMatch, txHash common.Has
for _, trade := range trades {

// 2.a. put to trades
tradeSDK := &sdktypes.Trade{}
quantity := ToBigInt(trade[TradedQuantity])
price := ToBigInt(trade[TradedPrice])
tradeSDK := &Trade{}
quantity := ToBigInt(trade[TradeQuantity])
price := ToBigInt(trade[TradePrice])
if price.Cmp(big.NewInt(0)) <= 0 || quantity.Cmp(big.NewInt(0)) <= 0 {
return fmt.Errorf("trade misses important information. tradedPrice %v, tradedQuantity %v", price, quantity)
}
Expand All @@ -1255,13 +1254,15 @@ func (tomox *TomoX) SyncDataToSDKNode(txDataMatch TxDataMatch, txHash common.Has
tradeSDK.PairName = order.PairName
tradeSDK.BaseToken = order.BaseToken
tradeSDK.QuoteToken = order.QuoteToken
tradeSDK.Status = sdktypes.TradeStatusSuccess
tradeSDK.Status = TradeStatusSuccess
tradeSDK.Taker = order.UserAddress
tradeSDK.Maker = common.HexToAddress(trade[TradedMaker])
tradeSDK.Maker = common.HexToAddress(trade[TradeMaker])
tradeSDK.TakerOrderHash = order.Hash
tradeSDK.MakerOrderHash = common.HexToHash(trade[TradedMakerOrderHash])
tradeSDK.MakerOrderHash = common.HexToHash(trade[TradeMakerOrderHash])
tradeSDK.TxHash = txHash
tradeSDK.TakerOrderSide = order.Side
tradeSDK.TakerExchange = order.ExchangeAddress
tradeSDK.MakerExchange = common.HexToAddress(trade[TradeMakerExchange])

// feeAmount: all fees are calculated in quoteToken
quoteTokenQuantity := big.NewInt(0).Mul(quantity, price)
Expand All @@ -1270,7 +1271,7 @@ func (tomox *TomoX) SyncDataToSDKNode(txDataMatch TxDataMatch, txHash common.Has
takerFee = big.NewInt(0).Div(takerFee, common.TomoXBaseFee)
tradeSDK.TakeFee = takerFee

makerFee := big.NewInt(0).Mul(quoteTokenQuantity, GetExRelayerFee(common.HexToAddress(trade[TradedMakerExchangeAddress]), statedb))
makerFee := big.NewInt(0).Mul(quoteTokenQuantity, GetExRelayerFee(common.HexToAddress(trade[TradeMakerExchange]), statedb))
makerFee = big.NewInt(0).Div(makerFee, common.TomoXBaseFee)
tradeSDK.MakeFee = makerFee

Expand All @@ -1283,10 +1284,10 @@ func (tomox *TomoX) SyncDataToSDKNode(txDataMatch TxDataMatch, txHash common.Has
// 2.b. update status and filledAmount
filledAmount := quantity
// update order status of relating orders
if err := tomox.updateStatusOfMatchedOrder(trade[TradedMakerOrderHash], filledAmount); err != nil {
if err := tomox.updateStatusOfMatchedOrder(trade[TradeMakerOrderHash], filledAmount); err != nil {
return err
}
if err := tomox.updateStatusOfMatchedOrder(trade[TradedTakerOrderHash], filledAmount); err != nil {
if err := tomox.updateStatusOfMatchedOrder(trade[TradeTakerOrderHash], filledAmount); err != nil {
return err
}
}
Expand All @@ -1304,10 +1305,10 @@ func (tomox *TomoX) SyncDataToSDKNode(txDataMatch TxDataMatch, txHash common.Has
if data != nil && err == nil {
existingOrderInDB = data.(*OrderItem)
log.Debug("OrderInBook found in database", "order", existingOrderInDB)
if existingOrderInDB.Status == sdktypes.OrderStatusFilled {
if existingOrderInDB.Status == OrderStatusFilled {
log.Debug("Update status to PARTIAL_FILLED", "order", existingOrderInDB)
// if order already matched but still exist in orderbook, then update status to OrderStatusPartialFilled
existingOrderInDB.Status = sdktypes.OrderStatusPartialFilled
existingOrderInDB.Status = OrderStatusPartialFilled
if err = db.Put(key, existingOrderInDB, false, common.Hash{}); err != nil {
return fmt.Errorf("SDKNode: failed to update status to %s %s", existingOrderInDB.Status, err.Error())
}
Expand All @@ -1328,7 +1329,7 @@ func (tomox *TomoX) updateStatusOfMatchedOrder(hashString string, filledAmount *
return fmt.Errorf("SDKNode: failed to get order. Key: %s", hashString)
}
matchedOrder := val.(*OrderItem)
matchedOrder.Status = sdktypes.OrderStatusFilled
matchedOrder.Status = OrderStatusFilled
matchedOrder.UpdatedAt = uint64(time.Now().Unix())
updatedFillAmount := new(big.Int)
updatedFillAmount.Add(matchedOrder.FilledAmount, filledAmount)
Expand Down
Loading

0 comments on commit cff7e12

Please sign in to comment.