Skip to content

Commit

Permalink
More evm tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lumos42 committed Sep 30, 2023
1 parent 9bcc1b7 commit d2a182f
Show file tree
Hide file tree
Showing 3 changed files with 198 additions and 6 deletions.
187 changes: 187 additions & 0 deletions plugin/evm/orderbook/contract_events_processor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,101 @@ func TestHandleOrderBookEvent(t *testing.T) {
assert.Equal(t, big.NewInt(-fillAmount.Int64()), shortOrder.FilledBaseAssetQuantity)
})
})

t.Run("When event is OrderMatchingError", func(t *testing.T) {
db := getDatabase()
cep := newcep(t, db)
event := getEventFromABI(orderBookABI, "OrderMatchingError")
order := &Order{
Market: Market(ammIndex.Int64()),
PositionType: LONG,
Trader: traderAddress,
BaseAssetQuantity: baseAssetQuantity,
Price: price,
BlockNumber: big.NewInt(1),
FilledBaseAssetQuantity: big.NewInt(0),
Salt: salt,
}
order.Id = getIdFromOrder(*order)
db.Add(order)
topics := []common.Hash{event.ID, order.Id}
t.Run("When data in log unpack fails", func(t *testing.T) {
orderMatchingErrorEventData := []byte{}
log := getEventLog(OrderBookContractAddress, topics, orderMatchingErrorEventData, blockNumber)
cep.ProcessEvents([]*types.Log{log})
assert.Equal(t, int64(0), order.FilledBaseAssetQuantity.Int64())
assert.Equal(t, Placed, order.getOrderStatus().Status)
})
t.Run("When data in log unpack succeeds", func(t *testing.T) {
orderMatchingErrorEventData, err := event.Inputs.NonIndexed().Pack("error string")
if err != nil {
t.Fatalf("%s", err)
}
log := getEventLog(OrderBookContractAddress, topics, orderMatchingErrorEventData, blockNumber)
cep.ProcessEvents([]*types.Log{log})

order = db.GetOrderBookData().Orders[order.Id]
assert.Equal(t, int64(0), order.FilledBaseAssetQuantity.Int64())
assert.Equal(t, Execution_Failed, order.getOrderStatus().Status)
assert.Equal(t, "error string", order.getOrderStatus().Info)
assert.Equal(t, blockNumber, order.getOrderStatus().BlockNumber)
})
})
}

func TestHandleIOCOrderBookEvent(t *testing.T) {
t.Run("When event is OrderAccepted", func(t *testing.T) {
db := getDatabase()
cep := newcep(t, db)
iocOrderBookABI := getABIfromJson(abis.IOCOrderBookAbi)

order := createIOCOrder(LONG, trader.String(), big.NewInt(100), big.NewInt(10), Placed, big.NewInt(21), big.NewInt(1), big.NewInt(5))
iocOrder := IOCOrder{
BaseOrder: BaseOrder{
AmmIndex: big.NewInt(int64(order.Market)),
Trader: trader,
Price: order.Price,
BaseAssetQuantity: order.BaseAssetQuantity,
Salt: order.Salt,
ReduceOnly: order.ReduceOnly,
},
OrderType: 1,
ExpireAt: big.NewInt(5),
}
orderId := getIdFromOrder(order)

event := getEventFromABI(iocOrderBookABI, "OrderAccepted")
topics := []common.Hash{event.ID, trader.Hash(), orderId}
blockNumber := uint64(21)
t.Run("When data in log unpack fails", func(t *testing.T) {
orderAcceptedEventData := []byte{}
log := getEventLog(IOCOrderBookContractAddress, topics, orderAcceptedEventData, blockNumber)
cep.ProcessEvents([]*types.Log{log})
actualLimitOrder := db.GetOrderBookData().Orders[orderId]
assert.Nil(t, actualLimitOrder)
})
t.Run("When data in log unpack succeeds", func(t *testing.T) {
orderAcceptedEventData, err := event.Inputs.NonIndexed().Pack(iocOrder, timestamp)
if err != nil {
t.Fatalf("%s", err)
}
log := getEventLog(IOCOrderBookContractAddress, topics, orderAcceptedEventData, blockNumber)
cep.ProcessEvents([]*types.Log{log})

actualLimitOrder := db.GetOrderBookData().Orders[orderId]
assert.Equal(t, Market(order.Market), actualLimitOrder.Market)
assert.Equal(t, LONG, actualLimitOrder.PositionType)
assert.Equal(t, trader.String(), actualLimitOrder.Trader.String())
assert.Equal(t, *order.BaseAssetQuantity, *actualLimitOrder.BaseAssetQuantity)
assert.Equal(t, false, actualLimitOrder.ReduceOnly)
assert.Equal(t, false, actualLimitOrder.isPostOnly())
assert.Equal(t, *order.Price, *actualLimitOrder.Price)
assert.Equal(t, Placed, actualLimitOrder.getOrderStatus().Status)
assert.Equal(t, big.NewInt(int64(blockNumber)), actualLimitOrder.BlockNumber)
// rawOrder := &IOCOrder{}
assert.Equal(t, &iocOrder, actualLimitOrder.RawOrder.(*IOCOrder))
})
})
}

