-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgateway_handlers.go
More file actions
923 lines (788 loc) · 28.1 KB
/
gateway_handlers.go
File metadata and controls
923 lines (788 loc) · 28.1 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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
// gateway_handlers.go
// Gateway-proxied implementations of API handlers
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/go-chi/chi/v5"
)
// handleDashboardMetricsViaGateway computes dashboard metrics from gateway ledger data
func (app *App) handleDashboardMetricsViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
// Fetch recent ledgers from gateway (last 100)
ledgers, err := app.gateway.GetLedgers(ctx, network, 1, 999999999, 100, "")
if err != nil {
log.Printf("Error fetching ledgers from gateway for metrics: %v", err)
w.Write([]byte(`
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<div class="bg-red-900 border border-red-700 rounded-lg p-6">
<p class="text-red-200">Error fetching data from gateway</p>
</div>
</div>
`))
return
}
if len(ledgers) == 0 {
w.Write([]byte(`
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<div class="bg-yellow-900 border border-yellow-700 rounded-lg p-6">
<p class="text-yellow-200">No ledger data available</p>
</div>
</div>
`))
return
}
// Compute metrics from ledgers
// Note: Gateway returns ledgers in ascending order (oldest first)
var totalTx, successfulTx, failedTx int64
var latestLedger, earliestLedger int64
var latestTime, earliestTime string
for _, ledger := range ledgers {
successCount := getInt64(ledger, "successful_tx_count")
failedCount := getInt64(ledger, "failed_tx_count")
seq := getInt64(ledger, "sequence")
closedAt := getString(ledger, "closed_at")
totalTx += successCount + failedCount
successfulTx += successCount
failedTx += failedCount
// Track min/max ledger sequences regardless of order
if earliestLedger == 0 || seq < earliestLedger {
earliestLedger = seq
earliestTime = closedAt
}
if seq > latestLedger {
latestLedger = seq
latestTime = closedAt
}
}
successRate := float64(0)
if totalTx > 0 {
successRate = float64(successfulTx) / float64(totalTx) * 100
}
avgTxPerLedger := float64(totalTx) / float64(len(ledgers))
// Render HTML response (same format as original handler)
html := fmt.Sprintf(`
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-400 text-sm">Latest Ledger</p>
<p class="text-2xl font-bold text-white mt-1">%d</p>
</div>
<div class="w-12 h-12 bg-blue-900/50 rounded-lg flex items-center justify-center">
<svg class="w-6 h-6 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/>
</svg>
</div>
</div>
</div>
<div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-400 text-sm">Transactions (Last 100 Ledgers)</p>
<p class="text-2xl font-bold text-white mt-1">%d</p>
</div>
<div class="w-12 h-12 bg-green-900/50 rounded-lg flex items-center justify-center">
<svg class="w-6 h-6 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
</svg>
</div>
</div>
</div>
<div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-400 text-sm">Success Rate</p>
<p class="text-2xl font-bold text-white mt-1">%.1f%%</p>
</div>
<div class="w-12 h-12 bg-purple-900/50 rounded-lg flex items-center justify-center">
<svg class="w-6 h-6 text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
</svg>
</div>
</div>
</div>
<div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
<div class="flex items-center justify-between">
<div>
<p class="text-gray-400 text-sm">Avg TX/Ledger</p>
<p class="text-2xl font-bold text-white mt-1">%.1f</p>
</div>
<div class="w-12 h-12 bg-orange-900/50 rounded-lg flex items-center justify-center">
<svg class="w-6 h-6 text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"/>
</svg>
</div>
</div>
</div>
</div>
<p class="text-gray-500 text-xs">Data from %s to %s via gateway</p>
`, latestLedger, totalTx, successRate, avgTxPerLedger, earliestTime, latestTime)
w.Write([]byte(html))
}
// Helper functions for extracting values from map[string]interface{}
func getInt64(m map[string]interface{}, key string) int64 {
if v, ok := m[key]; ok {
switch val := v.(type) {
case float64:
return int64(val)
case int64:
return val
case int:
return int64(val)
case json.Number:
i, _ := val.Int64()
return i
}
}
return 0
}
func getString(m map[string]interface{}, key string) string {
if v, ok := m[key]; ok {
if s, ok := v.(string); ok {
return s
}
}
return ""
}
// handleAPILedgersViaGateway fetches ledgers from the gateway
func (app *App) handleAPILedgersViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
// Parse query parameters
limitStr := r.URL.Query().Get("limit")
offsetStr := r.URL.Query().Get("offset")
minSequenceStr := r.URL.Query().Get("min_sequence")
maxSequenceStr := r.URL.Query().Get("max_sequence")
sort := r.URL.Query().Get("sort") // sequence_asc, sequence_desc, closed_at_asc, closed_at_desc, tx_count_desc
limit := 100
if limitStr != "" {
if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 1000 {
limit = l
}
}
offset := 0
if offsetStr != "" {
if o, err := strconv.Atoi(offsetStr); err == nil && o >= 0 {
offset = o
}
}
// Validate sort parameter, default to sequence_desc (newest first)
validSorts := map[string]bool{
"sequence_asc": true,
"sequence_desc": true,
"closed_at_asc": true,
"closed_at_desc": true,
"tx_count_desc": true,
}
if sort == "" || !validSorts[sort] {
sort = "sequence_desc" // Default to newest first
}
// For gateway, we need start/end ledger sequences
// Default to a reasonable recent range if not specified
var start, end int64 = 0, 0
if minSequenceStr != "" {
if minSeq, err := strconv.ParseInt(minSequenceStr, 10, 64); err == nil {
start = minSeq
}
}
if maxSequenceStr != "" {
if maxSeq, err := strconv.ParseInt(maxSequenceStr, 10, 64); err == nil {
end = maxSeq
}
}
// If no range specified, use a default range (requires knowing latest ledger)
if start == 0 && end == 0 {
// Default to fetching recent ledgers - set end high to get latest
start = 1
end = 999999999 // Gateway will return what's available
}
// Gateway doesn't support offset natively, so we fetch offset+limit+1 records
// to detect if there's more data, then slice the result
fetchLimit := offset + limit + 1
if fetchLimit > 1000 {
fetchLimit = 1000
}
queryStart := time.Now()
ledgers, err := app.gateway.GetLedgers(ctx, network, start, end, fetchLimit, sort)
queryDuration := time.Since(queryStart)
log.Printf("[%s/gateway] Ledgers query took: %v (limit=%d, offset=%d)", network, queryDuration, limit, offset)
if err != nil {
log.Printf("Error fetching ledgers from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching ledgers: %v", err), http.StatusInternalServerError)
return
}
// Apply offset by slicing the result
if offset >= len(ledgers) {
response := map[string]interface{}{
"ledgers": []map[string]interface{}{},
"count": 0,
"has_more": false,
}
json.NewEncoder(w).Encode(response)
return
}
endIdx := offset + limit
if endIdx > len(ledgers) {
endIdx = len(ledgers)
}
result := ledgers[offset:endIdx]
// has_more is true if we have more data after this page
hasMore := len(ledgers) > endIdx
response := map[string]interface{}{
"ledgers": result,
"count": len(result),
"has_more": hasMore,
}
json.NewEncoder(w).Encode(response)
}
// handleAPILedgerViaGateway fetches a single ledger from the gateway
func (app *App) handleAPILedgerViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
sequenceStr := chi.URLParam(r, "sequence")
sequence, err := strconv.ParseInt(sequenceStr, 10, 64)
if err != nil {
http.Error(w, "Invalid sequence number", http.StatusBadRequest)
return
}
ledgers, err := app.gateway.GetLedgers(ctx, network, sequence, sequence, 1, "")
if err != nil {
log.Printf("Error fetching ledger from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching ledger: %v", err), http.StatusInternalServerError)
return
}
if len(ledgers) == 0 {
http.Error(w, "Ledger not found", http.StatusNotFound)
return
}
json.NewEncoder(w).Encode(ledgers[0])
}
// handleAPITransactionsViaGateway fetches transactions from the gateway
func (app *App) handleAPITransactionsViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
limitStr := r.URL.Query().Get("limit")
offsetStr := r.URL.Query().Get("offset")
ledgerStr := r.URL.Query().Get("ledger_sequence")
if ledgerStr == "" {
ledgerStr = r.URL.Query().Get("ledger") // backward compatibility
}
limit := 100
if limitStr != "" {
if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 1000 {
limit = l
}
}
offset := 0
if offsetStr != "" {
if o, err := strconv.Atoi(offsetStr); err == nil && o >= 0 {
offset = o
}
}
var start, end int64 = 1, 999999999
if ledgerStr != "" {
if ledger, err := strconv.ParseInt(ledgerStr, 10, 64); err == nil {
start = ledger
end = ledger
}
}
// Gateway doesn't support offset natively, so we fetch offset+limit+1 records
// to detect if there's more data, then slice the result.
fetchLimit := offset + limit + 1
if fetchLimit > 1000 {
fetchLimit = 1000 // Cap at 1000 to avoid excessive data transfer
}
queryStart := time.Now()
transactions, err := app.gateway.GetTransactions(ctx, network, start, end, fetchLimit)
queryDuration := time.Since(queryStart)
log.Printf("[%s/gateway] Transactions query took: %v (limit=%d, offset=%d)", network, queryDuration, limit, offset)
if err != nil {
log.Printf("Error fetching transactions from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching transactions: %v", err), http.StatusInternalServerError)
return
}
// Apply offset by slicing the result
if offset >= len(transactions) {
response := map[string]interface{}{
"transactions": []map[string]interface{}{},
"count": 0,
"has_more": false,
}
json.NewEncoder(w).Encode(response)
return
}
// Slice from offset to offset+limit
endIdx := offset + limit
if endIdx > len(transactions) {
endIdx = len(transactions)
}
result := transactions[offset:endIdx]
// has_more is true if we have more data after this page
hasMore := len(transactions) > endIdx
response := map[string]interface{}{
"transactions": result,
"count": len(result),
"has_more": hasMore,
}
json.NewEncoder(w).Encode(response)
}
// handleAPITransactionViaGateway fetches a single transaction from the gateway
func (app *App) handleAPITransactionViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
txHash := chi.URLParam(r, "hash")
if txHash == "" {
http.Error(w, "Missing transaction hash", http.StatusBadRequest)
return
}
details, err := app.gateway.GetTransactionDetails(ctx, network, txHash)
if err != nil {
log.Printf("Error fetching transaction from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching transaction: %v", err), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(details)
}
// handleAPIOperationsViaGateway fetches operations from the gateway with cursor pagination
func (app *App) handleAPIOperationsViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
params := make(map[string]string)
// Pagination params
if limit := r.URL.Query().Get("limit"); limit != "" {
params["limit"] = limit
} else {
params["limit"] = "100"
}
if cursor := r.URL.Query().Get("cursor"); cursor != "" {
params["cursor"] = cursor
}
// Filter params
if accountID := r.URL.Query().Get("account_id"); accountID != "" {
params["account_id"] = accountID
}
if txHash := r.URL.Query().Get("tx_hash"); txHash != "" {
params["tx_hash"] = txHash
}
if txHash := r.URL.Query().Get("transaction_hash"); txHash != "" {
params["tx_hash"] = txHash
}
if startLedger := r.URL.Query().Get("start_ledger"); startLedger != "" {
params["start_ledger"] = startLedger
}
if endLedger := r.URL.Query().Get("end_ledger"); endLedger != "" {
params["end_ledger"] = endLedger
}
queryStart := time.Now()
result, err := app.gateway.GetOperationsWithCursor(ctx, network, params)
queryDuration := time.Since(queryStart)
log.Printf("[%s/gateway] Operations query took: %v", network, queryDuration)
if err != nil {
log.Printf("Error fetching operations from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching operations: %v", err), http.StatusInternalServerError)
return
}
// Return paginated response with cursor info
response := map[string]interface{}{
"operations": result.Data,
"count": result.Count,
"has_more": result.HasMore,
}
if result.Cursor != "" {
response["cursor"] = result.Cursor
}
json.NewEncoder(w).Encode(response)
}
// handleAPIEffectsViaGateway fetches effects from the gateway silver layer with cursor pagination
func (app *App) handleAPIEffectsViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
params := make(map[string]string)
// Pagination params
if limit := r.URL.Query().Get("limit"); limit != "" {
params["limit"] = limit
} else {
params["limit"] = "100"
}
if cursor := r.URL.Query().Get("cursor"); cursor != "" {
params["cursor"] = cursor
}
// Optional filter params
if accountID := r.URL.Query().Get("account_id"); accountID != "" {
params["account_id"] = accountID
}
if effectType := r.URL.Query().Get("effect_type"); effectType != "" {
params["effect_type"] = effectType
}
queryStart := time.Now()
result, err := app.gateway.GetEffectsWithCursor(ctx, network, params)
queryDuration := time.Since(queryStart)
log.Printf("[%s/gateway] Effects query took: %v", network, queryDuration)
if err != nil {
log.Printf("Error fetching effects from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching effects: %v", err), http.StatusInternalServerError)
return
}
// Return paginated response with cursor info
response := map[string]interface{}{
"effects": result.Data,
"count": result.Count,
"has_more": result.HasMore,
}
if result.Cursor != "" {
response["cursor"] = result.Cursor
}
json.NewEncoder(w).Encode(response)
}
// handleAPITradesViaGateway fetches trades from the gateway silver layer with cursor pagination
func (app *App) handleAPITradesViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
params := make(map[string]string)
// Pagination params
if limit := r.URL.Query().Get("limit"); limit != "" {
params["limit"] = limit
} else {
params["limit"] = "100"
}
if cursor := r.URL.Query().Get("cursor"); cursor != "" {
params["cursor"] = cursor
}
// Optional filter params
if sellerAccount := r.URL.Query().Get("seller_account"); sellerAccount != "" {
params["seller_account"] = sellerAccount
}
if buyerAccount := r.URL.Query().Get("buyer_account"); buyerAccount != "" {
params["buyer_account"] = buyerAccount
}
if sellingAsset := r.URL.Query().Get("selling_asset"); sellingAsset != "" {
params["selling_asset"] = sellingAsset
}
if buyingAsset := r.URL.Query().Get("buying_asset"); buyingAsset != "" {
params["buying_asset"] = buyingAsset
}
if tradeType := r.URL.Query().Get("trade_type"); tradeType != "" {
params["trade_type"] = tradeType
}
queryStart := time.Now()
result, err := app.gateway.GetTradesWithCursor(ctx, network, params)
queryDuration := time.Since(queryStart)
log.Printf("[%s/gateway] Trades query took: %v", network, queryDuration)
if err != nil {
log.Printf("Error fetching trades from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching trades: %v", err), http.StatusInternalServerError)
return
}
// Return paginated response with cursor info
response := map[string]interface{}{
"trades": result.Data,
"count": result.Count,
"has_more": result.HasMore,
}
if result.Cursor != "" {
response["cursor"] = result.Cursor
}
json.NewEncoder(w).Encode(response)
}
// handleAPIOffersViaGateway fetches offers from the gateway
func (app *App) handleAPIOffersViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
params := make(map[string]string)
// Pagination params
if limit := r.URL.Query().Get("limit"); limit != "" {
params["limit"] = limit
} else {
params["limit"] = "50"
}
if cursor := r.URL.Query().Get("cursor"); cursor != "" {
params["cursor"] = cursor
}
// Optional filter params - seller_id is now OPTIONAL in silver layer
if sellerID := r.URL.Query().Get("seller_id"); sellerID != "" {
params["seller_id"] = sellerID
}
if sellerID := r.URL.Query().Get("seller"); sellerID != "" {
params["seller_id"] = sellerID // backward compatibility
}
queryStart := time.Now()
result, err := app.gateway.GetOffersWithCursor(ctx, network, params)
queryDuration := time.Since(queryStart)
log.Printf("[%s/gateway] Offers query took: %v", network, queryDuration)
if err != nil {
log.Printf("Error fetching offers from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching offers: %v", err), http.StatusInternalServerError)
return
}
// Return paginated response with cursor info
response := map[string]interface{}{
"offers": result.Data,
"count": result.Count,
"has_more": result.HasMore,
}
if result.Cursor != "" {
response["cursor"] = result.Cursor
}
json.NewEncoder(w).Encode(response)
}
// handleAccountsAPIViaGateway fetches accounts from the gateway with cursor pagination
func (app *App) handleAccountsAPIViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
params := make(map[string]string)
// Pagination params
if limit := r.URL.Query().Get("limit"); limit != "" {
params["limit"] = limit
} else {
params["limit"] = "50"
}
if cursor := r.URL.Query().Get("cursor"); cursor != "" {
params["cursor"] = cursor
}
// Filter params
if minBalance := r.URL.Query().Get("min_balance"); minBalance != "" {
params["min_balance"] = minBalance
}
if sortBy := r.URL.Query().Get("sort_by"); sortBy != "" {
params["sort_by"] = sortBy
}
if order := r.URL.Query().Get("order"); order != "" {
params["order"] = order
}
queryStart := time.Now()
result, err := app.gateway.GetAccountsWithCursor(ctx, network, params)
queryDuration := time.Since(queryStart)
log.Printf("[%s/gateway] Accounts query took: %v", network, queryDuration)
if err != nil {
log.Printf("Error fetching accounts from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching accounts: %v", err), http.StatusInternalServerError)
return
}
// Return paginated response with cursor info
response := map[string]interface{}{
"accounts": result.Data,
"count": result.Count,
"has_more": result.HasMore,
}
if result.Cursor != "" {
response["cursor"] = result.Cursor
}
json.NewEncoder(w).Encode(response)
}
// handleAccountAPIViaGateway fetches a single account from the gateway
func (app *App) handleAccountAPIViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
accountID := chi.URLParam(r, "id")
if accountID == "" {
http.Error(w, "Missing account ID", http.StatusBadRequest)
return
}
account, err := app.gateway.GetAccountOverview(ctx, network, accountID)
if err != nil {
log.Printf("Error fetching account from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching account: %v", err), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(account)
}
// handleAPILiquidityPoolsViaGateway fetches liquidity pools from the gateway silver layer
func (app *App) handleAPILiquidityPoolsViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
params := make(map[string]string)
// Pagination params
if limit := r.URL.Query().Get("limit"); limit != "" {
params["limit"] = limit
} else {
params["limit"] = "50"
}
if cursor := r.URL.Query().Get("cursor"); cursor != "" {
params["cursor"] = cursor
}
// Filter params
if assetA := r.URL.Query().Get("asset_a"); assetA != "" {
params["asset_a"] = assetA
}
if assetB := r.URL.Query().Get("asset_b"); assetB != "" {
params["asset_b"] = assetB
}
queryStart := time.Now()
result, err := app.gateway.GetLiquidityPoolsWithCursor(ctx, network, params)
queryDuration := time.Since(queryStart)
log.Printf("[%s/gateway] Liquidity pools query took: %v", network, queryDuration)
if err != nil {
log.Printf("Error fetching liquidity pools from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching liquidity pools: %v", err), http.StatusInternalServerError)
return
}
// Return paginated response with cursor info
response := map[string]interface{}{
"liquidity_pools": result.Data,
"count": result.Count,
"has_more": result.HasMore,
}
if result.Cursor != "" {
response["cursor"] = result.Cursor
}
json.NewEncoder(w).Encode(response)
}
// handleAPINetworkStatsViaGateway fetches network statistics from the gateway silver layer
func (app *App) handleAPINetworkStatsViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
queryStart := time.Now()
result, err := app.gateway.GetNetworkStats(ctx, network)
queryDuration := time.Since(queryStart)
log.Printf("[%s/gateway] Network stats query took: %v", network, queryDuration)
if err != nil {
log.Printf("Error fetching network stats from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching network stats: %v", err), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(result)
}
// handleAPIContractsViaGateway fetches top contracts from the gateway silver layer
func (app *App) handleAPIContractsViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
params := make(map[string]string)
// Pagination params
if limit := r.URL.Query().Get("limit"); limit != "" {
params["limit"] = limit
} else {
params["limit"] = "50"
}
if cursor := r.URL.Query().Get("cursor"); cursor != "" {
params["cursor"] = cursor
}
// Filter params
if period := r.URL.Query().Get("period"); period != "" {
params["period"] = period
}
queryStart := time.Now()
result, err := app.gateway.GetTopContracts(ctx, network, params)
queryDuration := time.Since(queryStart)
log.Printf("[%s/gateway] Top contracts query took: %v", network, queryDuration)
if err != nil {
log.Printf("Error fetching contracts from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching contracts: %v", err), http.StatusInternalServerError)
return
}
// Return paginated response with cursor info
response := map[string]interface{}{
"contracts": result.Data,
"count": result.Count,
"has_more": result.HasMore,
}
if result.Cursor != "" {
response["cursor"] = result.Cursor
}
json.NewEncoder(w).Encode(response)
}
// handleAPIContractViaGateway fetches a contract from the gateway
func (app *App) handleAPIContractViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
contractID := chi.URLParam(r, "id")
if contractID == "" {
http.Error(w, "Missing contract ID", http.StatusBadRequest)
return
}
contract, err := app.gateway.GetContractSummary(ctx, network, contractID)
if err != nil {
log.Printf("Error fetching contract from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching contract: %v", err), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(contract)
}
// handleAPIContractEventsViaGateway fetches contract events from the gateway
func (app *App) handleAPIContractEventsViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
contractID := chi.URLParam(r, "id")
if contractID == "" {
http.Error(w, "Missing contract ID", http.StatusBadRequest)
return
}
startLedgerStr := r.URL.Query().Get("start_ledger")
endLedgerStr := r.URL.Query().Get("end_ledger")
var startLedger, endLedger int64
if startLedgerStr != "" {
startLedger, _ = strconv.ParseInt(startLedgerStr, 10, 64)
}
if endLedgerStr != "" {
endLedger, _ = strconv.ParseInt(endLedgerStr, 10, 64)
}
events, err := app.gateway.GetContractEvents(ctx, network, contractID, startLedger, endLedger)
if err != nil {
log.Printf("Error fetching contract events from gateway: %v", err)
http.Error(w, fmt.Sprintf("Error fetching contract events: %v", err), http.StatusInternalServerError)
return
}
json.NewEncoder(w).Encode(events)
}
// handleAPIMetricsSummaryViaGateway computes metrics summary from gateway ledger data
func (app *App) handleAPIMetricsSummaryViaGateway(w http.ResponseWriter, r *http.Request, network string) {
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
// Fetch recent ledgers from gateway (last 100)
ledgers, err := app.gateway.GetLedgers(ctx, network, 1, 999999999, 100, "")
if err != nil {
log.Printf("Error fetching ledgers from gateway for metrics: %v", err)
http.Error(w, fmt.Sprintf("Error fetching metrics: %v", err), http.StatusInternalServerError)
return
}
if len(ledgers) == 0 {
json.NewEncoder(w).Encode(map[string]interface{}{
"error": "No ledger data available",
})
return
}
// Compute metrics from ledgers
var totalTx, successfulTx, failedTx int64
var latestLedger, earliestLedger int64
var latestTime, earliestTime string
for _, ledger := range ledgers {
successCount := getInt64(ledger, "successful_tx_count")
failedCount := getInt64(ledger, "failed_tx_count")
seq := getInt64(ledger, "sequence")
closedAt := getString(ledger, "closed_at")
totalTx += successCount + failedCount
successfulTx += successCount
failedTx += failedCount
if earliestLedger == 0 || seq < earliestLedger {
earliestLedger = seq
earliestTime = closedAt
}
if seq > latestLedger {
latestLedger = seq
latestTime = closedAt
}
}
successRate := float64(0)
if totalTx > 0 {
successRate = float64(successfulTx) / float64(totalTx) * 100
}
avgTxPerLedger := float64(totalTx) / float64(len(ledgers))
summary := map[string]interface{}{
"total_ledgers": len(ledgers),
"total_transactions": totalTx,
"successful_transactions": successfulTx,
"failed_transactions": failedTx,
"success_rate": successRate,
"avg_tps": avgTxPerLedger,
"latest_ledger": latestLedger,
"earliest_time": earliestTime,
"latest_time": latestTime,
}
json.NewEncoder(w).Encode(summary)
}