/
offer.go
371 lines (332 loc) · 8.6 KB
/
offer.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package model
import (
"context"
"fmt"
"math/big"
"time"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
sqlite3 "github.com/mattn/go-sqlite3"
"github.com/spolu/settle/lib/db"
"github.com/spolu/settle/lib/errors"
"github.com/spolu/settle/lib/token"
"github.com/spolu/settle/mint"
)
// Offer represents an offer for an asset pair.
// - Offers are always represented as asks
// (ask on pair A/B offer to sell A (base asset) for B (quote asset)).
// Amounts are expressed in quote asset.
// - Canonical offers are stored on the mint of the offer's owner (which acts
// as source of truth on its state).
// - Propagated offers are indicatively stored on the mints of the offers's
// assets, to compute order books.
type Offer struct {
Owner string
Token string
Created time.Time
Propagation mint.PgType
BaseAsset string `db:"base_asset"` // BaseAsset name.
QuoteAsset string `db:"quote_asset"` // QuoteAsset name.
BasePrice Amount `db:"base_price"`
QuotePrice Amount `db:"quote_price"`
Amount Amount
Status mint.OfStatus
Remainder Amount
}
// NewOfferResource generates a new resource.
func NewOfferResource(
ctx context.Context,
offer *Offer,
) mint.OfferResource {
return mint.OfferResource{
ID: fmt.Sprintf(
"%s[%s]", offer.Owner, offer.Token),
Created: offer.Created.UnixNano() / mint.TimeResolutionNs,
Owner: offer.Owner,
Propagation: offer.Propagation,
Pair: fmt.Sprintf("%s/%s", offer.BaseAsset, offer.QuoteAsset),
Price: fmt.Sprintf(
"%s/%s",
(*big.Int)(&offer.BasePrice).String(),
(*big.Int)(&offer.QuotePrice).String()),
Amount: (*big.Int)(&offer.Amount),
Status: offer.Status,
Remainder: (*big.Int)(&offer.Remainder),
}
}
// CreateCanonicalOffer creates and stores a new canonical Offer object.
func CreateCanonicalOffer(
ctx context.Context,
owner string,
baseAsset string,
quoteAsset string,
basePrice Amount,
quotePrice Amount,
amount Amount,
status mint.OfStatus,
remainder Amount,
) (*Offer, error) {
offer := Offer{
Owner: owner,
Token: token.New("offer"),
Created: time.Now().UTC(),
Propagation: mint.PgTpCanonical,
BaseAsset: baseAsset,
QuoteAsset: quoteAsset,
BasePrice: basePrice,
QuotePrice: quotePrice,
Amount: amount,
Status: status,
Remainder: remainder,
}
ext := db.Ext(ctx, "mint")
if _, err := sqlx.NamedExec(ext, `
INSERT INTO offers
(owner, token, created, propagation, base_asset, quote_asset,
base_price, quote_price, amount, status, remainder)
VALUES
(:owner, :token, :created, :propagation, :base_asset, :quote_asset,
:base_price, :quote_price, :amount, :status, :remainder)
`, offer); err != nil {
switch err := err.(type) {
case *pq.Error:
if err.Code.Name() == "unique_violation" {
return nil, errors.Trace(ErrUniqueConstraintViolation{err})
}
case sqlite3.Error:
if err.ExtendedCode == sqlite3.ErrConstraintUnique {
return nil, errors.Trace(ErrUniqueConstraintViolation{err})
}
}
return nil, errors.Trace(err)
}
return &offer, nil
}
// CreatePropagatedOffer creates and stores a new propagated Offer object.
func CreatePropagatedOffer(
ctx context.Context,
owner string,
token string,
created time.Time,
baseAsset string,
quoteAsset string,
basePrice Amount,
quotePrice Amount,
amount Amount,
status mint.OfStatus,
remainder Amount,
) (*Offer, error) {
offer := Offer{
Owner: owner,
Token: token,
Created: created.UTC(),
Propagation: mint.PgTpPropagated,
BaseAsset: baseAsset,
QuoteAsset: quoteAsset,
BasePrice: basePrice,
QuotePrice: quotePrice,
Amount: amount,
Status: status,
Remainder: remainder,
}
ext := db.Ext(ctx, "mint")
if _, err := sqlx.NamedExec(ext, `
INSERT INTO offers
(owner, token, created, propagation, base_asset, quote_asset,
base_price, quote_price, amount, status, remainder)
VALUES
(:owner, :token, :created, :propagation, :base_asset, :quote_asset,
:base_price, :quote_price, :amount, :status, :remainder)
`, offer); err != nil {
switch err := err.(type) {
case *pq.Error:
if err.Code.Name() == "unique_violation" {
return nil, errors.Trace(ErrUniqueConstraintViolation{err})
}
case sqlite3.Error:
if err.ExtendedCode == sqlite3.ErrConstraintUnique {
return nil, errors.Trace(ErrUniqueConstraintViolation{err})
}
}
return nil, errors.Trace(err)
}
return &offer, nil
}
// ID returns the ID of the object.
func (o *Offer) ID() string {
return fmt.Sprintf("%s[%s]", o.Owner, o.Token)
}
// Save updates the object database representation with the in-memory values.
func (o *Offer) Save(
ctx context.Context,
) error {
ext := db.Ext(ctx, "mint")
_, err := sqlx.NamedExec(ext, `
UPDATE offers
SET status = :status, remainder = :remainder
WHERE owner = :owner
AND token = :token
`, o)
if err != nil {
return errors.Trace(err)
}
return nil
}
// LoadCanonicalOfferByOwnerToken attempts to load the canonical offer for the
// given owner and token.
func LoadCanonicalOfferByOwnerToken(
ctx context.Context,
owner string,
token string,
) (*Offer, error) {
offer := Offer{
Owner: owner,
Token: token,
Propagation: mint.PgTpCanonical,
}
ext := db.Ext(ctx, "mint")
if rows, err := sqlx.NamedQuery(ext, `
SELECT *
FROM offers
WHERE owner = :owner
AND token = :token
AND propagation = :propagation
`, offer); err != nil {
return nil, errors.Trace(err)
} else if !rows.Next() {
return nil, nil
} else if err := rows.StructScan(&offer); err != nil {
defer rows.Close()
return nil, errors.Trace(err)
} else if err := rows.Close(); err != nil {
return nil, errors.Trace(err)
}
return &offer, nil
}
// LoadCanonicalOfferByID attempts to load the canonical offer for the given
// id.
func LoadCanonicalOfferByID(
ctx context.Context,
id string,
) (*Offer, error) {
owner, token, err := mint.NormalizedOwnerAndTokenFromID(ctx, id)
if err != nil {
return nil, errors.Trace(err)
}
return LoadCanonicalOfferByOwnerToken(ctx, owner, token)
}
// LoadPropagatedOfferByOwnerToken attempts to load the propagated offer for
// the given owner and token.
func LoadPropagatedOfferByOwnerToken(
ctx context.Context,
owner string,
token string,
) (*Offer, error) {
offer := Offer{
Owner: owner,
Token: token,
Propagation: mint.PgTpPropagated,
}
ext := db.Ext(ctx, "mint")
if rows, err := sqlx.NamedQuery(ext, `
SELECT *
FROM offers
WHERE owner = :owner
AND token = :token
AND propagation = :propagation
`, offer); err != nil {
return nil, errors.Trace(err)
} else if !rows.Next() {
return nil, nil
} else if err := rows.StructScan(&offer); err != nil {
defer rows.Close()
return nil, errors.Trace(err)
} else if err := rows.Close(); err != nil {
return nil, errors.Trace(err)
}
return &offer, nil
}
// LoadPropagatedOfferByID attempts to load the propagated offer for the given
// id.
func LoadPropagatedOfferByID(
ctx context.Context,
id string,
) (*Offer, error) {
owner, token, err := mint.NormalizedOwnerAndTokenFromID(ctx, id)
if err != nil {
return nil, errors.Trace(err)
}
return LoadPropagatedOfferByOwnerToken(ctx, owner, token)
}
// LoadOfferListByBaseAsset loads a balance list by base asset.
func LoadOfferListByBaseAsset(
ctx context.Context,
createdBefore time.Time,
limit uint,
asset string,
) ([]Offer, error) {
query := map[string]interface{}{
"base_asset": asset,
"created_before": createdBefore.UTC(),
"limit": limit,
}
ext := db.Ext(ctx, "mint")
rows, err := sqlx.NamedQuery(ext, `
SELECT *
FROM offers
WHERE base_asset = :base_asset
AND created < :created_before
ORDER BY created DESC
LIMIT :limit
`, query)
if err != nil {
return nil, errors.Trace(err)
}
offers := []Offer{}
defer rows.Close()
for rows.Next() {
o := Offer{}
err := rows.StructScan(&o)
if err != nil {
return nil, errors.Trace(err)
}
offers = append(offers, o)
}
return offers, nil
}
// LoadOfferListByQuoteAsset loads a balance list by quote asset.
func LoadOfferListByQuoteAsset(
ctx context.Context,
createdBefore time.Time,
limit uint,
asset string,
) ([]Offer, error) {
query := map[string]interface{}{
"quote_asset": asset,
"created_before": createdBefore.UTC(),
"limit": limit,
}
ext := db.Ext(ctx, "mint")
rows, err := sqlx.NamedQuery(ext, `
SELECT *
FROM offers
WHERE quote_asset = :quote_asset
AND created < :created_before
ORDER BY created DESC
LIMIT :limit
`, query)
if err != nil {
return nil, errors.Trace(err)
}
offers := []Offer{}
defer rows.Close()
for rows.Next() {
o := Offer{}
err := rows.StructScan(&o)
if err != nil {
return nil, errors.Trace(err)
}
offers = append(offers, o)
}
return offers, nil
}