func TestHandleMarginAccountEvent(t *testing.T) {
Expand Down Expand Up @@ -615,6 +710,30 @@ func TestHandleClearingHouseEvent(t *testing.T) {
assert.Equal(t, openNotional, db.TraderMap[traderAddress].Positions[market].OpenNotional)
})
})

t.Run("When event is NotifyNextPISample", func(t *testing.T) {
event := getEventFromABI(clearingHouseABI, "NotifyNextPISample")
topics := []common.Hash{event.ID}
db := getDatabase()
cep := newcep(t, db)
t.Run("When event parsing fails", func(t *testing.T) {
notifyNextPISampleEvent := []byte{}
log := getEventLog(ClearingHouseContractAddress, topics, notifyNextPISampleEvent, blockNumber)
cep.ProcessAcceptedEvents([]*types.Log{log}, false)
assert.Equal(t, uint64(0), db.NextSamplePITime)
})
t.Run("When event parsing succeeds", func(t *testing.T) {
nextSamplePITime := big.NewInt(time.Now().Unix())
notifyNextPISampleEvent, err := event.Inputs.NonIndexed().Pack(nextSamplePITime)
if err != nil {
t.Fatal(err)
}
log := getEventLog(ClearingHouseContractAddress, topics, notifyNextPISampleEvent, blockNumber)
cep.ProcessAcceptedEvents([]*types.Log{log}, false)
assert.Equal(t, nextSamplePITime.Uint64(), db.NextSamplePITime)
})

})
}

func TestRemovedEvents(t *testing.T) {
Expand Down Expand Up @@ -733,6 +852,74 @@ func TestRemovedEvents(t *testing.T) {
})
}

func TestPushToTraderFeed(t *testing.T) {
testPushToTraderFeed := func(t *testing.T, event *types.Log, expectedResponse TraderEvent) {
cep := newcep(t, getDatabase())

traderFeedCh := make(chan TraderEvent)
traderFeedSubscription := traderFeed.Subscribe(traderFeedCh)
defer traderFeedSubscription.Unsubscribe()

go cep.PushToTraderFeed([]*types.Log{event}, ConfirmationLevelHead)

select {
case event := <-traderFeedCh:
assert.Equal(t, expectedResponse.Trader, event.Trader)
assert.Equal(t, expectedResponse.Removed, event.Removed)
assert.Equal(t, expectedResponse.EventName, event.EventName)
// assert.Equal(t, expectedResponse.Args, event.Args)
assert.Equal(t, expectedResponse.BlockNumber, event.BlockNumber)
assert.Equal(t, expectedResponse.BlockStatus, event.BlockStatus)
assert.Equal(t, expectedResponse.OrderId, event.OrderId)
assert.Equal(t, expectedResponse.OrderType, event.OrderType)

case <-time.After(1 * time.Second):
t.Fatalf("Expected traderFeed.Send to be called, but it was not")
}
}

t.Run("OrderMatched", func(t *testing.T) {
orderBookABI := getABIfromJson(abis.OrderBookAbi)
orderMatchedEvent := getEventFromABI(orderBookABI, "OrderMatched")
orderId := common.HexToHash("0x456")
orderMatchedEventTopics := []common.Hash{orderMatchedEvent.ID, trader.Hash(), orderId}
price = hu.Mul(big.NewInt(20), hu.ONE_E_6)
baseAssetQuantity := hu.Mul(big.NewInt(5), hu.ONE_E_18)
orderMatchedEventData, err := orderMatchedEvent.Inputs.NonIndexed().Pack(baseAssetQuantity, price, hu.Mul(baseAssetQuantity, price), timestamp, false)
if err != nil {
t.Fatal(err)
}
event := getEventLog(OrderBookContractAddress, orderMatchedEventTopics, orderMatchedEventData, blockNumber.Uint64())
expectedResponse := TraderEvent{
Trader: trader,
Removed: false,
EventName: "OrderMatched",
Args: map[string]interface{}{
"fillAmount": 5,
"isLiquidation": false,
"openInterestNotional": hu.Mul(big.NewInt(100), hu.ONE_E_6),
"price": hu.Div(price, hu.ONE_E_6),
"timestamp": timestamp,
},
BlockNumber: blockNumber,
BlockStatus: ConfirmationLevelHead,
OrderId: orderId,
OrderType: "",
}

testPushToTraderFeed(t, event, expectedResponse)
})
}

