/
fights.go
378 lines (320 loc) · 11.7 KB
/
fights.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
372
373
374
375
376
377
378
package server
import (
"database/sql"
"encoding/hex"
"fmt"
"math/rand"
"net/http"
"strconv"
"time"
"github.com/labstack/echo/v4"
db "github.com/reliablestaking/zombie-fight-club-server/db"
"github.com/sirupsen/logrus"
)
//GetMyNfts get all nfts I own
func (s Server) GetNftsToFight(c echo.Context) (err error) {
log := logrus.WithContext(c.Request().Context())
dbUser := c.Get("user").(*db.User)
typeParam := c.QueryParam("type")
if typeParam == "" {
log.Warn("No type provided")
return echo.NewHTTPError(http.StatusBadRequest, "No type provided")
}
ownedOnly := false
ownedParamString := c.QueryParam("owned")
if ownedParamString == "true" {
ownedOnly = true
}
log.Infof("User %d is getting nfts with type %s", dbUser.ID, typeParam)
nftDtos := make([]Nft, 0)
if ownedOnly {
// get nfts the user owns too
myAssets, err := s.GetAssetsForUser(c.Request().Context(), *dbUser)
if err != nil {
log.WithError(err).Error("Error getting my assets")
return s.RenderError("Error getting my assets", c)
}
// convert to nfts
for _, asset := range myAssets {
if asset.Type == typeParam {
// add to list
newListNft := Nft{
Name: asset.Name,
Type: asset.Type,
UserOwns: true,
Wins: asset.Wins,
Loses: asset.Loses,
}
if asset.Type == "Zombie" {
newListNft.IPFS = s.ZombieMeta[asset.Name]
} else if asset.Type == "Hunter" {
newListNft.IPFS = s.HunterMeta[asset.Name]
}
nftDtos = append(nftDtos, newListNft)
}
}
} else {
nameParam := c.QueryParam("name")
if nameParam == "" {
listedNfts, err := s.Store.GetListedNfts(typeParam, 100, true)
if err != nil {
log.WithError(err).Error("Error getting listed nfts")
return s.RenderError("Error getting listed nfts", c)
}
nftDtos = s.convertNftToDto(listedNfts)
} else {
listedNfts, err := s.Store.GetListedNftsByName(typeParam, nameParam)
if err != nil {
log.WithError(err).Error("Error getting listed nfts")
return s.RenderError("Error getting listed nfts", c)
}
nftDtos = s.convertNftToDto(listedNfts)
}
}
return c.JSON(http.StatusOK, nftDtos)
}
//CreateFight create new fight
func (s Server) CreateFight(c echo.Context) (err error) {
log := logrus.WithContext(c.Request().Context())
// bind incoming object
fight := new(db.FightDto)
if err = c.Bind(fight); err != nil {
log.WithError(err).Errorf("Error binding")
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
dbUser := c.Get("user").(*db.User)
log.Infof("Creating fight between %s and %s for user %d", fight.HunterName, fight.ZombieName, dbUser.ID)
// check that zombie is availabe to fight and still owned by user
zombies, err := s.Store.GetListedNftByName(fight.ZombieName)
if err != nil {
log.WithError(err).Errorf("Error checking if user owns zombie %s", fight.ZombieName)
return s.RenderError("Error checking if user owns zombie", c)
}
if len(zombies) == 0 {
log.Warnf("Zombie %s not for listed", fight.ZombieName)
return echo.NewHTTPError(http.StatusBadRequest, "Zombie not listed")
}
// if not listed, must be owned by current user
if !zombies[0].ListAmount.Valid {
if zombies[0].UserID == dbUser.ID {
logrus.Infof("User owns this zombie, so okay it's not listed")
zombies[0].ListAmount = sql.NullInt16{Int16: 0, Valid: true}
} else {
log.Warnf("Zombie %s not listed and user doenst own", fight.ZombieName)
return echo.NewHTTPError(http.StatusBadRequest, "Zombie not listed")
}
}
// check that owned by user system thinks it is
ownsZombie, err := s.doesUserOwnNft(c.Request().Context(), fight.ZombieName, zombies[0].UserID)
if err != nil {
log.WithError(err).Errorf("Error checking user owns %s", fight.ZombieName)
return s.RenderError("Error checking if user owns zombie", c)
}
if !ownsZombie {
log.Warnf("Zombie %s not owned by user %d", fight.ZombieName, zombies[0].UserID)
return echo.NewHTTPError(http.StatusBadRequest, "Zombie not owned by user anymore")
}
log.Infof("Zombie %s is valid", fight.ZombieName)
// check that hunter is available to fight and still owned by user
hunters, err := s.Store.GetListedNftByName(fight.HunterName)
if err != nil {
log.WithError(err).Errorf("Error checking if user owns hunter %s", fight.HunterName)
return s.RenderError("Error checking if user owns hunter", c)
}
if len(hunters) == 0 {
log.Warnf("Hunter %s not for listed", fight.HunterName)
return echo.NewHTTPError(http.StatusBadRequest, "Hunter not listed")
}
// if not listed, must be owned by current user
if !hunters[0].ListAmount.Valid {
if hunters[0].UserID == dbUser.ID {
logrus.Infof("User owns this hunter, so okay it's not listed")
hunters[0].ListAmount = sql.NullInt16{Int16: 0, Valid: true}
} else {
log.Warnf("Hunter %s not listed and user doenst own", fight.HunterName)
return echo.NewHTTPError(http.StatusBadRequest, "Zombie not listed")
}
}
// check that owned by user system thinks it is
ownsHunter, err := s.doesUserOwnNft(c.Request().Context(), fight.HunterName, hunters[0].UserID)
if err != nil {
log.WithError(err).Errorf("Error checking user owns %s", fight.HunterName)
return s.RenderError("Error checking if user owns zombie", c)
}
if !ownsHunter {
log.Warnf("Hunter %s not owned by user %d", fight.HunterName, hunters[0].UserID)
return echo.NewHTTPError(http.StatusBadRequest, "Hunter not owned by user anymore")
}
log.Infof("Hunter %s is valid", fight.HunterName)
// check that user owns at least one or the other (unless they are service account)
if dbUser.NftkeymeAccessToken != "" && zombies[0].UserID != dbUser.ID && hunters[0].UserID != dbUser.ID {
log.Warn("User doesn't own zombie or hunter, can't create fight")
return echo.NewHTTPError(http.StatusBadRequest, "User doesn't own zombie or hunter, can't create fight")
}
// calculate cost
//zombieCost := int64(zombies[0].ListAmount.Int16)
// if zombies[0].UserID == dbUser.ID {
// log.Infof("User %d owns zombie %s so not cost", dbUser.ID, fight.ZombieName)
// //zombieCost = 0
// } else {
// figure out what address asset lives at
assetName := s.ZombiePolicyId + hex.EncodeToString([]byte(fight.ZombieName))
logrus.Infof("Finding address for asset %s", assetName)
addresses, err := s.BlockforstIpfsClient.GetAddressesForAsset(assetName)
if err != nil {
log.WithError(err).Errorf("Error getting asset address %s", fight.ZombieName)
return s.RenderError("Error getting asset address", c)
} else if len(addresses) == 0 || addresses[0].Address == "" {
log.WithError(err).Errorf("No asset address %s", fight.HunterName)
return s.RenderError("No asset address", c)
}
logrus.Infof("Setting zombie send address to %d / %s / %s", len(addresses), addresses[0].Address, addresses[0].Quantity)
fight.ZombieSendAddress = addresses[0].Address
//}
//hunterCost := int64(hunters[0].ListAmount.Int16)
// if hunters[0].UserID == dbUser.ID {
// log.Infof("User %d owns hunter %s so not cost", dbUser.ID, fight.HunterName)
// //hunterCost = 0
// } else {
// figure out what address asset lives at
assetName = s.HunterPolicyId + hex.EncodeToString([]byte(fight.HunterName))
addresses, err = s.BlockforstIpfsClient.GetAddressesForAsset(assetName)
if err != nil {
log.WithError(err).Errorf("Error getting asset address %s", fight.HunterName)
return s.RenderError("Error getting asset address", c)
} else if len(addresses) == 0 {
log.WithError(err).Errorf("No asset address %s", fight.HunterName)
return s.RenderError("No asset address", c)
}
logrus.Infof("Setting hunter send address to %s", addresses[0].Address)
fight.HunterSendAddress = addresses[0].Address
// }
paymentAmountAda := int64(s.BaseCostAda)
logrus.Infof("Calculated a payment amoutn of %d", paymentAmountAda)
// calculate dust
dustTry := 0
for {
if dustTry == 5 {
log.WithError(err).Errorf("Error getting unique payment amount")
return s.RenderError("Error getting unique payment amount", c)
}
cost := (paymentAmountAda * 1000000) + int64(rand.Intn(500000))
fightCheck, err := s.Store.GetFightForPaymentLastFifteen(cost)
if err != nil {
log.WithError(err).Errorf("Error checking fights")
return s.RenderError("Error checking fights", c)
}
if fightCheck == nil {
fight.PaymentAmountLovelace = cost
break
}
dustTry++
}
// set payment address
fight.PaymentAddress = s.PaymentAddress
// set initial status
fight.Status = "PENDING"
// persist
fightId, err := s.Store.CreateFight(*fight, hunters[0], zombies[0], *dbUser)
if err != nil {
log.WithError(err).Errorf("Error persisting fight")
return s.RenderError("Error persisting fight", c)
}
fight.ID = fightId
// set minutes til expired
fight.MinutesUntilExpired = 15
// set amount in ada
fight.PaymentAmountAda = lovelaceToString(int(fight.PaymentAmountLovelace))
return c.JSON(http.StatusOK, fight)
}
func lovelaceToString(lovelace int) string {
lovelaceString := strconv.Itoa(lovelace)
lovelaceLen := len(lovelaceString)
ada := lovelaceString[0 : lovelaceLen-6]
lace := lovelaceString[lovelaceLen-6 : lovelaceLen]
return ada + "." + lace
}
//GetFightById gets fight by id
func (s Server) GetFightById(c echo.Context) (err error) {
log := logrus.WithContext(c.Request().Context())
// get param
fightIdString := c.Param("fightId")
if fightIdString == "" {
return echo.NewHTTPError(http.StatusBadRequest, "No fight id provided")
}
fightId, err := strconv.Atoi(fightIdString)
if err != nil {
log.WithError(err).Errorf("Error getting fight with id %s", fightIdString)
return s.RenderError("Error converting fight id to int", c)
}
log.Infof("Getting fight id %d", fightId)
dbUser := c.Get("user").(*db.User)
fights, err := s.Store.GetFightsForUserAndId(*dbUser, fightId)
if err != nil {
log.WithError(err).Error("Error getting fights for user")
return s.RenderError("Error getting fights", c)
}
fightDtos := make([]db.FightDto, 0)
if len(fights) > 0 {
fightDtos = s.convertFightToDto(fights)
} else {
return c.String(http.StatusNotFound, "Fight id not found")
}
return c.JSON(http.StatusOK, fightDtos[0])
}
func (s Server) convertFightToDto(fights []db.FightDb) []db.FightDto {
dto := make([]db.FightDto, 0)
for _, f := range fights {
fight := db.FightDto{
ID: f.ID,
ZombieName: f.ZombieName,
HunterName: f.HunterName,
Status: f.Status,
CreatedDate: &f.CreatedDate,
PaymentAddress: f.PaymentAddress,
PaymentAmountLovelace: f.PaymentAmountLovelace,
}
if f.IPFS.Valid {
fight.FightIPFS = f.IPFS.String
}
if f.IPFSAlien.Valid {
fight.AlienIPFS = f.IPFSAlien.String
}
fight.PaymentAmountAda = lovelaceToString(int(fight.PaymentAmountLovelace))
minutes := int(fight.CreatedDate.Add(15 * time.Minute).Sub(time.Now()).Minutes())
//logrus.Infof("Comparing %s to %s with a diff of minutes %d", fight.CreatedDate, time.Now(), minutes)
if minutes > 0 {
fight.MinutesUntilExpired = minutes
} else {
fight.MinutesUntilExpired = 0
}
// PENDING > QUEUED > STAGED > MINTED > CONFIRMED > MINTED
if fight.Status == "PENDING" {
if time.Now().Sub(*fight.CreatedDate).Minutes() > 15 {
fight.Status = "EXPIRED"
} else {
fight.Status = "AWAITING_PAYMENT"
}
} else if fight.Status == "QUEUED" || fight.Status == "STAGED" || fight.Status == "MINTED" {
fight.Status = "PAYMENT_RECEIVED"
} else if fight.Status == "CONFIRMED" {
fight.Status = "MINTED"
}
// set winner text
if f.HunterLifeBar.Valid && f.ZombieLifeBar.Valid {
if f.HunterLifeBar.Int64 > f.ZombieLifeBar.Int64 {
fight.Winner = f.HunterName
fight.Loser = f.ZombieName
} else {
fight.Winner = f.ZombieName
fight.Loser = f.HunterName
}
}
// set tweet link
if f.TweetID.Valid {
fight.TweetLink = fmt.Sprintf("https://twitter.com/ZFCBot/status/%s", f.TweetID.String)
}
dto = append(dto, fight)
}
return dto
}