-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathinternal.go
1549 lines (1417 loc) · 80.5 KB
/
internal.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
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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package data
import (
"context"
"database/sql"
"fmt"
"sync"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"golang.org/x/text/language"
"github.com/code-payments/code-server/pkg/cache"
currency_lib "github.com/code-payments/code-server/pkg/currency"
pg "github.com/code-payments/code-server/pkg/database/postgres"
"github.com/code-payments/code-server/pkg/database/query"
timelock_token "github.com/code-payments/code-server/pkg/solana/timelock/v1"
commonpb "github.com/code-payments/code-protobuf-api/generated/go/common/v1"
"github.com/code-payments/code-server/pkg/code/data/account"
"github.com/code-payments/code-server/pkg/code/data/action"
"github.com/code-payments/code-server/pkg/code/data/airdrop"
"github.com/code-payments/code-server/pkg/code/data/badgecount"
"github.com/code-payments/code-server/pkg/code/data/balance"
"github.com/code-payments/code-server/pkg/code/data/chat"
"github.com/code-payments/code-server/pkg/code/data/commitment"
"github.com/code-payments/code-server/pkg/code/data/contact"
"github.com/code-payments/code-server/pkg/code/data/currency"
"github.com/code-payments/code-server/pkg/code/data/deposit"
"github.com/code-payments/code-server/pkg/code/data/event"
"github.com/code-payments/code-server/pkg/code/data/fulfillment"
"github.com/code-payments/code-server/pkg/code/data/intent"
"github.com/code-payments/code-server/pkg/code/data/login"
"github.com/code-payments/code-server/pkg/code/data/merkletree"
"github.com/code-payments/code-server/pkg/code/data/nonce"
"github.com/code-payments/code-server/pkg/code/data/onramp"
"github.com/code-payments/code-server/pkg/code/data/payment"
"github.com/code-payments/code-server/pkg/code/data/paymentrequest"
"github.com/code-payments/code-server/pkg/code/data/paywall"
"github.com/code-payments/code-server/pkg/code/data/phone"
"github.com/code-payments/code-server/pkg/code/data/preferences"
"github.com/code-payments/code-server/pkg/code/data/push"
"github.com/code-payments/code-server/pkg/code/data/rendezvous"
"github.com/code-payments/code-server/pkg/code/data/timelock"
"github.com/code-payments/code-server/pkg/code/data/transaction"
"github.com/code-payments/code-server/pkg/code/data/treasury"
"github.com/code-payments/code-server/pkg/code/data/twitter"
"github.com/code-payments/code-server/pkg/code/data/user"
"github.com/code-payments/code-server/pkg/code/data/user/identity"
"github.com/code-payments/code-server/pkg/code/data/user/storage"
"github.com/code-payments/code-server/pkg/code/data/vault"
"github.com/code-payments/code-server/pkg/code/data/webhook"
account_memory_client "github.com/code-payments/code-server/pkg/code/data/account/memory"
action_memory_client "github.com/code-payments/code-server/pkg/code/data/action/memory"
airdrop_memory_client "github.com/code-payments/code-server/pkg/code/data/airdrop/memory"
badgecount_memory_client "github.com/code-payments/code-server/pkg/code/data/badgecount/memory"
balance_memory_client "github.com/code-payments/code-server/pkg/code/data/balance/memory"
chat_memory_client "github.com/code-payments/code-server/pkg/code/data/chat/memory"
commitment_memory_client "github.com/code-payments/code-server/pkg/code/data/commitment/memory"
contact_memory_client "github.com/code-payments/code-server/pkg/code/data/contact/memory"
currency_memory_client "github.com/code-payments/code-server/pkg/code/data/currency/memory"
deposit_memory_client "github.com/code-payments/code-server/pkg/code/data/deposit/memory"
event_memory_client "github.com/code-payments/code-server/pkg/code/data/event/memory"
fulfillment_memory_client "github.com/code-payments/code-server/pkg/code/data/fulfillment/memory"
intent_memory_client "github.com/code-payments/code-server/pkg/code/data/intent/memory"
login_memory_client "github.com/code-payments/code-server/pkg/code/data/login/memory"
merkletree_memory_client "github.com/code-payments/code-server/pkg/code/data/merkletree/memory"
messaging "github.com/code-payments/code-server/pkg/code/data/messaging"
messaging_memory_client "github.com/code-payments/code-server/pkg/code/data/messaging/memory"
nonce_memory_client "github.com/code-payments/code-server/pkg/code/data/nonce/memory"
onramp_memory_client "github.com/code-payments/code-server/pkg/code/data/onramp/memory"
payment_memory_client "github.com/code-payments/code-server/pkg/code/data/payment/memory"
paymentrequest_memory_client "github.com/code-payments/code-server/pkg/code/data/paymentrequest/memory"
paywall_memory_client "github.com/code-payments/code-server/pkg/code/data/paywall/memory"
phone_memory_client "github.com/code-payments/code-server/pkg/code/data/phone/memory"
preferences_memory_client "github.com/code-payments/code-server/pkg/code/data/preferences/memory"
push_memory_client "github.com/code-payments/code-server/pkg/code/data/push/memory"
rendezvous_memory_client "github.com/code-payments/code-server/pkg/code/data/rendezvous/memory"
timelock_memory_client "github.com/code-payments/code-server/pkg/code/data/timelock/memory"
transaction_memory_client "github.com/code-payments/code-server/pkg/code/data/transaction/memory"
treasury_memory_client "github.com/code-payments/code-server/pkg/code/data/treasury/memory"
twitter_memory_client "github.com/code-payments/code-server/pkg/code/data/twitter/memory"
user_identity_memory_client "github.com/code-payments/code-server/pkg/code/data/user/identity/memory"
user_storage_memory_client "github.com/code-payments/code-server/pkg/code/data/user/storage/memory"
vault_memory_client "github.com/code-payments/code-server/pkg/code/data/vault/memory"
webhook_memory_client "github.com/code-payments/code-server/pkg/code/data/webhook/memory"
account_postgres_client "github.com/code-payments/code-server/pkg/code/data/account/postgres"
action_postgres_client "github.com/code-payments/code-server/pkg/code/data/action/postgres"
airdrop_postgres_client "github.com/code-payments/code-server/pkg/code/data/airdrop/postgres"
badgecount_postgres_client "github.com/code-payments/code-server/pkg/code/data/badgecount/postgres"
balance_postgres_client "github.com/code-payments/code-server/pkg/code/data/balance/postgres"
chat_postgres_client "github.com/code-payments/code-server/pkg/code/data/chat/postgres"
commitment_postgres_client "github.com/code-payments/code-server/pkg/code/data/commitment/postgres"
contact_postgres_client "github.com/code-payments/code-server/pkg/code/data/contact/postgres"
currency_postgres_client "github.com/code-payments/code-server/pkg/code/data/currency/postgres"
deposit_postgres_client "github.com/code-payments/code-server/pkg/code/data/deposit/postgres"
event_postgres_client "github.com/code-payments/code-server/pkg/code/data/event/postgres"
fulfillment_postgres_client "github.com/code-payments/code-server/pkg/code/data/fulfillment/postgres"
intent_postgres_client "github.com/code-payments/code-server/pkg/code/data/intent/postgres"
login_postgres_client "github.com/code-payments/code-server/pkg/code/data/login/postgres"
merkletree_postgres_client "github.com/code-payments/code-server/pkg/code/data/merkletree/postgres"
messaging_postgres_client "github.com/code-payments/code-server/pkg/code/data/messaging/postgres"
nonce_postgres_client "github.com/code-payments/code-server/pkg/code/data/nonce/postgres"
onramp_postgres_client "github.com/code-payments/code-server/pkg/code/data/onramp/postgres"
payment_postgres_client "github.com/code-payments/code-server/pkg/code/data/payment/postgres"
paymentrequest_postgres_client "github.com/code-payments/code-server/pkg/code/data/paymentrequest/postgres"
paywall_postgres_client "github.com/code-payments/code-server/pkg/code/data/paywall/postgres"
phone_postgres_client "github.com/code-payments/code-server/pkg/code/data/phone/postgres"
preferences_postgres_client "github.com/code-payments/code-server/pkg/code/data/preferences/postgres"
push_postgres_client "github.com/code-payments/code-server/pkg/code/data/push/postgres"
rendezvous_postgres_client "github.com/code-payments/code-server/pkg/code/data/rendezvous/postgres"
timelock_postgres_client "github.com/code-payments/code-server/pkg/code/data/timelock/postgres"
transaction_postgres_client "github.com/code-payments/code-server/pkg/code/data/transaction/postgres"
treasury_postgres_client "github.com/code-payments/code-server/pkg/code/data/treasury/postgres"
twitter_postgres_client "github.com/code-payments/code-server/pkg/code/data/twitter/postgres"
user_identity_postgres_client "github.com/code-payments/code-server/pkg/code/data/user/identity/postgres"
user_storage_postgres_client "github.com/code-payments/code-server/pkg/code/data/user/storage/postgres"
vault_postgres_client "github.com/code-payments/code-server/pkg/code/data/vault/postgres"
webhook_postgres_client "github.com/code-payments/code-server/pkg/code/data/webhook/postgres"
)
// Cache Constants
const (
maxExchangeRateCacheBudget = 1000000 // 1 million
singleExchangeRateCacheWeight = 1
multiExchangeRateCacheWeight = 60 // usually we get 60 exchange rates from CoinGecko for a single time interval
maxTimelockCacheBudget = 100000
timelockCacheTTL = 5 * time.Second // Keep this relatively small
)
type timelockCacheEntry struct {
mu sync.RWMutex
record *timelock.Record
lastUpdatedAt time.Time
}
type DatabaseData interface {
// Account Info
// --------------------------------------------------------------------------------
CreateAccountInfo(ctx context.Context, record *account.Record) error
UpdateAccountInfo(ctx context.Context, record *account.Record) error
GetAccountInfoByTokenAddress(ctx context.Context, address string) (*account.Record, error)
GetAccountInfoByAuthorityAddress(ctx context.Context, address string) (*account.Record, error)
GetLatestAccountInfosByOwnerAddress(ctx context.Context, address string) (map[commonpb.AccountType][]*account.Record, error)
GetLatestAccountInfoByOwnerAddressAndType(ctx context.Context, address string, accountType commonpb.AccountType) (*account.Record, error)
GetRelationshipAccountInfoByOwnerAddress(ctx context.Context, address, relationshipTo string) (*account.Record, error)
GetPrioritizedAccountInfosRequiringDepositSync(ctx context.Context, limit uint64) ([]*account.Record, error)
GetPrioritizedAccountInfosRequiringAutoReturnCheck(ctx context.Context, maxAge time.Duration, limit uint64) ([]*account.Record, error)
GetPrioritizedAccountInfosRequiringSwapRetry(ctx context.Context, maxAge time.Duration, limit uint64) ([]*account.Record, error)
GetAccountInfoCountRequiringDepositSync(ctx context.Context) (uint64, error)
GetAccountInfoCountRequiringAutoReturnCheck(ctx context.Context) (uint64, error)
GetAccountInfoCountRequiringSwapRetry(ctx context.Context) (uint64, error)
// Currency
// --------------------------------------------------------------------------------
GetExchangeRate(ctx context.Context, code currency_lib.Code, t time.Time) (*currency.ExchangeRateRecord, error)
GetAllExchangeRates(ctx context.Context, t time.Time) (*currency.MultiRateRecord, error)
GetExchangeRateHistory(ctx context.Context, code currency_lib.Code, opts ...query.Option) ([]*currency.ExchangeRateRecord, error)
ImportExchangeRates(ctx context.Context, data *currency.MultiRateRecord) error
// Vault
// --------------------------------------------------------------------------------
GetKey(ctx context.Context, public_key string) (*vault.Record, error)
GetKeyCount(ctx context.Context) (uint64, error)
GetKeyCountByState(ctx context.Context, state vault.State) (uint64, error)
GetAllKeysByState(ctx context.Context, state vault.State, opts ...query.Option) ([]*vault.Record, error)
SaveKey(ctx context.Context, record *vault.Record) error
// Nonce
// --------------------------------------------------------------------------------
GetNonce(ctx context.Context, address string) (*nonce.Record, error)
GetNonceCount(ctx context.Context) (uint64, error)
GetNonceCountByState(ctx context.Context, state nonce.State) (uint64, error)
GetNonceCountByStateAndPurpose(ctx context.Context, state nonce.State, purpose nonce.Purpose) (uint64, error)
GetAllNonceByState(ctx context.Context, state nonce.State, opts ...query.Option) ([]*nonce.Record, error)
GetRandomAvailableNonceByPurpose(ctx context.Context, purpose nonce.Purpose) (*nonce.Record, error)
SaveNonce(ctx context.Context, record *nonce.Record) error
// Fulfillment
// --------------------------------------------------------------------------------
GetFulfillmentById(ctx context.Context, id uint64) (*fulfillment.Record, error)
GetFulfillmentBySignature(ctx context.Context, signature string) (*fulfillment.Record, error)
GetFulfillmentCount(ctx context.Context) (uint64, error)
GetFulfillmentCountByState(ctx context.Context, state fulfillment.State) (uint64, error)
GetFulfillmentCountByStateGroupedByType(ctx context.Context, state fulfillment.State) (map[fulfillment.Type]uint64, error)
GetFulfillmentCountForMetrics(ctx context.Context, state fulfillment.State) (map[fulfillment.Type]uint64, error)
GetFulfillmentCountByStateAndAddress(ctx context.Context, state fulfillment.State, address string) (uint64, error)
GetFulfillmentCountByTypeStateAndAddress(ctx context.Context, fulfillmentType fulfillment.Type, state fulfillment.State, address string) (uint64, error)
GetFulfillmentCountByTypeStateAndAddressAsSource(ctx context.Context, fulfillmentType fulfillment.Type, state fulfillment.State, address string) (uint64, error)
GetFulfillmentCountByIntentAndState(ctx context.Context, intent string, state fulfillment.State) (uint64, error)
GetFulfillmentCountByIntent(ctx context.Context, intent string) (uint64, error)
GetFulfillmentCountByTypeActionAndState(ctx context.Context, intentId string, actionId uint32, fulfillmentType fulfillment.Type, state fulfillment.State) (uint64, error)
GetPendingFulfillmentCountByType(ctx context.Context) (map[fulfillment.Type]uint64, error)
GetAllFulfillmentsByState(ctx context.Context, state fulfillment.State, includeDisabledActiveScheduling bool, opts ...query.Option) ([]*fulfillment.Record, error)
GetAllFulfillmentsByIntent(ctx context.Context, intent string, opts ...query.Option) ([]*fulfillment.Record, error)
GetAllFulfillmentsByAction(ctx context.Context, intentId string, actionId uint32) ([]*fulfillment.Record, error)
GetAllFulfillmentsByTypeAndAction(ctx context.Context, fulfillmentType fulfillment.Type, intentId string, actionId uint32) ([]*fulfillment.Record, error)
GetFirstSchedulableFulfillmentByAddressAsSource(ctx context.Context, address string) (*fulfillment.Record, error)
GetFirstSchedulableFulfillmentByAddressAsDestination(ctx context.Context, address string) (*fulfillment.Record, error)
GetFirstSchedulableFulfillmentByType(ctx context.Context, fulfillmentType fulfillment.Type) (*fulfillment.Record, error)
GetNextSchedulableFulfillmentByAddress(ctx context.Context, address string, intentOrderingIndex uint64, actionOrderingIndex, fulfillmentOrderingIndex uint32) (*fulfillment.Record, error)
PutAllFulfillments(ctx context.Context, records ...*fulfillment.Record) error
UpdateFulfillment(ctx context.Context, record *fulfillment.Record) error
MarkFulfillmentAsActivelyScheduled(ctx context.Context, id uint64) error
ActivelyScheduleTreasuryAdvanceFulfillments(ctx context.Context, treasury string, intentOrderingIndex uint64, limit int) (uint64, error)
// Intent
// --------------------------------------------------------------------------------
SaveIntent(ctx context.Context, record *intent.Record) error
GetIntent(ctx context.Context, intentID string) (*intent.Record, error)
GetIntentBySignature(ctx context.Context, signature string) (*intent.Record, error)
GetLatestIntentByInitiatorAndType(ctx context.Context, intentType intent.Type, owner string) (*intent.Record, error)
GetAllIntentsByOwner(ctx context.Context, owner string, opts ...query.Option) ([]*intent.Record, error)
GetIntentCountForAntispam(ctx context.Context, intentType intent.Type, phoneNumber string, states []intent.State, since time.Time) (uint64, error)
GetIntentCountWithOwnerInteractionsForAntispam(ctx context.Context, sourceOwner, destinationOwner string, states []intent.State, since time.Time) (uint64, error)
GetTransactedAmountForAntiMoneyLaundering(ctx context.Context, phoneNumber string, since time.Time) (uint64, float64, error)
GetDepositedAmountForAntiMoneyLaundering(ctx context.Context, phoneNumber string, since time.Time) (uint64, float64, error)
GetNetBalanceFromPrePrivacy2022Intents(ctx context.Context, account string) (int64, error)
GetLatestSaveRecentRootIntentForTreasury(ctx context.Context, treasury string) (*intent.Record, error)
GetOriginalGiftCardIssuedIntent(ctx context.Context, giftCardVault string) (*intent.Record, error)
GetGiftCardClaimedIntent(ctx context.Context, giftCardVault string) (*intent.Record, error)
// Action
// --------------------------------------------------------------------------------
PutAllActions(ctx context.Context, records ...*action.Record) error
UpdateAction(ctx context.Context, record *action.Record) error
GetActionById(ctx context.Context, intent string, actionId uint32) (*action.Record, error)
GetAllActionsByIntent(ctx context.Context, intent string) ([]*action.Record, error)
GetAllActionsByAddress(ctx context.Context, address string) ([]*action.Record, error)
GetNetBalanceFromActions(ctx context.Context, address string) (int64, error)
GetNetBalanceFromActionsBatch(ctx context.Context, accounts ...string) (map[string]int64, error)
GetGiftCardClaimedAction(ctx context.Context, giftCardVault string) (*action.Record, error)
GetGiftCardAutoReturnAction(ctx context.Context, giftCardVault string) (*action.Record, error)
// Payment (mostly deprecated for legacy accounts and unmigrated processes)
// --------------------------------------------------------------------------------
GetPayment(ctx context.Context, sig string, index int) (*payment.Record, error)
CreatePayment(ctx context.Context, record *payment.Record) error
UpdateOrCreatePayment(ctx context.Context, record *payment.Record) error
GetPaymentHistory(ctx context.Context, account string, opts ...query.Option) ([]*payment.Record, error)
GetPaymentHistoryWithinBlockRange(ctx context.Context, account string, lowerBound, upperBound uint64, opts ...query.Option) ([]*payment.Record, error)
GetLegacyTotalExternalDepositAmountFromPrePrivacy2022Accounts(ctx context.Context, account string) (uint64, error)
// Transaction
// --------------------------------------------------------------------------------
GetTransaction(ctx context.Context, sig string) (*transaction.Record, error)
SaveTransaction(ctx context.Context, record *transaction.Record) error
// Messaging
// --------------------------------------------------------------------------------
CreateMessage(ctx context.Context, record *messaging.Record) error
GetMessages(ctx context.Context, account string) ([]*messaging.Record, error)
DeleteMessage(ctx context.Context, account string, messageID uuid.UUID) error
// Phone
// --------------------------------------------------------------------------------
SavePhoneVerification(ctx context.Context, v *phone.Verification) error
GetPhoneVerification(ctx context.Context, account, phoneNumber string) (*phone.Verification, error)
GetLatestPhoneVerificationForAccount(ctx context.Context, account string) (*phone.Verification, error)
GetLatestPhoneVerificationForNumber(ctx context.Context, phoneNumber string) (*phone.Verification, error)
GetAllPhoneVerificationsForNumber(ctx context.Context, phoneNumber string) ([]*phone.Verification, error)
SavePhoneLinkingToken(ctx context.Context, token *phone.LinkingToken) error
UsePhoneLinkingToken(ctx context.Context, phoneNumber, code string) error
FilterVerifiedPhoneNumbers(ctx context.Context, phoneNumbers []string) ([]string, error)
SaveOwnerAccountPhoneSetting(ctx context.Context, phoneNumber string, newSettings *phone.OwnerAccountSetting) error
IsPhoneNumberLinkedToAccount(ctx context.Context, phoneNumber string, tokenAccount string) (bool, error)
IsPhoneNumberEnabledForRemoteSendToAccount(ctx context.Context, phoneNumber string, tokenAccount string) (bool, error)
PutPhoneEvent(ctx context.Context, event *phone.Event) error
GetLatestPhoneEventForNumberByType(ctx context.Context, phoneNumber string, eventType phone.EventType) (*phone.Event, error)
GetPhoneEventCountForVerificationByType(ctx context.Context, verification string, eventType phone.EventType) (uint64, error)
GetPhoneEventCountForNumberByTypeSinceTimestamp(ctx context.Context, phoneNumber string, eventType phone.EventType, since time.Time) (uint64, error)
GetUniquePhoneVerificationIdCountForNumberSinceTimestamp(ctx context.Context, phoneNumber string, since time.Time) (uint64, error)
// Contact
// --------------------------------------------------------------------------------
AddContact(ctx context.Context, owner *user.DataContainerID, contact string) error
BatchAddContacts(ctx context.Context, owner *user.DataContainerID, contacts []string) error
RemoveContact(ctx context.Context, owner *user.DataContainerID, contact string) error
BatchRemoveContacts(ctx context.Context, owner *user.DataContainerID, contacts []string) error
GetContacts(ctx context.Context, owner *user.DataContainerID, limit uint32, pageToken []byte) (contacts []string, nextPageToken []byte, err error)
// User Identity
// --------------------------------------------------------------------------------
PutUser(ctx context.Context, record *identity.Record) error
GetUserByID(ctx context.Context, id *user.UserID) (*identity.Record, error)
GetUserByPhoneView(ctx context.Context, phoneNumber string) (*identity.Record, error)
// User Storage Management
// --------------------------------------------------------------------------------
PutUserDataContainer(ctx context.Context, container *storage.Record) error
GetUserDataContainerByID(ctx context.Context, id *user.DataContainerID) (*storage.Record, error)
GetUserDataContainerByPhone(ctx context.Context, tokenAccount, phoneNumber string) (*storage.Record, error)
// Timelock
// --------------------------------------------------------------------------------
SaveTimelock(ctx context.Context, record *timelock.Record) error
GetTimelockByAddress(ctx context.Context, address string) (*timelock.Record, error)
GetTimelockByVault(ctx context.Context, vault string) (*timelock.Record, error)
GetTimelockByVaultBatch(ctx context.Context, vaults ...string) (map[string]*timelock.Record, error)
GetAllTimelocksByState(ctx context.Context, state timelock_token.TimelockState, opts ...query.Option) ([]*timelock.Record, error)
GetTimelockCountByState(ctx context.Context, state timelock_token.TimelockState) (uint64, error)
// Push
// --------------------------------------------------------------------------------
PutPushToken(ctx context.Context, record *push.Record) error
MarkPushTokenAsInvalid(ctx context.Context, pushToken string) error
DeletePushToken(ctx context.Context, pushToken string) error
GetAllValidPushTokensdByDataContainer(ctx context.Context, id *user.DataContainerID) ([]*push.Record, error)
// Commitment
// --------------------------------------------------------------------------------
SaveCommitment(ctx context.Context, record *commitment.Record) error
GetCommitmentByAddress(ctx context.Context, address string) (*commitment.Record, error)
GetCommitmentByVault(ctx context.Context, vault string) (*commitment.Record, error)
GetCommitmentByAction(ctx context.Context, intentId string, actionId uint32) (*commitment.Record, error)
GetAllCommitmentsByState(ctx context.Context, state commitment.State, opts ...query.Option) ([]*commitment.Record, error)
GetUpgradeableCommitmentsByOwner(ctx context.Context, owner string, limit uint64) ([]*commitment.Record, error)
GetUsedTreasuryPoolDeficitFromCommitments(ctx context.Context, treasuryPool string) (uint64, error)
GetTotalTreasuryPoolDeficitFromCommitments(ctx context.Context, treasuryPool string) (uint64, error)
CountCommitmentsByState(ctx context.Context, state commitment.State) (uint64, error)
CountCommitmentRepaymentsDivertedToVault(ctx context.Context, vault string) (uint64, error)
// Treasury Pool
// --------------------------------------------------------------------------------
SaveTreasuryPool(ctx context.Context, record *treasury.Record) error
GetTreasuryPoolByName(ctx context.Context, name string) (*treasury.Record, error)
GetTreasuryPoolByAddress(ctx context.Context, address string) (*treasury.Record, error)
GetTreasuryPoolByVault(ctx context.Context, vault string) (*treasury.Record, error)
GetAllTreasuryPoolsByState(ctx context.Context, state treasury.TreasuryPoolState, opts ...query.Option) ([]*treasury.Record, error)
SaveTreasuryPoolFunding(ctx context.Context, record *treasury.FundingHistoryRecord) error
GetTotalAvailableTreasuryPoolFunds(ctx context.Context, vault string) (uint64, error)
// Merkle Tree
// --------------------------------------------------------------------------------
InitializeNewMerkleTree(ctx context.Context, name string, levels uint8, seeds []merkletree.Seed, readOnly bool) (*merkletree.MerkleTree, error)
LoadExistingMerkleTree(ctx context.Context, name string, readOnly bool) (*merkletree.MerkleTree, error)
// External Deposits
// --------------------------------------------------------------------------------
SaveExternalDeposit(ctx context.Context, record *deposit.Record) error
GetExternalDeposit(ctx context.Context, signature, destination string) (*deposit.Record, error)
GetTotalExternalDepositedAmountInQuarks(ctx context.Context, account string) (uint64, error)
GetTotalExternalDepositedAmountInQuarksBatch(ctx context.Context, accounts ...string) (map[string]uint64, error)
GetTotalExternalDepositedAmountInUsd(ctx context.Context, account string) (float64, error)
// Rendezvous
// --------------------------------------------------------------------------------
SaveRendezvous(ctx context.Context, record *rendezvous.Record) error
GetRendezvous(ctx context.Context, key string) (*rendezvous.Record, error)
DeleteRendezvous(ctx context.Context, key string) error
// Requests
// --------------------------------------------------------------------------------
CreateRequest(ctx context.Context, record *paymentrequest.Record) error
GetRequest(ctx context.Context, intentId string) (*paymentrequest.Record, error)
// Paywall
// --------------------------------------------------------------------------------
CreatePaywall(ctx context.Context, record *paywall.Record) error
GetPaywallByShortPath(ctx context.Context, path string) (*paywall.Record, error)
// Event
// --------------------------------------------------------------------------------
SaveEvent(ctx context.Context, record *event.Record) error
GetEvent(ctx context.Context, id string) (*event.Record, error)
// Webhook
// --------------------------------------------------------------------------------
CreateWebhook(ctx context.Context, record *webhook.Record) error
UpdateWebhook(ctx context.Context, record *webhook.Record) error
GetWebhook(ctx context.Context, webhookId string) (*webhook.Record, error)
CountWebhookByState(ctx context.Context, state webhook.State) (uint64, error)
GetAllPendingWebhooksReadyToSend(ctx context.Context, limit uint64) ([]*webhook.Record, error)
// Chat
// --------------------------------------------------------------------------------
PutChat(ctx context.Context, record *chat.Chat) error
GetChatById(ctx context.Context, chatId chat.ChatId) (*chat.Chat, error)
GetAllChatsForUser(ctx context.Context, user string, opts ...query.Option) ([]*chat.Chat, error)
PutChatMessage(ctx context.Context, record *chat.Message) error
DeleteChatMessage(ctx context.Context, chatId chat.ChatId, messageId string) error
GetChatMessage(ctx context.Context, chatId chat.ChatId, messageId string) (*chat.Message, error)
GetAllChatMessages(ctx context.Context, chatId chat.ChatId, opts ...query.Option) ([]*chat.Message, error)
AdvanceChatPointer(ctx context.Context, chatId chat.ChatId, pointer string) error
GetChatUnreadCount(ctx context.Context, chatId chat.ChatId) (uint32, error)
SetChatMuteState(ctx context.Context, chatId chat.ChatId, isMuted bool) error
SetChatSubscriptionState(ctx context.Context, chatId chat.ChatId, isSubscribed bool) error
// Badge Count
// --------------------------------------------------------------------------------
AddToBadgeCount(ctx context.Context, owner string, amount uint32) error
ResetBadgeCount(ctx context.Context, owner string) error
GetBadgeCount(ctx context.Context, owner string) (*badgecount.Record, error)
// Login
// --------------------------------------------------------------------------------
SaveLogins(ctx context.Context, record *login.MultiRecord) error
GetLoginsByAppInstall(ctx context.Context, appInstallId string) (*login.MultiRecord, error)
GetLatestLoginByOwner(ctx context.Context, owner string) (*login.Record, error)
// Balance
// --------------------------------------------------------------------------------
SaveBalanceCheckpoint(ctx context.Context, record *balance.Record) error
GetBalanceCheckpoint(ctx context.Context, account string) (*balance.Record, error)
// Onramp
// --------------------------------------------------------------------------------
PutFiatOnrampPurchase(ctx context.Context, record *onramp.Record) error
GetFiatOnrampPurchase(ctx context.Context, nonce uuid.UUID) (*onramp.Record, error)
// User Preferences
// --------------------------------------------------------------------------------
SaveUserPreferences(ctx context.Context, record *preferences.Record) error
GetUserPreferences(ctx context.Context, id *user.DataContainerID) (*preferences.Record, error)
GetUserLocale(ctx context.Context, owner string) (language.Tag, error)
// Airdrop
// --------------------------------------------------------------------------------
MarkIneligibleForAirdrop(ctx context.Context, owner string) error
IsEligibleForAirdrop(ctx context.Context, owner string) (bool, error)
// Twitter
// --------------------------------------------------------------------------------
SaveTwitterUser(ctx context.Context, record *twitter.Record) error
GetTwitterUserByUsername(ctx context.Context, username string) (*twitter.Record, error)
GetTwitterUserByTipAddress(ctx context.Context, tipAddress string) (*twitter.Record, error)
GetStaleTwitterUsers(ctx context.Context, minAge time.Duration, limit int) ([]*twitter.Record, error)
MarkTweetAsProcessed(ctx context.Context, tweetId string) error
IsTweetProcessed(ctx context.Context, tweetId string) (bool, error)
MarkTwitterNonceAsUsed(ctx context.Context, tweetId string, nonce uuid.UUID) error
// ExecuteInTx executes fn with a single DB transaction that is scoped to the call.
// This enables more complex transactions that can span many calls across the provider.
//
// Note: This highly relies on the store implementations adding explicit support for
// this, which was added way later than when most were written. When using this
// function, ensure there is proper support for whatever is being called inside fn.
ExecuteInTx(ctx context.Context, isolation sql.IsolationLevel, fn func(ctx context.Context) error) error
}
type DatabaseProvider struct {
accounts account.Store
currencies currency.Store
vault vault.Store
nonces nonce.Store
fulfillments fulfillment.Store
intents intent.Store
actions action.Store
payments payment.Store
transactions transaction.Store
messages messaging.Store
phone phone.Store
contact contact.Store
userIdentity identity.Store
userStorage storage.Store
timelock timelock.Store
push push.Store
commitment commitment.Store
treasury treasury.Store
merkleTree merkletree.Store
deposits deposit.Store
rendezvous rendezvous.Store
paymentRequest paymentrequest.Store
paywall paywall.Store
event event.Store
webhook webhook.Store
chat chat.Store
badgecount badgecount.Store
login login.Store
balance balance.Store
onramp onramp.Store
preferences preferences.Store
airdrop airdrop.Store
twitter twitter.Store
exchangeCache cache.Cache
timelockCache cache.Cache
db *sqlx.DB
}
func NewDatabaseProvider(dbConfig *pg.Config) (DatabaseData, error) {
db, err := pg.NewWithUsernameAndPassword(
dbConfig.User,
dbConfig.Password,
dbConfig.Host,
fmt.Sprint(dbConfig.Port),
dbConfig.DbName,
)
if err != nil {
return nil, err
}
if dbConfig.MaxOpenConnections > 0 {
db.SetMaxOpenConns(dbConfig.MaxOpenConnections)
}
if dbConfig.MaxIdleConnections > 0 {
db.SetMaxIdleConns(dbConfig.MaxIdleConnections)
}
db.SetConnMaxIdleTime(time.Hour)
db.SetConnMaxLifetime(time.Hour)
return &DatabaseProvider{
accounts: account_postgres_client.New(db),
currencies: currency_postgres_client.New(db),
nonces: nonce_postgres_client.New(db),
fulfillments: fulfillment_postgres_client.New(db),
intents: intent_postgres_client.New(db),
actions: action_postgres_client.New(db),
payments: payment_postgres_client.New(db),
transactions: transaction_postgres_client.New(db),
messages: messaging_postgres_client.New(db),
phone: phone_postgres_client.New(db),
contact: contact_postgres_client.New(db),
userIdentity: user_identity_postgres_client.New(db),
userStorage: user_storage_postgres_client.New(db),
timelock: timelock_postgres_client.New(db),
vault: vault_postgres_client.New(db),
push: push_postgres_client.New(db),
commitment: commitment_postgres_client.New(db),
treasury: treasury_postgres_client.New(db),
merkleTree: merkletree_postgres_client.New(db),
deposits: deposit_postgres_client.New(db),
rendezvous: rendezvous_postgres_client.New(db),
paymentRequest: paymentrequest_postgres_client.New(db),
paywall: paywall_postgres_client.New(db),
event: event_postgres_client.New(db),
webhook: webhook_postgres_client.New(db),
chat: chat_postgres_client.New(db),
badgecount: badgecount_postgres_client.New(db),
login: login_postgres_client.New(db),
balance: balance_postgres_client.New(db),
onramp: onramp_postgres_client.New(db),
preferences: preferences_postgres_client.New(db),
airdrop: airdrop_postgres_client.New(db),
twitter: twitter_postgres_client.New(db),
exchangeCache: cache.NewCache(maxExchangeRateCacheBudget),
timelockCache: cache.NewCache(maxTimelockCacheBudget),
db: sqlx.NewDb(db, "pgx"),
}, nil
}
func NewTestDatabaseProvider() DatabaseData {
return &DatabaseProvider{
accounts: account_memory_client.New(),
currencies: currency_memory_client.New(),
nonces: nonce_memory_client.New(),
fulfillments: fulfillment_memory_client.New(),
intents: intent_memory_client.New(),
actions: action_memory_client.New(),
payments: payment_memory_client.New(),
transactions: transaction_memory_client.New(),
phone: phone_memory_client.New(),
contact: contact_memory_client.New(),
userIdentity: user_identity_memory_client.New(),
userStorage: user_storage_memory_client.New(),
timelock: timelock_memory_client.New(),
vault: vault_memory_client.New(),
push: push_memory_client.New(),
commitment: commitment_memory_client.New(),
treasury: treasury_memory_client.New(),
merkleTree: merkletree_memory_client.New(),
messages: messaging_memory_client.New(),
deposits: deposit_memory_client.New(),
rendezvous: rendezvous_memory_client.New(),
paymentRequest: paymentrequest_memory_client.New(),
paywall: paywall_memory_client.New(),
event: event_memory_client.New(),
webhook: webhook_memory_client.New(),
chat: chat_memory_client.New(),
badgecount: badgecount_memory_client.New(),
login: login_memory_client.New(),
balance: balance_memory_client.New(),
onramp: onramp_memory_client.New(),
preferences: preferences_memory_client.New(),
airdrop: airdrop_memory_client.New(),
twitter: twitter_memory_client.New(),
exchangeCache: cache.NewCache(maxExchangeRateCacheBudget),
timelockCache: nil, // Shouldn't be used for tests
}
}
func (dp *DatabaseProvider) ExecuteInTx(ctx context.Context, isolation sql.IsolationLevel, fn func(ctx context.Context) error) error {
if dp.db == nil {
return fn(ctx)
}
return pg.ExecuteTxWithinCtx(ctx, dp.db, isolation, fn)
}
// Account Info
// --------------------------------------------------------------------------------
func (dp *DatabaseProvider) CreateAccountInfo(ctx context.Context, record *account.Record) error {
return dp.accounts.Put(ctx, record)
}
func (dp *DatabaseProvider) UpdateAccountInfo(ctx context.Context, record *account.Record) error {
return dp.accounts.Update(ctx, record)
}
func (dp *DatabaseProvider) GetAccountInfoByTokenAddress(ctx context.Context, address string) (*account.Record, error) {
return dp.accounts.GetByTokenAddress(ctx, address)
}
func (dp *DatabaseProvider) GetAccountInfoByAuthorityAddress(ctx context.Context, address string) (*account.Record, error) {
return dp.accounts.GetByAuthorityAddress(ctx, address)
}
func (dp *DatabaseProvider) GetLatestAccountInfosByOwnerAddress(ctx context.Context, address string) (map[commonpb.AccountType][]*account.Record, error) {
return dp.accounts.GetLatestByOwnerAddress(ctx, address)
}
func (dp *DatabaseProvider) GetLatestAccountInfoByOwnerAddressAndType(ctx context.Context, address string, accountType commonpb.AccountType) (*account.Record, error) {
return dp.accounts.GetLatestByOwnerAddressAndType(ctx, address, accountType)
}
func (dp *DatabaseProvider) GetRelationshipAccountInfoByOwnerAddress(ctx context.Context, address, relationshipTo string) (*account.Record, error) {
return dp.accounts.GetRelationshipByOwnerAddress(ctx, address, relationshipTo)
}
func (dp *DatabaseProvider) GetPrioritizedAccountInfosRequiringDepositSync(ctx context.Context, limit uint64) ([]*account.Record, error) {
return dp.accounts.GetPrioritizedRequiringDepositSync(ctx, limit)
}
func (dp *DatabaseProvider) GetPrioritizedAccountInfosRequiringAutoReturnCheck(ctx context.Context, maxAge time.Duration, limit uint64) ([]*account.Record, error) {
return dp.accounts.GetPrioritizedRequiringAutoReturnCheck(ctx, maxAge, limit)
}
func (dp *DatabaseProvider) GetPrioritizedAccountInfosRequiringSwapRetry(ctx context.Context, maxAge time.Duration, limit uint64) ([]*account.Record, error) {
return dp.accounts.GetPrioritizedRequiringSwapRetry(ctx, maxAge, limit)
}
func (dp *DatabaseProvider) GetAccountInfoCountRequiringDepositSync(ctx context.Context) (uint64, error) {
return dp.accounts.CountRequiringDepositSync(ctx)
}
func (dp *DatabaseProvider) GetAccountInfoCountRequiringAutoReturnCheck(ctx context.Context) (uint64, error) {
return dp.accounts.CountRequiringAutoReturnCheck(ctx)
}
func (dp *DatabaseProvider) GetAccountInfoCountRequiringSwapRetry(ctx context.Context) (uint64, error) {
return dp.accounts.CountRequiringSwapRetry(ctx)
}
// Currency
// --------------------------------------------------------------------------------
func (dp *DatabaseProvider) GetExchangeRate(ctx context.Context, code currency_lib.Code, t time.Time) (*currency.ExchangeRateRecord, error) {
key := fmt.Sprintf("%s:%s", code, t.Truncate(5*time.Minute).Format(time.RFC3339))
if rate, ok := dp.exchangeCache.Retrieve(key); ok {
return rate.(*currency.ExchangeRateRecord), nil
}
rate, err := dp.currencies.Get(ctx, string(code), t)
if err != nil {
return nil, err
}
dp.exchangeCache.Insert(key, rate, singleExchangeRateCacheWeight)
return rate, nil
}
func (dp *DatabaseProvider) GetAllExchangeRates(ctx context.Context, t time.Time) (*currency.MultiRateRecord, error) {
key := fmt.Sprintf("everything:%s", t.Truncate(5*time.Minute).Format(time.RFC3339))
if rates, ok := dp.exchangeCache.Retrieve(key); ok {
return rates.(*currency.MultiRateRecord), nil
}
rates, err := dp.currencies.GetAll(ctx, t)
if err != nil {
return nil, err
}
dp.exchangeCache.Insert(key, rates, multiExchangeRateCacheWeight)
return rates, nil
}
func (dp *DatabaseProvider) GetExchangeRateHistory(ctx context.Context, code currency_lib.Code, opts ...query.Option) ([]*currency.ExchangeRateRecord, error) {
req := query.QueryOptions{
Limit: maxCurrencyHistoryReqSize,
End: time.Now(),
SortBy: query.Ascending,
Supported: query.CanLimitResults | query.CanSortBy | query.CanBucketBy | query.CanQueryByStartTime | query.CanQueryByEndTime,
}
req.Apply(opts...)
if req.Start.IsZero() {
return nil, query.ErrQueryNotSupported
}
if req.Limit > maxCurrencyHistoryReqSize {
return nil, query.ErrQueryNotSupported
}
return dp.currencies.GetRange(ctx, string(code), req.Interval, req.Start, req.End, req.SortBy)
}
func (dp *DatabaseProvider) ImportExchangeRates(ctx context.Context, data *currency.MultiRateRecord) error {
return dp.currencies.Put(ctx, data)
}
// Vault
// --------------------------------------------------------------------------------
func (dp *DatabaseProvider) GetKey(ctx context.Context, public_key string) (*vault.Record, error) {
return dp.vault.Get(ctx, public_key)
}
func (dp *DatabaseProvider) GetKeyCount(ctx context.Context) (uint64, error) {
return dp.vault.Count(ctx)
}
func (dp *DatabaseProvider) GetKeyCountByState(ctx context.Context, state vault.State) (uint64, error) {
return dp.vault.CountByState(ctx, state)
}
func (dp *DatabaseProvider) GetAllKeysByState(ctx context.Context, state vault.State, opts ...query.Option) ([]*vault.Record, error) {
req, err := query.DefaultPaginationHandlerWithLimit(25, opts...)
if err != nil {
return nil, err
}
return dp.vault.GetAllByState(ctx, state, req.Cursor, req.Limit, req.SortBy)
}
func (dp *DatabaseProvider) SaveKey(ctx context.Context, record *vault.Record) error {
return dp.vault.Save(ctx, record)
}
// Nonce
// --------------------------------------------------------------------------------
func (dp *DatabaseProvider) GetNonce(ctx context.Context, address string) (*nonce.Record, error) {
return dp.nonces.Get(ctx, address)
}
func (dp *DatabaseProvider) GetNonceCount(ctx context.Context) (uint64, error) {
return dp.nonces.Count(ctx)
}
func (dp *DatabaseProvider) GetNonceCountByState(ctx context.Context, state nonce.State) (uint64, error) {
return dp.nonces.CountByState(ctx, state)
}
func (dp *DatabaseProvider) GetNonceCountByStateAndPurpose(ctx context.Context, state nonce.State, purpose nonce.Purpose) (uint64, error) {
return dp.nonces.CountByStateAndPurpose(ctx, state, purpose)
}
func (dp *DatabaseProvider) GetAllNonceByState(ctx context.Context, state nonce.State, opts ...query.Option) ([]*nonce.Record, error) {
req, err := query.DefaultPaginationHandler(opts...)
if err != nil {
return nil, err
}
return dp.nonces.GetAllByState(ctx, state, req.Cursor, req.Limit, req.SortBy)
}
func (dp *DatabaseProvider) GetRandomAvailableNonceByPurpose(ctx context.Context, purpose nonce.Purpose) (*nonce.Record, error) {
return dp.nonces.GetRandomAvailableByPurpose(ctx, purpose)
}
func (dp *DatabaseProvider) SaveNonce(ctx context.Context, record *nonce.Record) error {
return dp.nonces.Save(ctx, record)
}
// Fulfillment
// --------------------------------------------------------------------------------
func (dp *DatabaseProvider) GetFulfillmentById(ctx context.Context, id uint64) (*fulfillment.Record, error) {
return dp.fulfillments.GetById(ctx, id)
}
func (dp *DatabaseProvider) GetFulfillmentBySignature(ctx context.Context, signature string) (*fulfillment.Record, error) {
return dp.fulfillments.GetBySignature(ctx, signature)
}
func (dp *DatabaseProvider) GetFulfillmentCount(ctx context.Context) (uint64, error) {
return dp.fulfillments.Count(ctx)
}
func (dp *DatabaseProvider) GetFulfillmentCountByState(ctx context.Context, state fulfillment.State) (uint64, error) {
return dp.fulfillments.CountByState(ctx, state)
}
func (dp *DatabaseProvider) GetFulfillmentCountByStateGroupedByType(ctx context.Context, state fulfillment.State) (map[fulfillment.Type]uint64, error) {
return dp.fulfillments.CountByStateGroupedByType(ctx, state)
}
func (dp *DatabaseProvider) GetFulfillmentCountForMetrics(ctx context.Context, state fulfillment.State) (map[fulfillment.Type]uint64, error) {
return dp.fulfillments.CountForMetrics(ctx, state)
}
func (dp *DatabaseProvider) GetFulfillmentCountByStateAndAddress(ctx context.Context, state fulfillment.State, address string) (uint64, error) {
return dp.fulfillments.CountByStateAndAddress(ctx, state, address)
}
func (dp *DatabaseProvider) GetFulfillmentCountByTypeStateAndAddress(ctx context.Context, fulfillmentType fulfillment.Type, state fulfillment.State, address string) (uint64, error) {
return dp.fulfillments.CountByTypeStateAndAddress(ctx, fulfillmentType, state, address)
}
func (dp *DatabaseProvider) GetFulfillmentCountByTypeStateAndAddressAsSource(ctx context.Context, fulfillmentType fulfillment.Type, state fulfillment.State, address string) (uint64, error) {
return dp.fulfillments.CountByTypeStateAndAddressAsSource(ctx, fulfillmentType, state, address)
}
func (dp *DatabaseProvider) GetFulfillmentCountByIntentAndState(ctx context.Context, intent string, state fulfillment.State) (uint64, error) {
return dp.fulfillments.CountByIntentAndState(ctx, intent, state)
}
func (dp *DatabaseProvider) GetFulfillmentCountByIntent(ctx context.Context, intent string) (uint64, error) {
return dp.fulfillments.CountByIntent(ctx, intent)
}
func (dp *DatabaseProvider) GetFulfillmentCountByTypeActionAndState(ctx context.Context, intentId string, actionId uint32, fulfillmentType fulfillment.Type, state fulfillment.State) (uint64, error) {
return dp.fulfillments.CountByTypeActionAndState(ctx, intentId, actionId, fulfillmentType, state)
}
func (dp *DatabaseProvider) GetPendingFulfillmentCountByType(ctx context.Context) (map[fulfillment.Type]uint64, error) {
return dp.fulfillments.CountPendingByType(ctx)
}
func (dp *DatabaseProvider) GetAllFulfillmentsByState(ctx context.Context, state fulfillment.State, includeDisabledActiveScheduling bool, opts ...query.Option) ([]*fulfillment.Record, error) {
req, err := query.DefaultPaginationHandler(opts...)
if err != nil {
return nil, err
}
return dp.fulfillments.GetAllByState(ctx, state, includeDisabledActiveScheduling, req.Cursor, req.Limit, req.SortBy)
}
func (dp *DatabaseProvider) GetAllFulfillmentsByIntent(ctx context.Context, intent string, opts ...query.Option) ([]*fulfillment.Record, error) {
req, err := query.DefaultPaginationHandler(opts...)
if err != nil {
return nil, err
}
return dp.fulfillments.GetAllByIntent(ctx, intent, req.Cursor, req.Limit, req.SortBy)
}
func (dp *DatabaseProvider) GetAllFulfillmentsByAction(ctx context.Context, intentId string, actionId uint32) ([]*fulfillment.Record, error) {
return dp.fulfillments.GetAllByAction(ctx, intentId, actionId)
}
func (dp *DatabaseProvider) GetAllFulfillmentsByTypeAndAction(ctx context.Context, fulfillmentType fulfillment.Type, intentId string, actionId uint32) ([]*fulfillment.Record, error) {
return dp.fulfillments.GetAllByTypeAndAction(ctx, fulfillmentType, intentId, actionId)
}
func (dp *DatabaseProvider) GetFirstSchedulableFulfillmentByAddressAsSource(ctx context.Context, address string) (*fulfillment.Record, error) {
return dp.fulfillments.GetFirstSchedulableByAddressAsSource(ctx, address)
}
func (dp *DatabaseProvider) GetFirstSchedulableFulfillmentByAddressAsDestination(ctx context.Context, address string) (*fulfillment.Record, error) {
return dp.fulfillments.GetFirstSchedulableByAddressAsDestination(ctx, address)
}
func (dp *DatabaseProvider) GetFirstSchedulableFulfillmentByType(ctx context.Context, fulfillmentType fulfillment.Type) (*fulfillment.Record, error) {
return dp.fulfillments.GetFirstSchedulableByType(ctx, fulfillmentType)
}
func (dp *DatabaseProvider) GetNextSchedulableFulfillmentByAddress(ctx context.Context, address string, intentOrderingIndex uint64, actionOrderingIndex, fulfillmentOrderingIndex uint32) (*fulfillment.Record, error) {
return dp.fulfillments.GetNextSchedulableByAddress(ctx, address, intentOrderingIndex, actionOrderingIndex, fulfillmentOrderingIndex)
}
func (dp *DatabaseProvider) PutAllFulfillments(ctx context.Context, records ...*fulfillment.Record) error {
return dp.fulfillments.PutAll(ctx, records...)
}
func (dp *DatabaseProvider) UpdateFulfillment(ctx context.Context, record *fulfillment.Record) error {
return dp.fulfillments.Update(ctx, record)
}
func (dp *DatabaseProvider) MarkFulfillmentAsActivelyScheduled(ctx context.Context, id uint64) error {
return dp.fulfillments.MarkAsActivelyScheduled(ctx, id)
}
func (dp *DatabaseProvider) ActivelyScheduleTreasuryAdvanceFulfillments(ctx context.Context, treasury string, intentOrderingIndex uint64, limit int) (uint64, error) {
return dp.fulfillments.ActivelyScheduleTreasuryAdvances(ctx, treasury, intentOrderingIndex, limit)
}
// Intent
// --------------------------------------------------------------------------------
func (dp *DatabaseProvider) GetIntent(ctx context.Context, intentID string) (*intent.Record, error) {
return dp.intents.Get(ctx, intentID)
}
func (dp *DatabaseProvider) GetIntentBySignature(ctx context.Context, signature string) (*intent.Record, error) {
fulfillmentRecord, err := dp.fulfillments.GetBySignature(ctx, signature)
if err == fulfillment.ErrFulfillmentNotFound {
return nil, intent.ErrIntentNotFound
} else if err != nil {
return nil, err
}
return dp.intents.Get(ctx, fulfillmentRecord.Intent)
}
func (dp *DatabaseProvider) GetLatestIntentByInitiatorAndType(ctx context.Context, intentType intent.Type, owner string) (*intent.Record, error) {
return dp.intents.GetLatestByInitiatorAndType(ctx, intentType, owner)
}
func (dp *DatabaseProvider) GetAllIntentsByOwner(ctx context.Context, owner string, opts ...query.Option) ([]*intent.Record, error) {
req, err := query.DefaultPaginationHandler(opts...)
if err != nil {
return nil, err
}
return dp.intents.GetAllByOwner(ctx, owner, req.Cursor, req.Limit, req.SortBy)
}
func (dp *DatabaseProvider) GetIntentCountForAntispam(ctx context.Context, intentType intent.Type, phoneNumber string, states []intent.State, since time.Time) (uint64, error) {
return dp.intents.CountForAntispam(ctx, intentType, phoneNumber, states, since)
}
func (dp *DatabaseProvider) GetIntentCountWithOwnerInteractionsForAntispam(ctx context.Context, sourceOwner, destinationOwner string, states []intent.State, since time.Time) (uint64, error) {
return dp.intents.CountOwnerInteractionsForAntispam(ctx, sourceOwner, destinationOwner, states, since)
}
func (dp *DatabaseProvider) GetTransactedAmountForAntiMoneyLaundering(ctx context.Context, phoneNumber string, since time.Time) (uint64, float64, error) {
return dp.intents.GetTransactedAmountForAntiMoneyLaundering(ctx, phoneNumber, since)
}
func (dp *DatabaseProvider) GetDepositedAmountForAntiMoneyLaundering(ctx context.Context, phoneNumber string, since time.Time) (uint64, float64, error) {
return dp.intents.GetDepositedAmountForAntiMoneyLaundering(ctx, phoneNumber, since)
}
func (dp *DatabaseProvider) GetNetBalanceFromPrePrivacy2022Intents(ctx context.Context, account string) (int64, error) {
return dp.intents.GetNetBalanceFromPrePrivacy2022Intents(ctx, account)
}
func (dp *DatabaseProvider) GetLatestSaveRecentRootIntentForTreasury(ctx context.Context, treasury string) (*intent.Record, error) {
return dp.intents.GetLatestSaveRecentRootIntentForTreasury(ctx, treasury)
}
func (dp *DatabaseProvider) GetOriginalGiftCardIssuedIntent(ctx context.Context, giftCardVault string) (*intent.Record, error) {
return dp.intents.GetOriginalGiftCardIssuedIntent(ctx, giftCardVault)
}
func (dp *DatabaseProvider) GetGiftCardClaimedIntent(ctx context.Context, giftCardVault string) (*intent.Record, error) {
return dp.intents.GetGiftCardClaimedIntent(ctx, giftCardVault)
}
func (dp *DatabaseProvider) SaveIntent(ctx context.Context, record *intent.Record) error {
return dp.intents.Save(ctx, record)
}
// Action
// --------------------------------------------------------------------------------
func (dp *DatabaseProvider) PutAllActions(ctx context.Context, records ...*action.Record) error {
return dp.actions.PutAll(ctx, records...)
}
func (dp *DatabaseProvider) UpdateAction(ctx context.Context, record *action.Record) error {
return dp.actions.Update(ctx, record)
}
func (dp *DatabaseProvider) GetActionById(ctx context.Context, intent string, actionId uint32) (*action.Record, error) {
return dp.actions.GetById(ctx, intent, actionId)
}
func (dp *DatabaseProvider) GetAllActionsByIntent(ctx context.Context, intent string) ([]*action.Record, error) {
return dp.actions.GetAllByIntent(ctx, intent)
}
func (dp *DatabaseProvider) GetAllActionsByAddress(ctx context.Context, address string) ([]*action.Record, error) {
return dp.actions.GetAllByAddress(ctx, address)
}
func (dp *DatabaseProvider) GetNetBalanceFromActions(ctx context.Context, address string) (int64, error) {
return dp.actions.GetNetBalance(ctx, address)
}
func (dp *DatabaseProvider) GetNetBalanceFromActionsBatch(ctx context.Context, accounts ...string) (map[string]int64, error) {
return dp.actions.GetNetBalanceBatch(ctx, accounts...)
}
func (dp *DatabaseProvider) GetGiftCardClaimedAction(ctx context.Context, giftCardVault string) (*action.Record, error) {
return dp.actions.GetGiftCardClaimedAction(ctx, giftCardVault)
}
func (dp *DatabaseProvider) GetGiftCardAutoReturnAction(ctx context.Context, giftCardVault string) (*action.Record, error) {
return dp.actions.GetGiftCardAutoReturnAction(ctx, giftCardVault)
}
// Payment
// --------------------------------------------------------------------------------
func (dp *DatabaseProvider) GetPayment(ctx context.Context, sig string, index int) (*payment.Record, error) {
return dp.payments.Get(ctx, sig, uint32(index))
}
func (dp *DatabaseProvider) CreatePayment(ctx context.Context, record *payment.Record) error {
return dp.payments.Put(ctx, record)
}
func (dp *DatabaseProvider) UpdatePayment(ctx context.Context, record *payment.Record) error {
return dp.payments.Update(ctx, record)
}
func (dp *DatabaseProvider) UpdateOrCreatePayment(ctx context.Context, record *payment.Record) error {
if record.Id > 0 {
return dp.UpdatePayment(ctx, record)
}
return dp.CreatePayment(ctx, record)
}
func (dp *DatabaseProvider) GetPaymentHistory(ctx context.Context, account string, opts ...query.Option) ([]*payment.Record, error) {
req := query.QueryOptions{
Limit: maxPaymentHistoryReqSize,
SortBy: query.Ascending,
Supported: query.CanLimitResults | query.CanSortBy | query.CanQueryByCursor | query.CanFilterBy,
}
req.Apply(opts...)
if req.Limit > maxPaymentHistoryReqSize {
return nil, query.ErrQueryNotSupported
}
var cursor uint64
if len(req.Cursor) > 0 {
cursor = query.FromCursor(req.Cursor)
} else {
cursor = 0
}
if req.FilterBy.Valid {
return dp.payments.GetAllForAccountByType(ctx, account, cursor, uint(req.Limit), req.SortBy, payment.PaymentType(req.FilterBy.Value))
}
return dp.payments.GetAllForAccount(ctx, account, cursor, uint(req.Limit), req.SortBy)
}
func (dp *DatabaseProvider) GetPaymentHistoryWithinBlockRange(ctx context.Context, account string, lowerBound, upperBound uint64, opts ...query.Option) ([]*payment.Record, error) {
req := query.QueryOptions{
Limit: maxPaymentHistoryReqSize,
SortBy: query.Ascending,
Supported: query.CanLimitResults | query.CanSortBy | query.CanQueryByCursor | query.CanFilterBy,
}
req.Apply(opts...)
if req.Limit > maxPaymentHistoryReqSize {
return nil, query.ErrQueryNotSupported
}
var cursor uint64
if len(req.Cursor) > 0 {
cursor = query.FromCursor(req.Cursor)
} else {
cursor = 0
}
if req.FilterBy.Valid {
return dp.payments.GetAllForAccountByTypeWithinBlockRange(ctx, account, lowerBound, upperBound, cursor, uint(req.Limit), req.SortBy, payment.PaymentType(req.FilterBy.Value))
}
return nil, query.ErrQueryNotSupported
}
func (dp *DatabaseProvider) GetLegacyTotalExternalDepositAmountFromPrePrivacy2022Accounts(ctx context.Context, account string) (uint64, error) {
return dp.payments.GetExternalDepositAmount(ctx, account)
}
// Transaction
// --------------------------------------------------------------------------------
func (dp *DatabaseProvider) GetTransaction(ctx context.Context, sig string) (*transaction.Record, error) {
return dp.transactions.Get(ctx, sig)
}
func (dp *DatabaseProvider) SaveTransaction(ctx context.Context, record *transaction.Record) error {
return dp.transactions.Put(ctx, record)
}