forked from Cogwheel-Validator/spectra-gnoland-indexer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransactions.go
More file actions
589 lines (556 loc) · 18.6 KB
/
Copy pathtransactions.go
File metadata and controls
589 lines (556 loc) · 18.6 KB
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
package handlers
import (
"context"
"encoding/base64"
"fmt"
"strconv"
"strings"
"time"
humatypes "github.com/Cogwheel-Validator/spectra-gnoland-indexer/api/huma-types"
"github.com/Cogwheel-Validator/spectra-gnoland-indexer/pkgs/database"
)
type TransactionsHandler struct {
db TransactionDbHandler
chainName string
}
func NewTransactionsHandler(db TransactionDbHandler, chainName string) *TransactionsHandler {
return &TransactionsHandler{db: db, chainName: chainName}
}
// GetTransactionBasic retrieves basic transaction details by tx hash
func (h *TransactionsHandler) GetTransactionBasic(
ctx context.Context,
input *humatypes.TransactionGetInput,
) (*humatypes.TransactionBasicGetOutput, error) {
input.TxHash = strings.Trim(input.TxHash, " ")
txHashBase64, err := parseTxHash(input.TxHash)
if err != nil {
return nil, badRequest("transaction hash is not valid base64 encoded")
}
transaction, err := h.db.GetTransaction(ctx, txHashBase64, h.chainName)
if err != nil {
return nil, mapDbError(
"GetTransaction",
fmt.Sprintf("transaction with hash %s not found", input.TxHash),
err,
)
}
return &humatypes.TransactionBasicGetOutput{
Body: *transaction,
}, nil
}
// GetTransactionMessage retrieves all messages within a transaction by tx hash
func (h *TransactionsHandler) GetTransactionMessage(
ctx context.Context,
input *humatypes.TransactionGetInput,
) (*humatypes.TransactionMessageGetOutput, error) {
input.TxHash = strings.Trim(input.TxHash, " ")
txHashBase64, err := parseTxHash(input.TxHash)
if err != nil {
return nil, badRequest("transaction hash is not valid base64 encoded")
}
response := make(map[int16]humatypes.TransactionMessage)
msgTypes, err := h.db.GetMsgTypes(ctx, txHashBase64, h.chainName)
if err != nil {
return nil, mapDbError(
"GetMsgTypes",
fmt.Sprintf("transaction with hash %s not found", input.TxHash),
err,
)
}
for _, msgType := range msgTypes {
switch msgType {
case "bank_msg_send":
if err := h.getBankSendResponse(ctx, msgType, txHashBase64, h.chainName, response); err != nil {
return nil, err
}
case "bank_msg_multi_send":
if err := h.getBankMultiSendResponse(ctx, msgType, txHashBase64, h.chainName, response); err != nil {
return nil, err
}
case "vm_msg_call":
if err := h.getMsgCallResponse(ctx, msgType, txHashBase64, h.chainName, response); err != nil {
return nil, err
}
case "vm_msg_add_package":
if err := h.getMsgAddPackageResponse(ctx, msgType, txHashBase64, h.chainName, response); err != nil {
return nil, err
}
case "vm_msg_run":
if err := h.getMsgRunResponse(ctx, msgType, txHashBase64, h.chainName, response); err != nil {
return nil, err
}
case "auth_msg_create_session":
if err := h.getMsgAuthCrSessionResponse(ctx, msgType, txHashBase64, h.chainName, response); err != nil {
return nil, err
}
case "auth_msg_revoke_session":
if err := h.getMsgAuthRvSessionResponse(ctx, msgType, txHashBase64, h.chainName, response); err != nil {
return nil, err
}
case "auth_msg_revoke_all_sessions":
if err := h.getMsgAuthRvAllSessionsResponse(ctx, msgType, txHashBase64, h.chainName, response); err != nil {
return nil, err
}
default:
// An unknown message type coming out of the database is a server-side
// integrity problem, not something the caller can fix. Log it and
// return a generic 500 so we don't expose the internal type name.
return nil, internalError(
"GetTransactionMessage",
fmt.Errorf("unknown message type %q for tx %s", msgType, input.TxHash),
)
}
}
return &humatypes.TransactionMessageGetOutput{
Body: response,
}, nil
}
// GetTransactionsByCursor returns a page of transactions using keyset (cursor) pagination.
//
// The response is always newest-first: transactions[0] is the newest row on the page and
// transactions[len-1] is the oldest. Cursors are built from the (block_height, tx_hash)
// pair of boundary rows so the caller can walk the history in either direction:
// - NextCursor points at the oldest row; use it with direction=next to load older data.
// - PrevCursor points at the newest row; use it with direction=prev to load newer data.
func (h *TransactionsHandler) GetTransactionsByCursor(
ctx context.Context,
input *humatypes.TransactionGeneralListByCursorGetInput,
) (*humatypes.TransactionGeneralListByCursorGetOutput, error) {
limit := input.Limit
if limit == 0 {
limit = 25
}
if limit > 100 {
return nil, badRequest("invalid limit (1..100)")
}
direction := input.Direction
if direction == "" {
direction = database.Next
}
if direction != database.Next && direction != database.Prev {
return nil, badRequest("invalid direction (must be 'next' or 'prev')")
}
if direction == database.Prev && input.Cursor == "" {
return nil, badRequest("direction=prev requires a cursor")
}
transactions, hasMore, err := h.db.GetTransactionsByRange(
ctx, h.chainName, input.Cursor, limit, direction,
)
if err != nil {
return nil, mapDbError("GetTransactionsByRange", "transactions not found", err)
}
body := humatypes.TransactionsRangeBody{
Transactions: transactions,
}
if len(transactions) > 0 {
newest := transactions[0]
oldest := transactions[len(transactions)-1]
newestCur, err := makeTxCursor(newest.BlockHeight, newest.TxHash)
if err != nil {
return nil, internalError("GetTransactionsByCursor.makeTxCursor", err)
}
oldestCur, err := makeTxCursor(oldest.BlockHeight, oldest.TxHash)
if err != nil {
return nil, internalError("GetTransactionsByCursor.makeTxCursor", err)
}
switch direction {
case database.Next:
body.HasNext = hasMore
if hasMore {
body.NextCursor = &oldestCur
}
// A prev page exists only when the caller supplied a cursor, since
// the initial fetch (no cursor) already starts at the head.
if input.Cursor != "" {
body.HasPrev = true
body.PrevCursor = &newestCur
}
case database.Prev:
// We walked toward the head: hasMore means newer rows still remain
// between this page and the head.
body.HasPrev = hasMore
if hasMore {
body.PrevCursor = &newestCur
}
// A prev call implies the caller was already deeper in history, so
// older rows always exist past the oldest row on this page.
body.HasNext = true
body.NextCursor = &oldestCur
}
}
return &humatypes.TransactionGeneralListByCursorGetOutput{
Body: body,
}, nil
}
// parseTxHash decodes a 44-character transaction hash that is either standard base64
// ("+" and "/" characters) or base64url ("-" and "_" characters). It always returns
// the hash re-encoded as standard base64, which is what the database expects.
func parseTxHash(s string) (string, error) {
normalized := strings.NewReplacer("-", "+", "_", "/").Replace(s)
raw, err := base64.StdEncoding.DecodeString(normalized)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(raw), nil
}
// makeTxCursor encodes a (block_height, tx_hash) pair into the "<height>|<hash>" form
// used by the transactions range API. The tx hash is received as standard base64 and
// re-encoded as URL-safe base64 so the cursor is safe to pass as a query parameter.
func makeTxCursor(blockHeight uint64, txHashB64 string) (string, error) {
raw, err := base64.StdEncoding.DecodeString(txHashB64)
if err != nil {
return "", fmt.Errorf("error decoding tx hash: %w", err)
}
return strconv.FormatUint(blockHeight, 10) + "|" + base64.URLEncoding.Strict().EncodeToString(raw), nil
}
// GetLastXTransactions retrieves the most recent X transactions
func (h *TransactionsHandler) GetLastXTransactions(
ctx context.Context,
input *humatypes.LastXTransactionsGetInput,
) (*humatypes.LastXTransactionsGetOutput, error) {
transactions, err := h.db.GetLastXTransactions(ctx, h.chainName, input.Amount, nil)
if err != nil {
return nil, mapDbError("GetLastXTransactions", "no recent transactions found", err)
}
return &humatypes.LastXTransactionsGetOutput{Body: transactions}, nil
}
// GetTotalTxCount24h returns the total number of transactions in the last 24 hours
func (h *TransactionsHandler) GetTotalTxCount24h(
ctx context.Context,
input *humatypes.TotalTxCount24hGetInput,
) (*humatypes.TotalTxCount24hGetOutput, error) {
count, err := h.db.GetTotalTxCount24h(ctx, h.chainName)
if err != nil {
return nil, mapDbError("GetTotalTxCount24h", "transaction count for last 24h not found", err)
}
body := &humatypes.TotalTxCount24hBody{Count: count}
return &humatypes.TotalTxCount24hGetOutput{Body: body}, nil
}
// GetTotalTxCountByDate returns the transaction count per day within the given date range
func (h *TransactionsHandler) GetTotalTxCountByDate(
ctx context.Context,
input *humatypes.TxCountByDateGetInput,
) (*humatypes.TxCountByDateGetOutput, error) {
startDate := input.StartDate
endDate := input.EndDate
if !startDate.Before(endDate.Time) {
return nil, badRequest("start_date must be before end_date")
}
if endDate.Sub(startDate.Time) > 24*time.Hour*30 {
return nil, badRequest("end_date must be within 30 days of start_date")
}
counts, err := h.db.GetTotalTxCountByDate(ctx, h.chainName, startDate, endDate, input.SortOrder)
if err != nil {
return nil, mapDbError(
"GetTotalTxCountByDate",
"transaction count for the given date range not found",
err,
)
}
if len(counts) == 0 {
return nil, notFound("transaction count for the given date range not found")
}
return &humatypes.TxCountByDateGetOutput{Body: counts}, nil
}
// GetTotalTxCountByHour returns the transaction count per hour within the given datetime range
func (h *TransactionsHandler) GetTotalTxCountByHour(
ctx context.Context,
input *humatypes.TxCountByHourGetInput,
) (*humatypes.TxCountByHourGetOutput, error) {
if !input.StartTimestamp.Before(input.EndTimestamp) {
return nil, badRequest("start_timestamp must be before end_timestamp")
}
if input.EndTimestamp.Sub(input.StartTimestamp) > 24*time.Hour*7 { // 7 days
return nil, badRequest("end_timestamp must be within 7 days of start_timestamp")
}
counts, err := h.db.GetTotalTxCountByHour(ctx, h.chainName, input.StartTimestamp, input.EndTimestamp, input.SortOrder)
if err != nil {
return nil, mapDbError(
"GetTotalTxCountByHour",
"transaction count for the given time range not found",
err,
)
}
if len(counts) == 0 {
return nil, notFound("transaction count for the given time range not found")
}
return &humatypes.TxCountByHourGetOutput{Body: counts}, nil
}
// GetVolumeByDate returns the transaction volume grouped by denom per day within the given date range
func (h *TransactionsHandler) GetVolumeByDate(ctx context.Context, input *humatypes.VolumeByDateGetInput) (*humatypes.VolumeByDateGetOutput, error) {
if !input.StartDate.Before(input.EndDate.Time) {
return nil, badRequest("start_date must be before end_date")
}
if input.EndDate.Sub(input.StartDate.Time) > 24*time.Hour*30 {
return nil, badRequest("end_date must be within 30 days of start_date")
}
volume, err := h.db.GetVolumeByDate(ctx, h.chainName, input.StartDate, input.EndDate, input.SortOrder)
if err != nil {
return nil, mapDbError(
"GetVolumeByDate",
"volume for the given date range not found",
err,
)
}
if len(volume) == 0 {
return nil, notFound("volume for the given date range not found")
}
return &humatypes.VolumeByDateGetOutput{Body: volume}, nil
}
// GetVolumeByHour returns the transaction volume grouped by denom per hour within the given datetime range
func (h *TransactionsHandler) GetVolumeByHour(ctx context.Context, input *humatypes.VolumeByHourGetInput) (*humatypes.VolumeByHourGetOutput, error) {
if !input.StartTimestamp.Before(input.EndTimestamp) {
return nil, badRequest("start_timestamp must be before end_timestamp")
}
if input.EndTimestamp.Sub(input.StartTimestamp) > 24*time.Hour*7 { // 7 days
return nil, badRequest("end_timestamp must be within 7 days of start_timestamp")
}
volume, err := h.db.GetVolumeByHour(ctx, h.chainName, input.StartTimestamp, input.EndTimestamp, input.SortOrder)
if err != nil {
return nil, mapDbError(
"GetVolumeByHour",
"volume for the given time range not found",
err,
)
}
return &humatypes.VolumeByHourGetOutput{Body: volume}, nil
}
// Helper method that collects msg call data from the database and adds it to the response
func (h *TransactionsHandler) getMsgCallResponse(
ctx context.Context,
msgType string,
txHash string,
chainName string,
response map[int16]humatypes.TransactionMessage,
) error {
data, err := h.db.GetMsgCall(ctx, txHash, chainName)
if err != nil {
return internalError("GetMsgCall", err)
}
for _, d := range data {
index := d.MessageCounter
response[index] = humatypes.TransactionMessage{
MessageType: msgType,
TxHash: d.TxHash,
Timestamp: d.Timestamp,
Signers: d.Signers,
Caller: d.Caller,
Send: d.Send,
PkgPath: d.PkgPath,
FuncName: d.FuncName,
Args: d.Args,
MaxDeposit: d.MaxDeposit,
}
}
return nil
}
// Helper method that collects add package data from the database and adds it to the response
func (h *TransactionsHandler) getMsgAddPackageResponse(
ctx context.Context,
msgType string,
txHash string,
chainName string,
response map[int16]humatypes.TransactionMessage,
) error {
data, err := h.db.GetMsgAddPackage(ctx, txHash, chainName)
if err != nil {
return internalError("GetMsgAddPackage", err)
}
for _, d := range data {
index := d.MessageCounter
response[index] = humatypes.TransactionMessage{
MessageType: msgType,
TxHash: d.TxHash,
Timestamp: d.Timestamp,
Signers: d.Signers,
Creator: d.Creator,
PkgPath: d.PkgPath,
PkgName: d.PkgName,
PkgFileNames: d.PkgFileNames,
Send: d.Send,
MaxDeposit: d.MaxDeposit,
}
}
return nil
}
// Helper method that collects msg run data from the database and adds it to the response
func (h *TransactionsHandler) getMsgRunResponse(
ctx context.Context,
msgType string,
txHash string,
chainName string,
response map[int16]humatypes.TransactionMessage,
) error {
data, err := h.db.GetMsgRun(ctx, txHash, chainName)
if err != nil {
return internalError("GetMsgRun", err)
}
for _, d := range data {
index := d.MessageCounter
response[index] = humatypes.TransactionMessage{
MessageType: msgType,
TxHash: d.TxHash,
Timestamp: d.Timestamp,
Signers: d.Signers,
Caller: d.Caller,
PkgPath: d.PkgPath,
PkgName: d.PkgName,
PkgFileNames: d.PkgFileNames,
Send: d.Send,
MaxDeposit: d.MaxDeposit,
}
}
return nil
}
// Helper method that collects bank multi-send data from the database and adds it to the response.
// Rows are aggregated by message_counter: direction=true rows become Outputs, direction=false become Inputs.
func (h *TransactionsHandler) getBankMultiSendResponse(
ctx context.Context,
msgType string,
txHash string,
chainName string,
response map[int16]humatypes.TransactionMessage,
) error {
data, err := h.db.GetBankMultiSend(ctx, txHash, chainName)
if err != nil {
return internalError("GetBankMultiSend", err)
}
type agg struct {
base humatypes.TransactionMessage
inputs []humatypes.MultiSendEntry
outputs []humatypes.MultiSendEntry
}
byCounter := make(map[int16]*agg)
for _, d := range data {
idx := d.MessageCounter
if _, ok := byCounter[idx]; !ok {
byCounter[idx] = &agg{
base: humatypes.TransactionMessage{
MessageType: msgType,
TxHash: d.TxHash,
Timestamp: d.Timestamp,
Signers: d.Signers,
},
}
}
entry := humatypes.MultiSendEntry{Address: d.Address, Coins: d.Coins}
if d.Direction {
byCounter[idx].outputs = append(byCounter[idx].outputs, entry)
} else {
byCounter[idx].inputs = append(byCounter[idx].inputs, entry)
}
}
for idx, a := range byCounter {
msg := a.base
msg.Inputs = a.inputs
msg.Outputs = a.outputs
response[idx] = msg
}
return nil
}
// Helper method that collects auth create-session data from the database and adds it to the response
func (h *TransactionsHandler) getMsgAuthCrSessionResponse(
ctx context.Context,
msgType string,
txHash string,
chainName string,
response map[int16]humatypes.TransactionMessage,
) error {
data, err := h.db.GetMsgAuthCrSession(ctx, txHash, chainName)
if err != nil {
return internalError("GetMsgAuthCrSession", err)
}
for _, d := range data {
index := d.MessageCounter
expiresAt := d.ExpiresAt
spendPeriod := d.SpendPeriod
response[index] = humatypes.TransactionMessage{
MessageType: msgType,
TxHash: d.TxHash,
Timestamp: d.Timestamp,
Signers: d.Signers,
Creator: d.Creator,
SessionKey: d.SessionKey,
ExpiresAt: &expiresAt,
AllowPaths: d.AllowPaths,
SpendLimit: d.SpendLimit,
SpendPeriod: &spendPeriod,
}
}
return nil
}
// Helper method that collects auth revoke-session data from the database and adds it to the response
func (h *TransactionsHandler) getMsgAuthRvSessionResponse(
ctx context.Context,
msgType string,
txHash string,
chainName string,
response map[int16]humatypes.TransactionMessage,
) error {
data, err := h.db.GetMsgAuthRvSession(ctx, txHash, chainName)
if err != nil {
return internalError("GetMsgAuthRvSession", err)
}
for _, d := range data {
index := d.MessageCounter
response[index] = humatypes.TransactionMessage{
MessageType: msgType,
TxHash: d.TxHash,
Timestamp: d.Timestamp,
Signers: d.Signers,
Creator: d.Creator,
SessionKey: d.SessionKey,
}
}
return nil
}
// Helper method that collects auth revoke-all-sessions data from the database and adds it to the response
func (h *TransactionsHandler) getMsgAuthRvAllSessionsResponse(
ctx context.Context,
msgType string,
txHash string,
chainName string,
response map[int16]humatypes.TransactionMessage,
) error {
data, err := h.db.GetMsgAuthRvAllSessions(ctx, txHash, chainName)
if err != nil {
return internalError("GetMsgAuthRvAllSessions", err)
}
for _, d := range data {
index := d.MessageCounter
response[index] = humatypes.TransactionMessage{
MessageType: msgType,
TxHash: d.TxHash,
Timestamp: d.Timestamp,
Signers: d.Signers,
Creator: d.Creator,
}
}
return nil
}
// Helper method that collects bank send data from the database and adds it to the response
func (h *TransactionsHandler) getBankSendResponse(
ctx context.Context,
msgType string,
txHash string,
chainName string,
response map[int16]humatypes.TransactionMessage,
) error {
data, err := h.db.GetBankSend(ctx, txHash, chainName)
if err != nil {
return internalError("GetBankSend", err)
}
for _, d := range data {
index := d.MessageCounter
response[index] = humatypes.TransactionMessage{
MessageType: msgType,
TxHash: d.TxHash,
Timestamp: d.Timestamp,
Signers: d.Signers,
FromAddress: d.FromAddress,
ToAddress: d.ToAddress,
Amount: d.Amount,
}
}
return nil
}