-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
best_quote.go
76 lines (63 loc) · 1.82 KB
/
best_quote.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package minercraft
import (
"context"
"sync"
)
// BestQuote will check all known miners and compare rates, returning the best rate/quote
//
// Note: this might return different results each time if miners have the same rates as
// it's a race condition on which results come back first
func (c *Client) BestQuote(ctx context.Context, feeCategory, feeType string) (*FeeQuoteResponse, error) {
// Best rate & quote
var bestRate uint64
var bestQuote FeeQuoteResponse
// The channel for the internal results
resultsChannel := make(chan *internalResult, len(c.miners))
// Loop each miner (break into a Go routine for each quote request)
var wg sync.WaitGroup
for _, miner := range c.miners {
wg.Add(1)
go func(ctx context.Context, wg *sync.WaitGroup, client *Client,
miner *Miner, resultsChannel chan *internalResult) {
defer wg.Done()
resultsChannel <- getQuote(ctx, client, miner, mAPIRouteFeeQuote)
}(ctx, &wg, c, miner, resultsChannel)
}
// Waiting for all requests to finish
wg.Wait()
close(resultsChannel)
// Loop the results of the channel
var testRate uint64
var quoteFound bool
var lastErr error
for result := range resultsChannel {
// Check for error?
if result.Response.Error != nil {
lastErr = result.Response.Error
continue
}
// Parse the response
var quote FeeQuoteResponse
if quote, lastErr = result.parseFeeQuote(); lastErr != nil {
continue
}
// Get a test rate
if testRate, lastErr = quote.Quote.CalculateFee(
feeCategory, feeType, 1000,
); lastErr != nil {
continue
}
// (Never set) || (or better than previous rate)
quoteFound = true
if bestRate == 0 || testRate < bestRate {
bestRate = testRate
bestQuote = quote
}
}
// No quotes?
if !quoteFound && lastErr != nil {
return nil, lastErr
}
// Return the best quote found
return &bestQuote, nil
}