// MockTraderFeed is a mock implementation of the TraderFeed interface for testing purposes
type MockTraderFeed struct {
Events []TraderEvent
}

func (m *MockTraderFeed) Send(event TraderEvent) {
m.Events = append(m.Events, event)
}

func newcep(t *testing.T, db LimitOrderDatabase) *ContractEventsProcessor {
return NewContractEventsProcessor(db)
}
Expand Down
15 changes: 11 additions & 4 deletions plugin/evm/orderbook/order_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package orderbook

import (
"encoding/hex"
"fmt"
"math/big"
"strings"

Expand Down Expand Up @@ -126,18 +125,27 @@ func testDecodeTypeAndEncodedOrder(t *testing.T, typedEncodedOrder string, encod

assert.Equal(t, orderType, decodeStep.OrderType)
assert.Equal(t, encodedOrder, hex.EncodeToString(decodeStep.EncodedOrder))

order, ok := expectedOutput.(LimitOrder)
assert.True(t, ok)
testEncodeOrder(t, &order, typedEncodedOrder)
testDecodeLimitOrder(t, encodedOrder, expectedOutput)
}

func testEncodeOrder(t *testing.T, order ContractOrder, expectedTypedEncoding string) {
encodedOrder, err := order.EncodeToABI()
assert.Nil(t, err)
assert.Equal(t, expectedTypedEncoding, hex.EncodeToString(encodedOrder))
}

func testDecodeLimitOrder(t *testing.T, encodedOrder string, expectedOutput interface{}) {
testData, err := hex.DecodeString(encodedOrder)
assert.Nil(t, err)

result, err := DecodeLimitOrder(testData)
fmt.Println(result)
assert.NoError(t, err)
assert.NotNil(t, result)
assertLimitOrderEquality(t, expectedOutput.(LimitOrder).BaseOrder, *&result.BaseOrder)
assertLimitOrderEquality(t, expectedOutput.(LimitOrder).BaseOrder, result.BaseOrder)
assert.Equal(t, expectedOutput.(LimitOrder).PostOnly, result.PostOnly)
}

Expand Down Expand Up @@ -208,7 +216,6 @@ func testDecodeTypeAndEncodedIOCOrder(t *testing.T, typedEncodedOrder string, en
func testDecodeIOCOrder(t *testing.T, encodedOrder []byte, expectedOutput *IOCOrder) {
result, err := DecodeIOCOrder(encodedOrder)
assert.NoError(t, err)
fmt.Println(result)
assert.NotNil(t, result)
assertIOCOrderEquality(t, expectedOutput, result)
}
Expand Down
2 changes: 0 additions & 2 deletions plugin/evm/orderbook/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package orderbook

import (
"context"
"fmt"
"math/big"
"testing"

Expand Down Expand Up @@ -48,7 +47,6 @@ func TestAggregatedOrderBook(t *testing.T) {
shortOrder2.Price.String(): shortOrder2.BaseAssetQuantity.String(),
},
}
fmt.Println(response)
assert.Equal(t, expectedAggregatedOrderBookState, *response)

orderbook, _ := service.GetOrderBook(ctx, "0")
Expand Down

0 comments on commit d2a182f

Please sign in to comment.