Skip to content

Commit

Permalink
review followup
Browse files Browse the repository at this point in the history
  • Loading branch information
buck54321 committed Apr 23, 2024
1 parent c0e288e commit 9b5dfe8
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 42 deletions.
42 changes: 27 additions & 15 deletions client/cmd/testbinance/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,11 +203,12 @@ type marketSubscriber struct {
}

type userOrder struct {
slug string
sell bool
rate float64
qty float64
apiKey string
slug string
sell bool
rate float64
qty float64
apiKey string
cancelled atomic.Bool
}

type fakeBinance struct {
Expand Down Expand Up @@ -299,14 +300,16 @@ func (f *fakeBinance) run(ctx context.Context) {
updates := make(map[string]json.RawMessage)
for mktID, mkt := range f.markets {
mkt.bookMtx.Lock()
mkt.updateID++
buys, sells := mkt.shuffle()
firstUpdateID := mkt.updateID + 1
mkt.updateID += uint64(len(buys) + len(sells))
update, _ := json.Marshal(&bntypes.BookNote{
StreamName: mktID + "@depth",
Data: &bntypes.BookUpdate{
Bids: buys,
Asks: sells,
LastUpdateID: mkt.updateID,
Bids: buys,
Asks: sells,
FirstUpdateID: firstUpdateID,
LastUpdateID: mkt.updateID,
},
})
updates[mktID] = update
Expand Down Expand Up @@ -835,6 +838,10 @@ func (f *fakeBinance) handleGetOrder(w http.ResponseWriter, r *http.Request) {
http.Error(w, "order not found", http.StatusBadRequest)
return
}
status := "NEW"
if ord.cancelled.Load() {
status = "CANCELED"
}
resp := &bntypes.BookedOrder{
Symbol: ord.slug,
// OrderID: ,
Expand All @@ -843,7 +850,7 @@ func (f *fakeBinance) handleGetOrder(w http.ResponseWriter, r *http.Request) {
OrigQty: strconv.FormatFloat(ord.qty, 'f', 9, 64),
ExecutedQty: "0",
CumulativeQuoteQty: "0",
Status: "NEW",
Status: status,
TimeInForce: "GTC",
}
writeJSONWithStatus(w, &resp, http.StatusOK)
Expand Down Expand Up @@ -910,8 +917,13 @@ func (f *fakeBinance) handleDeleteOrder(w http.ResponseWriter, r *http.Request)
apiKey := extractAPIKey(r)
f.bookedOrdersMtx.Lock()
ord, found := f.bookedOrders[tradeID]
delete(f.bookedOrders, tradeID)
f.bookedOrdersMtx.Unlock()
if found {
if !ord.cancelled.CompareAndSwap(false, true) {
log.Errorf("Detected cancellation of an already cancelled order %s", tradeID)
}
ord.cancelled.Store(true)
}
writeJSONWithStatus(w, &struct{}{}, http.StatusOK)
if !found {
log.Errorf("DELETE request received from user %s for unknown order %s", apiKey, tradeID)
Expand All @@ -928,10 +940,10 @@ func (f *fakeBinance) handleDeleteOrder(w http.ResponseWriter, r *http.Request)
update := &bntypes.StreamUpdate{
EventType: "executionReport",
CurrentOrderStatus: "CANCELED",
// CancelledOrderID
ClientOrderID: tradeID,
Filled: 0,
QuoteFilled: 0,
ClientOrderID: hex.EncodeToString(encode.RandomBytes(20)),
CancelledOrderID: tradeID,
Filled: 0,
QuoteFilled: 0,
}
updateB, _ := json.Marshal(update)
sub.SendRaw(updateB)
Expand Down
17 changes: 7 additions & 10 deletions client/mm/libxc/binance.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,8 @@ func (b *binanceOrderBook) convertBinanceBook(binanceBids, binanceAsks [][2]json
func (b *binanceOrderBook) sync(ctx context.Context) {
cm := dex.NewConnectionMaster(b)
b.mtx.Lock()
oldCM := b.cm
b.cm = cm
b.mtx.Unlock()
if oldCM != nil {
oldCM.Disconnect()
}
if err := cm.ConnectOnce(ctx); err != nil {
b.log.Errorf("Error connecting %s order book: %v", b.mktID, err)
}
Expand Down Expand Up @@ -176,7 +172,7 @@ func (b *binanceOrderBook) Connect(ctx context.Context) (*sync.WaitGroup, error
syncCache = append(syncCache, update)
return true
}
if update.LastUpdateID != updateID+1 {
if update.FirstUpdateID != updateID+1 {
// Trigger a resync.
return false
}
Expand Down Expand Up @@ -243,6 +239,7 @@ func (b *binanceOrderBook) Connect(ctx context.Context) (*sync.WaitGroup, error
select {
case update := <-b.updateQueue:
if !processUpdate(update) {
b.log.Tracef("Bad %s update with ID %d", b.mktID, update.LastUpdateID)
desync()
}
case <-ctx.Done():
Expand Down Expand Up @@ -938,8 +935,6 @@ func (bnc *binance) GetDepositAddress(ctx context.Context, assetID uint32) (stri
func (bnc *binance) ConfirmDeposit(ctx context.Context, deposit *DepositData, onConfirm func(uint64)) {
checkDepositStatus := func() (done bool, amt uint64) {
var resp []*bntypes.PendingDeposit
// TODO: Use the "startTime" parameter to apply a reasonable limit to
// this request.
// We'll add info for the fake server.
var query url.Values
if bnc.accountsURL == fakeBinanceURL {
Expand All @@ -956,6 +951,8 @@ func (bnc *binance) ConfirmDeposit(ctx context.Context, deposit *DepositData, on
"network": []string{bncAsset.chain},
}
}
// TODO: Use the "startTime" parameter to apply a reasonable limit to
// this request.
err := bnc.getAPI(ctx, "/sapi/v1/capital/deposit/hisrec", query, true, true, &resp)
if err != nil {
bnc.log.Errorf("error getting deposit status: %v", err)
Expand Down Expand Up @@ -1118,7 +1115,7 @@ func (bnc *binance) postAPI(ctx context.Context, endpoint string, query, form ur
}

func (bnc *binance) requestInto(req *http.Request, thing interface{}) error {
bnc.log.Tracef("Sending request: %+v", req)
// bnc.log.Tracef("Sending request: %+v", req)

resp, err := http.DefaultClient.Do(req)
if err != nil {
Expand Down Expand Up @@ -1524,7 +1521,7 @@ func (bnc *binance) subscribeToAdditionalMarketDataStream(ctx context.Context, b
}
book = newBinanceOrderBook(baseCfg.conversionFactor, quoteCfg.conversionFactor, mktID, getSnapshot, bnc.log)
bnc.books[mktID] = book
go book.sync(ctx)
book.sync(ctx)

return nil
}
Expand Down Expand Up @@ -1594,7 +1591,7 @@ func (bnc *binance) connectToMarketDataStream(ctx context.Context, baseID, quote

bnc.marketStream = conn

go book.sync(ctx)
book.sync(ctx)

// Start a goroutine to reconnect every 12 hours
go func() {
Expand Down
34 changes: 27 additions & 7 deletions client/mm/libxc/binance_live_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (

"decred.org/dcrdex/client/asset"
_ "decred.org/dcrdex/client/asset/importall"
"decred.org/dcrdex/client/mm/libxc/bntypes"
"decred.org/dcrdex/dex"
)

Expand Down Expand Up @@ -237,6 +238,23 @@ func TestVWAP(t *testing.T) {
}
}

func TestSubscribeMarket(t *testing.T) {
bnc := tNewBinance(t, dex.Testnet)
ctx, cancel := context.WithTimeout(context.Background(), time.Hour*23)
defer cancel()
wg, err := bnc.Connect(ctx)
if err != nil {
t.Fatalf("Connect error: %v", err)
}

err = bnc.SubscribeMarket(ctx, 60, 0)
if err != nil {
t.Fatalf("failed to subscribe to market: %v", err)
}

wg.Wait()
}

func TestWithdrawal(t *testing.T) {
bnc := tNewBinance(t, dex.Mainnet)
ctx, cancel := context.WithTimeout(context.Background(), time.Hour*23)
Expand All @@ -249,12 +267,12 @@ func TestWithdrawal(t *testing.T) {

wg := sync.WaitGroup{}
wg.Add(1)
onComplete := func(amt uint64, txID string) {
t.Logf("withdrawal complete: %v, %v", amt, txID)
onComplete := func(txID string) {
t.Logf("withdrawal complete: %v", txID)
wg.Done()
}

err = bnc.Withdraw(ctx, 966, 2e10, "", onComplete)
_, err = bnc.Withdraw(ctx, 966, 2e10, "", onComplete)
if err != nil {
fmt.Printf("withdrawal error: %v", err)
return
Expand All @@ -275,12 +293,14 @@ func TestConfirmDeposit(t *testing.T) {

wg := sync.WaitGroup{}
wg.Add(1)
onComplete := func(success bool, amount uint64) {
t.Logf("deposit complete: %v, %v", success, amount)
onComplete := func(amount uint64) {
t.Logf("deposit complete: %v", amount)
wg.Done()
}

bnc.ConfirmDeposit(ctx, "", onComplete)
bnc.ConfirmDeposit(ctx, &DepositData{
TxID: "",
}, onComplete)

wg.Wait()
}
Expand Down Expand Up @@ -326,7 +346,7 @@ func TestGetCoinInfo(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Hour*23)
defer cancel()

coins := make([]*binanceCoinInfo, 0)
coins := make([]*bntypes.CoinInfo, 0)
err := bnc.getAPI(ctx, "/sapi/v1/capital/config/getall", nil, true, true, &coins)
if err != nil {
t.Fatalf("error getting binance coin info: %v", err)
Expand Down
4 changes: 0 additions & 4 deletions client/mm/libxc/binance_types.go

This file was deleted.

2 changes: 1 addition & 1 deletion client/webserver/site/src/js/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1181,7 +1181,7 @@ export default class Application {
if (!w) return false
const traitAccountLocker = 1 << 14
if ((w.traits & traitAccountLocker) === 0) return false
const res = await postJSON('/api/walletsettings', { assetID })
const res = await postJSON('/api/walletsettings', { baseChainID })
if (!this.checkResponse(res)) {
console.error(res.msg)
return false
Expand Down
13 changes: 8 additions & 5 deletions dex/networks/eth/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,16 +208,19 @@ func MaybeReadSimnetAddrsDir(
testUSDCContractAddrFile := filepath.Join(harnessDir, "test_usdc_contract_address.txt")
multiBalanceContractAddrFile := filepath.Join(harnessDir, "multibalance_address.txt")

contractsAddrs[0][dex.Simnet] = getContractAddrFromFile(ethSwapContractAddrFile)
multiBalandAddresses[dex.Simnet] = getContractAddrFromFile(multiBalanceContractAddrFile)
contractsAddrs[0][dex.Simnet] = maybeGetContractAddrFromFile(ethSwapContractAddrFile)
multiBalandAddresses[dex.Simnet] = maybeGetContractAddrFromFile(multiBalanceContractAddrFile)

usdcToken.SwapContracts[0].Address = getContractAddrFromFile(testUSDCSwapContractAddrFile)
usdcToken.Address = getContractAddrFromFile(testUSDCContractAddrFile)
usdcToken.SwapContracts[0].Address = maybeGetContractAddrFromFile(testUSDCSwapContractAddrFile)
usdcToken.Address = maybeGetContractAddrFromFile(testUSDCContractAddrFile)
}

func getContractAddrFromFile(fileName string) (addr common.Address) {
func maybeGetContractAddrFromFile(fileName string) (addr common.Address) {
addrBytes, err := os.ReadFile(fileName)
if err != nil {
if os.IsNotExist(err) {
return
}
fmt.Printf("error reading contract address: %v \n", err)
return
}
Expand Down

0 comments on commit 9b5dfe8

Please sign in to comment.