/
orderbook.go
291 lines (257 loc) · 8.36 KB
/
orderbook.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package data
import (
"fmt"
"sort"
"strings"
)
type Asset struct {
Currency string `json:"currency"`
Issuer string `json:"issuer,omitempty"`
}
func NewAsset(s string) (*Asset, error) {
if s == "XRP" {
return &Asset{
Currency: s,
}, nil
}
parts := strings.Split(s, "/")
if len(parts) != 2 {
return nil, fmt.Errorf("bad asset: %s", s)
}
return &Asset{
Currency: parts[0],
Issuer: parts[1],
}, nil
}
func (a *Asset) IsNative() bool {
return a.Currency == "XRP"
}
func (a *Asset) Matches(amount *Amount) bool {
return (a.IsNative() && amount.IsNative()) ||
(a.Currency == amount.Currency.String() && a.Issuer == amount.Issuer.String())
}
func (a Asset) String() string {
if a.IsNative() {
return a.Currency
}
return fmt.Sprintf("%s/%s", a.Currency, a.Issuer)
}
type OrderBookOffer struct {
Offer
OwnerFunds Value `json:"owner_funds"`
Quality NonNativeValue `json:"quality"`
TakerGetsFunded *Amount `json:"taker_gets_funded"`
TakerPaysFunded *Amount `json:"taker_pays_funded"`
}
type AccountOffer struct {
Flags LedgerEntryFlag `json:"flags"`
Quality NonNativeValue `json:"quality"`
Sequence uint32 `json:"seq"`
TakerGets Amount `json:"taker_gets"`
TakerPays Amount `json:"taker_pays"`
Expiration *uint32 `json:"expiration"`
}
type AccountOfferSlice []AccountOffer
func (s AccountOfferSlice) Len() int { return len(s) }
func (s AccountOfferSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s AccountOfferSlice) Less(i, j int) bool { return s[i].Sequence > s[j].Sequence }
func (s AccountOfferSlice) GetSequences(pays, gets *Asset) []uint32 {
// TODO: improve performance
var sequences []uint32
for i := range s {
if pays.Matches(&s[i].TakerPays) && gets.Matches(&s[i].TakerGets) {
sequences = append(sequences, s[i].Sequence)
}
}
return sequences
}
func (s AccountOfferSlice) Find(sequence uint32) int {
return sort.Search(len(s), func(i int) bool {
return s[i].Sequence <= sequence
})
}
func (s AccountOfferSlice) Get(sequence uint32) *AccountOffer {
if i := s.Find(sequence); i < len(s) && s[i].Sequence == sequence {
return &s[i]
}
return nil
}
func defaultUint32(v *uint32) uint32 {
if v == nil {
return 0
}
return *v
}
func (s *AccountOfferSlice) Add(offer *Offer) bool {
quality, err := offer.TakerPays.Divide(offer.TakerGets)
if err != nil {
panic(fmt.Sprintf("impossible quality: %s %s", offer.TakerPays, offer.TakerGets))
}
o := AccountOffer{
Flags: LedgerEntryFlag(defaultUint32((*uint32)(offer.Flags))),
Sequence: *offer.Sequence,
TakerGets: *offer.TakerGets,
TakerPays: *offer.TakerPays,
Quality: NonNativeValue{*quality.Value},
Expiration: offer.Expiration,
}
i := s.Find(*offer.Sequence)
switch {
case i == len(*s):
*s = append(*s, o)
return true
case (*s)[i].Sequence != *offer.Sequence:
*s = append(*s, AccountOffer{})
copy((*s)[i+1:], (*s)[i:])
(*s)[i] = o
return true
default:
return false
}
}
func (s AccountOfferSlice) Update(offer *Offer) bool {
if existing := s.Get(*offer.Sequence); existing != nil {
existing.TakerGets = *offer.TakerGets
existing.TakerPays = *offer.TakerPays
return true
}
return false
}
func (s *AccountOfferSlice) Delete(offer *Offer) bool {
if i := s.Find(*offer.Sequence); i < len(*s) && (*s)[i].Sequence == *offer.Sequence {
*s = append((*s)[:i], (*s)[i+1:]...)
return true
}
return false
}
type AccountLine struct {
Account Account `json:"account"`
Balance NonNativeValue `json:"balance"`
Currency Currency `json:"currency"`
Limit NonNativeValue `json:"limit"`
LimitPeer NonNativeValue `json:"limit_peer"`
NoRipple bool `json:"no_ripple"`
NoRipplePeer bool `json:"no_ripple_peer"`
QualityIn uint32 `json:"quality_in"`
QualityOut uint32 `json:"quality_out"`
}
func (l *AccountLine) Asset() *Asset {
return &Asset{
Currency: l.Currency.String(),
Issuer: l.Account.String(),
}
}
func (l *AccountLine) CompareByCurrencyAccount(other *AccountLine) int {
if cmp := l.Currency.Compare(other.Currency); cmp != 0 {
return cmp
}
return l.Account.Compare(other.Account)
}
func (l *AccountLine) CompareByCurrencyAmount(other *AccountLine) int {
if cmp := l.Currency.Compare(other.Currency); cmp != 0 {
return cmp
}
return l.Balance.Abs().Compare(*other.Balance.Abs())
}
type AccountLineSlice []AccountLine
type byCurrencyAccount struct {
AccountLineSlice
}
func (by *byCurrencyAccount) Less(i, j int) bool {
return by.AccountLineSlice[i].CompareByCurrencyAccount(&by.AccountLineSlice[j]) < 0
}
type byCurrencyAmount struct {
AccountLineSlice
}
func (by *byCurrencyAmount) Less(i, j int) bool {
return by.AccountLineSlice[i].CompareByCurrencyAmount(&by.AccountLineSlice[j]) < 0
}
func (s AccountLineSlice) Len() int { return len(s) }
func (s AccountLineSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s AccountLineSlice) SortbyCurrencyAccount() { sort.Sort(&byCurrencyAccount{s}) }
func (s AccountLineSlice) SortByCurrencyAmount() { sort.Sort(&byCurrencyAmount{s}) }
func (s AccountLineSlice) Find(account Account, currency Currency) int {
return sort.Search(len(s), func(i int) bool {
switch s[i].Currency.Compare(currency) {
case 1:
return true
case -1:
return false
default:
return s[i].Account.Compare(account) >= 0
}
})
}
func (s AccountLineSlice) Get(account Account, currency Currency) *AccountLine {
if i := s.Find(account, currency); i < len(s) && s[i].Account.Equals(account) && s[i].Currency.Equals(currency) {
return &s[i]
}
return nil
}
type highLowFunc func(balance, limit, limitPeer *Amount, noRipple, noRipplePeer bool, qualityIn, qualityOut uint32) bool
func highLow(account Account, rs *RippleState, f highLowFunc) bool {
high, low := account.Equals(rs.HighLimit.Issuer), account.Equals(rs.LowLimit.Issuer)
switch {
case high == low:
return false
case high:
noRipple, noRipplePeer := *rs.Flags&LsHighNoRipple > 0, *rs.Flags&LsLowNoRipple > 0
return f(rs.Balance.Negate(), rs.HighLimit, rs.LowLimit, noRipple, noRipplePeer, defaultUint32(rs.HighQualityIn), defaultUint32(rs.HighQualityOut))
default:
noRipple, noRipplePeer := *rs.Flags&LsLowNoRipple > 0, *rs.Flags&LsHighNoRipple > 0
return f(rs.Balance, rs.LowLimit, rs.HighLimit, noRipple, noRipplePeer, defaultUint32(rs.LowQualityIn), defaultUint32(rs.LowQualityOut))
}
}
func (s *AccountLineSlice) Add(account Account, rs *RippleState) bool {
var add = func(balance, limit, limitPeer *Amount, noRipple, noRipplePeer bool, qualityIn, qualityOut uint32) bool {
line := AccountLine{
Account: limitPeer.Issuer,
Balance: NonNativeValue{*balance.Value},
Currency: limit.Currency,
Limit: NonNativeValue{*limit.Value},
LimitPeer: NonNativeValue{*limitPeer.Value},
NoRipple: noRipple,
NoRipplePeer: noRipplePeer,
QualityIn: qualityIn,
QualityOut: qualityOut,
}
i := s.Find(limitPeer.Issuer, limitPeer.Currency)
switch {
case i == len(*s):
*s = append(*s, line)
return true
case (*s)[i].Account.Equals(limitPeer.Issuer) && (*s)[i].Currency.Equals(limitPeer.Currency):
return false
default:
*s = append((*s)[:i], append(AccountLineSlice{line}, (*s)[i:]...)...)
return true
}
}
return highLow(account, rs, add)
}
func (s AccountLineSlice) Update(account Account, rs *RippleState) bool {
var update = func(balance, limit, limitPeer *Amount, noripple, noRipplePeer bool, qualityIn, qualityOut uint32) bool {
i := s.Find(limitPeer.Issuer, limitPeer.Currency)
if i == len(s) || !s[i].Account.Equals(limitPeer.Issuer) || !s[i].Currency.Equals(limitPeer.Currency) {
return false
}
s[i].Balance = NonNativeValue{*balance.Value}
s[i].Limit = NonNativeValue{*limit.Value}
s[i].LimitPeer = NonNativeValue{*limitPeer.Value}
s[i].NoRipple = noripple
s[i].NoRipplePeer = noRipplePeer
return true
}
return highLow(account, rs, update)
}
func (s *AccountLineSlice) Delete(account Account, rs *RippleState) bool {
var del = func(balance, limit, limitPeer *Amount, noripple, noRipplePeer bool, qualityIn, qualityOut uint32) bool {
i := s.Find(limitPeer.Issuer, limitPeer.Currency)
if i < len(*s) && (*s)[i].Account.Equals(limitPeer.Issuer) && (*s)[i].Currency.Equals(limitPeer.Currency) {
*s = append((*s)[:i], (*s)[i+1:]...)
return true
}
return false
}
return highLow(account, rs, del)
}