-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwallet_view_controller.go
More file actions
687 lines (531 loc) · 17.3 KB
/
wallet_view_controller.go
File metadata and controls
687 lines (531 loc) · 17.3 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
package sdk
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/urnetwork/glog"
"github.com/urnetwork/connect"
)
type AccountWalletsListener interface {
AccountWalletsChanged()
}
type PaymentsListener interface {
PaymentsChanged()
}
type IsCreatingExternalWalletListener interface {
StateChanged(bool)
}
type IsRemovingWalletListener interface {
StateChanged(bool)
}
type UnpaidByteCountListener interface {
StateChanged(ByteCount)
}
type PayoutWalletListener interface {
PayoutWalletChanged(*Id)
}
type AccountWallet struct {
WalletId *Id `json:"wallet_id"`
CircleWalletId string `json:"circle_wallet_id,omitempty"`
NetworkId *Id `json:"network_id"`
WalletType WalletType `json:"wallet_type"`
Blockchain string `json:"blockchain"`
WalletAddress string `json:"wallet_address"`
Active bool `json:"active"`
DefaultTokenType string `json:"default_token_type"`
CreateTime *Time `json:"create_time"`
HasSeekerToken bool `json:"has_seeker_token"`
}
type AccountPayment struct {
PaymentId *Id `json:"payment_id"`
PaymentPlanId *Id `json:"payment_plan_id"`
WalletId *Id `json:"wallet_id"`
NetworkId *Id `json:"network_id"`
PayoutByteCount ByteCount `json:"payout_byte_count"`
Payout NanoCents `json:"payout_nano_cents"`
MinSweepTime *Time `json:"min_sweep_time"`
CreateTime *Time `json:"create_time"`
PaymentRecord string `json:"payment_record,omitempty"`
TokenType string `json:"token_type"`
TokenAmount float64 `json:"token_amount,omitempty"`
PaymentTime *Time `json:"payment_time,omitempty"`
PaymentReceipt string `json:"payment_receipt,omitempty"`
WalletAddress string `json:"wallet_address"`
Blockchain string `json:"blockchain,omitempty"`
TxHash string `json:"tx_hash,omitempty"`
Completed bool `json:"completed,omitempty"`
CompleteTime *Time `json:"complete_time,omitempty"`
Canceled bool `json:"canceled"`
CancelTime *Time `json:"cancel_time,omitempty"`
}
type WalletViewController struct {
ctx context.Context
cancel context.CancelFunc
device Device
wallets *AccountWalletsList
isAddingExternalWallet bool
isRemovingWallet bool
payoutWalletId *Id
accountPayments *AccountPaymentsList
isPollingAccountWallets bool
isPollingPayoutWallet bool
isFetchingTransferStats bool
unpaidByteCount ByteCount
stateLock sync.Mutex
accountWalletsListeners *connect.CallbackList[AccountWalletsListener]
payoutWalletListeners *connect.CallbackList[PayoutWalletListener]
paymentsListeners *connect.CallbackList[PaymentsListener]
isCreatingExternalWalletListeners *connect.CallbackList[IsCreatingExternalWalletListener]
isRemovingWalletListeners *connect.CallbackList[IsRemovingWalletListener]
unpaidByteCountListeners *connect.CallbackList[UnpaidByteCountListener]
}
func newWalletViewController(ctx context.Context, device Device) *WalletViewController {
cancelCtx, cancel := context.WithCancel(ctx)
vc := &WalletViewController{
ctx: cancelCtx,
cancel: cancel,
device: device,
wallets: NewAccountWalletsList(),
isAddingExternalWallet: false,
isRemovingWallet: false,
payoutWalletId: nil,
accountPayments: NewAccountPaymentsList(),
isPollingAccountWallets: false,
isPollingPayoutWallet: false,
isFetchingTransferStats: false,
unpaidByteCount: 0,
accountWalletsListeners: connect.NewCallbackList[AccountWalletsListener](),
payoutWalletListeners: connect.NewCallbackList[PayoutWalletListener](),
paymentsListeners: connect.NewCallbackList[PaymentsListener](),
isCreatingExternalWalletListeners: connect.NewCallbackList[IsCreatingExternalWalletListener](),
isRemovingWalletListeners: connect.NewCallbackList[IsRemovingWalletListener](),
unpaidByteCountListeners: connect.NewCallbackList[UnpaidByteCountListener](),
}
return vc
}
func (self *WalletViewController) Start() {
go connect.HandleError(self.FetchAccountWallets)
go connect.HandleError(self.FetchPayoutWallet)
go connect.HandleError(self.FetchPayments)
go connect.HandleError(self.FetchTransferStats)
self.pollNewWallets()
}
func (vc *WalletViewController) Stop() {
// FIXME
}
func (vc *WalletViewController) Close() {
glog.Info("[wvc]close")
vc.cancel()
}
func (vc *WalletViewController) GetNextPayoutDate() string {
now := time.Now().UTC()
year := now.Year()
month := now.Month()
day := now.Day()
var nextPayoutDate time.Time
switch {
case day < 15:
nextPayoutDate = time.Date(year, month, 15, 0, 0, 0, 0, time.UTC)
case month == time.December:
nextPayoutDate = time.Date(year+1, time.January, 1, 0, 0, 0, 0, time.UTC)
default:
nextPayoutDate = time.Date(year, month+1, 1, 0, 0, 0, 0, time.UTC)
}
return nextPayoutDate.Format("Jan 2")
}
type ValidateAddressCallback interface {
SendResult(valid bool)
}
type validateAddressCallbackImpl struct {
sendResult func(bool)
}
func (v *validateAddressCallbackImpl) SendResult(valid bool) {
v.sendResult(valid)
}
// Return the concrete type instead of the interface pointer
func NewValidateAddressCallback(sendResult func(bool)) *validateAddressCallbackImpl {
return &validateAddressCallbackImpl{sendResult: sendResult}
}
func (vc *WalletViewController) ValidateAddress(
address string,
blockchain Blockchain,
callback ValidateAddressCallback,
) {
vc.device.GetApi().WalletValidateAddress(
&WalletValidateAddressArgs{
Address: address,
Chain: blockchain,
},
connect.NewApiCallback[*WalletValidateAddressResult](
func(result *WalletValidateAddressResult, err error) {
if err != nil {
glog.Infof("[wvc]error validating address %s on %s: %s", address, blockchain, err)
callback.SendResult(false)
}
callback.SendResult(result.Valid)
}),
)
}
func (vc *WalletViewController) AddIsCreatingExternalWalletListener(listener IsCreatingExternalWalletListener) Sub {
callbackId := vc.isCreatingExternalWalletListeners.Add(listener)
return newSub(func() {
vc.accountWalletsListeners.Remove(callbackId)
})
}
func (vc *WalletViewController) isCreatingExternalWalletChanged(isProcessing bool) {
for _, listener := range vc.isCreatingExternalWalletListeners.Get() {
connect.HandleError(func() {
listener.StateChanged(isProcessing)
})
}
}
func (vc *WalletViewController) setIsCreatingExternalWallet(state bool) {
vc.stateLock.Lock()
defer vc.stateLock.Unlock()
vc.isAddingExternalWallet = state
vc.isCreatingExternalWalletChanged(vc.isAddingExternalWallet)
}
func (vc *WalletViewController) AddExternalWallet(address string, blockchain Blockchain) {
if !vc.isAddingExternalWallet {
blockchainUpper := strings.ToUpper(blockchain)
if blockchainUpper != "SOL" && blockchainUpper != "MATIC" {
glog.Infof("[wvc]invalid blockchain passed: %s", blockchainUpper)
return
}
vc.setIsCreatingExternalWallet(true)
args := &CreateAccountWalletArgs{
Blockchain: blockchainUpper,
WalletAddress: address,
DefaultTokenType: "USDC",
}
vc.device.GetApi().CreateAccountWallet(args, CreateAccountWalletCallback(connect.NewApiCallback[*CreateAccountWalletResult](
func(result *CreateAccountWalletResult, err error) {
if err != nil {
glog.Infof("[wvc]error creating an external wallet: %s", err)
// err = createErr
return
}
vc.setIsCreatingExternalWallet(false)
vc.FetchAccountWallets()
vc.FetchPayoutWallet()
})))
}
}
func (vc *WalletViewController) AddPayoutWalletListener(listener PayoutWalletListener) Sub {
callbackId := vc.payoutWalletListeners.Add(listener)
return newSub(func() {
vc.payoutWalletListeners.Remove(callbackId)
})
}
func (vc *WalletViewController) payoutWalletIdChanged(id *Id) {
for _, listener := range vc.payoutWalletListeners.Get() {
connect.HandleError(func() {
listener.PayoutWalletChanged(id)
})
}
}
func (vc *WalletViewController) UpdatePayoutWallet(walletId *Id) (err error) {
if walletId == nil {
err = fmt.Errorf("no wallet id provided")
return
}
args := &SetPayoutWalletArgs{
WalletId: walletId,
}
vc.device.GetApi().SetPayoutWallet(args, SetPayoutWalletCallback(connect.NewApiCallback[*SetPayoutWalletResult](
func(result *SetPayoutWalletResult, setWalletErr error) {
if setWalletErr != nil {
glog.Infof("[wvc]Error setting payout wallet: %s", err)
return
}
vc.stateLock.Lock()
vc.payoutWalletId = args.WalletId
vc.stateLock.Unlock()
vc.payoutWalletIdChanged(vc.payoutWalletId)
})))
return
}
func (vc *WalletViewController) GetPayoutWalletId() (id *Id) {
return vc.payoutWalletId
}
func (self *WalletViewController) setPayoutWalletId(id *Id) {
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
self.payoutWalletId = id
}()
self.payoutWalletIdChanged(id)
}
func (self *WalletViewController) FetchPayoutWallet() {
self.device.GetApi().GetPayoutWallet(GetPayoutWalletCallback(connect.NewApiCallback[*GetPayoutWalletIdResult](
func(result *GetPayoutWalletIdResult, err error) {
if err != nil {
glog.Infof("error fetching payout wallet: %s", err)
return
}
// if is polling
// check if existing value matches result
if self.isPollingPayoutWallet && (
// no existing payout wallet, but result exists or
(self.payoutWalletId == nil && result.WalletId != nil) ||
// existing payout wallet does not equal incoming payout wallet
(self.payoutWalletId != nil && result.WalletId != nil && self.payoutWalletId.Cmp(result.WalletId) != 0)) {
self.SetIsPollingPayoutWallet(false)
}
self.setPayoutWalletId(result.WalletId)
})))
}
func (vc *WalletViewController) GetWallets() *AccountWalletsList {
return vc.wallets
}
func (vc *WalletViewController) FilterWalletsById(idStr string) *AccountWallet {
id, err := ParseId(idStr)
if err != nil {
return nil
}
for i := 0; i < vc.wallets.Len(); i++ {
wallet := vc.wallets.Get(i)
if wallet.WalletId.Cmp(id) == 0 {
return wallet
}
}
return nil
}
func (vc *WalletViewController) AddAccountWalletsListener(listener AccountWalletsListener) Sub {
callbackId := vc.accountWalletsListeners.Add(listener)
return newSub(func() {
vc.accountWalletsListeners.Remove(callbackId)
})
}
func (vc *WalletViewController) accountWalletsChanged() {
for _, listener := range vc.accountWalletsListeners.Get() {
connect.HandleError(func() {
listener.AccountWalletsChanged()
})
}
}
func (vc *WalletViewController) setAccountWallets(wallets *AccountWalletsList) {
func() {
vc.stateLock.Lock()
defer vc.stateLock.Unlock()
vc.wallets = wallets
}()
vc.accountWalletsChanged()
}
func (self *WalletViewController) FetchAccountWallets() {
self.device.GetApi().GetAccountWallets(connect.NewApiCallback[*GetAccountWalletsResult](
func(results *GetAccountWalletsResult, err error) {
if err != nil {
glog.Infof("[wvc]Error fetching account wallets: %s", err)
return
}
newWalletsList := NewAccountWalletsList()
var wallets []*AccountWallet
// if we are polling for new wallets
// and the new results length does not match the existing wallets length
// stop polling
if self.isPollingAccountWallets && results.Wallets.Len() != self.wallets.Len() {
self.SetIsPollingAccountWallets(false)
}
for i := 0; i < results.Wallets.Len(); i++ {
walletResult := results.Wallets.Get(i)
wallet := &AccountWallet{
WalletId: walletResult.WalletId,
CircleWalletId: walletResult.CircleWalletId,
NetworkId: walletResult.NetworkId,
WalletType: walletResult.WalletType,
Blockchain: walletResult.Blockchain,
WalletAddress: walletResult.WalletAddress,
Active: walletResult.Active,
DefaultTokenType: walletResult.DefaultTokenType,
CreateTime: walletResult.CreateTime,
HasSeekerToken: walletResult.HasSeekerToken,
}
wallets = append(wallets, wallet)
}
newWalletsList.addAll(wallets...)
self.setAccountWallets(newWalletsList)
// we fetch wallets after removing a wallet
if self.isRemovingWallet {
self.setIsRemovingWallet(false)
}
}))
}
func (vc *WalletViewController) AddPaymentsListener(listener PaymentsListener) Sub {
callbackId := vc.paymentsListeners.Add(listener)
return newSub(func() {
vc.paymentsListeners.Remove(callbackId)
})
}
func (vc *WalletViewController) paymentsChanged() {
for _, listener := range vc.paymentsListeners.Get() {
connect.HandleError(func() {
listener.PaymentsChanged()
})
}
}
func (vc *WalletViewController) GetAccountPayments() *AccountPaymentsList {
return vc.accountPayments
}
func (vc *WalletViewController) setAccountPayments(payments []*AccountPayment) {
func() {
vc.stateLock.Lock()
defer vc.stateLock.Unlock()
if len(payments) > 0 {
vc.accountPayments = NewAccountPaymentsList()
vc.accountPayments.addAll(payments...)
}
}()
vc.paymentsChanged()
}
func (vc *WalletViewController) FetchPayments() {
vc.device.GetApi().GetAccountPayments(connect.NewApiCallback[*GetNetworkAccountPaymentsResult](
func(results *GetNetworkAccountPaymentsResult, err error) {
if err != nil {
glog.Infof("[wvc]fetch payments failed: %s", err)
return
}
payouts := []*AccountPayment{}
// todo - why is results.AccountPayments nil and not an empty array?
if results != nil && results.AccountPayments != nil {
for i := 0; i < results.AccountPayments.Len(); i += 1 {
accountPayment := results.AccountPayments.Get(i)
payouts = append(payouts, accountPayment)
}
}
vc.setAccountPayments(payouts)
}))
}
func (vc *WalletViewController) AddIsRemovingWalletListener(listener IsRemovingWalletListener) Sub {
callbackId := vc.isRemovingWalletListeners.Add(listener)
return newSub(func() {
vc.isRemovingWalletListeners.Remove(callbackId)
})
}
func (vc *WalletViewController) isRemovingWalletChanged(isRemoving bool) {
for _, listener := range vc.isRemovingWalletListeners.Get() {
connect.HandleError(func() {
listener.StateChanged(isRemoving)
})
}
}
func (vc *WalletViewController) setIsRemovingWallet(isRemoving bool) {
func() {
vc.stateLock.Lock()
defer vc.stateLock.Unlock()
vc.isRemovingWallet = isRemoving
}()
vc.isRemovingWalletChanged(isRemoving)
}
func (vc *WalletViewController) RemoveWallet(walletId *Id) {
if !vc.isRemovingWallet {
vc.setIsRemovingWallet(true)
vc.device.GetApi().RemoveWallet(
&RemoveWalletArgs{
WalletId: walletId.IdStr,
},
RemoveWalletCallback(connect.NewApiCallback[*RemoveWalletResult](
func(result *RemoveWalletResult, err error) {
if err != nil || !result.Success {
vc.setIsRemovingWallet(false)
}
if result.Success {
vc.FetchAccountWallets()
}
}),
),
)
}
}
func (self *WalletViewController) SetIsPollingAccountWallets(isPolling bool) {
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
self.isPollingAccountWallets = isPolling
}()
}
func (self *WalletViewController) SetIsPollingPayoutWallet(isPolling bool) {
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
self.isPollingPayoutWallet = isPolling
}()
}
// when a user creates a circle wallet, we wait for a webhook from circle
// which creates an account_wallet entry
func (self *WalletViewController) pollNewWallets() {
go connect.HandleError(func() {
ticker := time.NewTicker(2500 * time.Millisecond)
defer ticker.Stop()
defer func() {
if r := recover(); r != nil {
glog.Infof("[wvc]pollNewWallets: recovered from panic: %v", r)
}
}()
for {
select {
case <-self.ctx.Done():
return
case <-ticker.C:
if self.isPollingAccountWallets {
self.FetchAccountWallets()
}
if self.isPollingPayoutWallet {
self.FetchPayoutWallet()
}
}
}
})
}
func (self *WalletViewController) setIsFetchingTransferStats(isFetching bool) {
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
self.isFetchingTransferStats = isFetching
}()
}
func (self *WalletViewController) AddUnpaidByteCountListener(listener UnpaidByteCountListener) Sub {
callbackId := self.unpaidByteCountListeners.Add(listener)
return newSub(func() {
self.unpaidByteCountListeners.Remove(callbackId)
})
}
func (self *WalletViewController) unpaidByteCountChanged(count ByteCount) {
for _, listener := range self.unpaidByteCountListeners.Get() {
connect.HandleError(func() {
listener.StateChanged(count)
})
}
}
func (self *WalletViewController) setUnpaidByteCount(count ByteCount) {
func() {
self.stateLock.Lock()
defer self.stateLock.Unlock()
self.unpaidByteCount = count
}()
self.unpaidByteCountChanged(count)
}
func (self *WalletViewController) GetUnpaidByteCount() ByteCount {
return self.unpaidByteCount
}
/**
* Sum of paid and unpaid bytes provided
**/
func (self *WalletViewController) FetchTransferStats() {
if !self.isFetchingTransferStats {
self.setIsFetchingTransferStats(true)
self.device.GetApi().GetTransferStats(connect.NewApiCallback[*TransferStatsResult](
func(results *TransferStatsResult, err error) {
if err != nil {
glog.Infof("[wvc]error fetching transfer stats: %s", err)
return
}
if results != nil {
self.setUnpaidByteCount(results.UnpaidBytesProvided)
}
self.setIsFetchingTransferStats(false)
}))
}
}