-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstore.go
99 lines (84 loc) · 1.9 KB
/
store.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
package memory
import (
"context"
"sync"
"time"
"github.com/code-payments/code-server/pkg/code/data/paymentrequest"
)
type store struct {
mu sync.Mutex
records []*paymentrequest.Record
last uint64
}
func New() paymentrequest.Store {
return &store{
records: make([]*paymentrequest.Record, 0),
last: 0,
}
}
func (s *store) reset() {
s.mu.Lock()
s.records = make([]*paymentrequest.Record, 0)
s.last = 0
s.mu.Unlock()
}
// Put implements paymentrequest.Store.Put
func (s *store) Put(_ context.Context, data *paymentrequest.Record) error {
if err := data.Validate(); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
s.last++
if item := s.find(data); item != nil {
return paymentrequest.ErrPaymentRequestAlreadyExists
} else {
seenDestinations := make(map[string]any)
for _, fee := range data.Fees {
_, ok := seenDestinations[fee.DestinationTokenAccount]
if ok {
return paymentrequest.ErrInvalidPaymentRequest
}
seenDestinations[fee.DestinationTokenAccount] = true
}
if data.Id == 0 {
data.Id = s.last
}
if data.CreatedAt.IsZero() {
data.CreatedAt = time.Now()
}
c := data.Clone()
s.records = append(s.records, &c)
}
return nil
}
// Get implements paymentrequest.Store.Get
func (s *store) Get(_ context.Context, intentId string) (*paymentrequest.Record, error) {
s.mu.Lock()
defer s.mu.Unlock()
item := s.findByIntent(intentId)
if item == nil {
return nil, paymentrequest.ErrPaymentRequestNotFound
}
cloned := item.Clone()
return &cloned, nil
}
func (s *store) find(data *paymentrequest.Record) *paymentrequest.Record {
for _, item := range s.records {
if item.Id == data.Id {
return item
}
if item.Intent == data.Intent {
return item
}
}
return nil
}
func (s *store) findByIntent(intentId string) *paymentrequest.Record {
for _, item := range s.records {
if item.Intent == intentId {
return item
}
}
return nil
}