forked from OpenBazaar/spvwallet
-
Notifications
You must be signed in to change notification settings - Fork 6
/
fees.go
122 lines (111 loc) · 2.44 KB
/
fees.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package spvwallet
import (
"encoding/json"
"github.com/phoreproject/wallet-interface"
"golang.org/x/net/proxy"
"net"
"net/http"
"time"
)
type httpClient interface {
Get(string) (*http.Response, error)
}
type feeCache struct {
fees *Fees
lastUpdated time.Time
}
type Fees struct {
Priority uint64 `json:"priority"`
Normal uint64 `json:"normal"`
Economic uint64 `json:"economic"`
}
type FeeProvider struct {
maxFee uint64
priorityFee uint64
normalFee uint64
economicFee uint64
feeAPI string
httpClient httpClient
cache *feeCache
}
func NewFeeProvider(maxFee, priorityFee, normalFee, economicFee uint64, feeAPI string, proxy proxy.Dialer) *FeeProvider {
fp := FeeProvider{
maxFee: maxFee,
priorityFee: priorityFee,
normalFee: normalFee,
economicFee: economicFee,
feeAPI: feeAPI,
cache: new(feeCache),
}
dial := net.Dial
if proxy != nil {
dial = proxy.Dial
}
tbTransport := &http.Transport{Dial: dial}
httpClient := &http.Client{Transport: tbTransport, Timeout: time.Second * 10}
fp.httpClient = httpClient
return &fp
}
func (fp *FeeProvider) GetFeePerByte(feeLevel wallet.FeeLevel) uint64 {
defaultFee := func() uint64 {
switch feeLevel {
case wallet.PRIOIRTY:
return fp.priorityFee
case wallet.NORMAL:
return fp.normalFee
case wallet.ECONOMIC:
return fp.economicFee
case wallet.FEE_BUMP:
return fp.priorityFee * 2
default:
return fp.normalFee
}
}
if fp.feeAPI == "" {
return defaultFee()
}
fees := new(Fees)
if time.Since(fp.cache.lastUpdated) > time.Minute {
resp, err := fp.httpClient.Get(fp.feeAPI)
if err != nil {
return defaultFee()
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&fees)
if err != nil {
return defaultFee()
}
fp.cache.lastUpdated = time.Now()
fp.cache.fees = fees
} else {
fees = fp.cache.fees
}
switch feeLevel {
case wallet.PRIOIRTY:
if fees.Priority > fp.maxFee || fees.Priority == 0 {
return fp.maxFee
} else {
return fees.Priority
}
case wallet.NORMAL:
if fees.Normal > fp.maxFee || fees.Normal == 0 {
return fp.maxFee
} else {
return fees.Normal
}
case wallet.ECONOMIC:
if fees.Economic > fp.maxFee || fees.Economic == 0 {
return fp.maxFee
} else {
return fees.Economic
}
case wallet.FEE_BUMP:
if (fees.Priority*2) > fp.maxFee || fees.Priority == 0 {
return fp.maxFee
} else {
return fees.Priority * 2
}
default:
return fp.normalFee
}
}