-
Notifications
You must be signed in to change notification settings - Fork 0
/
frontend.go
1334 lines (1200 loc) · 38.3 KB
/
frontend.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
// this file is for the implementation of all the frontend-requested service
// endpoints for wallets.
package stellarsvc
import (
"context"
"errors"
"fmt"
"sort"
"strconv"
"unicode/utf8"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/stellar1"
"github.com/keybase/client/go/stellar"
"github.com/keybase/client/go/stellar/remote"
"github.com/keybase/client/go/stellar/stellarcommon"
"github.com/keybase/stellarnet"
stellaramount "github.com/stellar/go/amount"
)
const WorthCurrencyErrorCode = "ERR"
func (s *Server) GetWalletAccountsLocal(ctx context.Context, sessionID int) (accts []stellar1.WalletAccountLocal, err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "GetWalletAccountsLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return nil, err
}
bundle, _, err := remote.Fetch(ctx, s.G())
if err != nil {
return nil, err
}
for _, entry := range bundle.Accounts {
acct, err := s.accountLocal(ctx, entry)
if err != nil {
return nil, err
}
accts = append(accts, acct)
}
// Put the primary account first, then sort by name, then by account ID
sort.SliceStable(accts, func(i, j int) bool {
if accts[i].IsDefault {
return true
}
if accts[j].IsDefault {
return false
}
if accts[i].Name == accts[j].Name {
return accts[i].AccountID < accts[j].AccountID
}
return accts[i].Name < accts[j].Name
})
return accts, nil
}
func (s *Server) GetWalletAccountLocal(ctx context.Context, arg stellar1.GetWalletAccountLocalArg) (acct stellar1.WalletAccountLocal, err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "GetWalletAccountLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return acct, err
}
bundle, _, err := remote.Fetch(ctx, s.G())
if err != nil {
return acct, err
}
entry, err := bundle.Lookup(arg.AccountID)
if err != nil {
return acct, err
}
return s.accountLocal(ctx, entry)
}
func (s *Server) accountLocal(ctx context.Context, entry stellar1.BundleEntry) (stellar1.WalletAccountLocal, error) {
var empty stellar1.WalletAccountLocal
details, err := s.remoter.Details(ctx, entry.AccountID)
if err != nil {
s.G().Log.CDebugf(ctx, "remote.Details failed for %q: %s", entry.AccountID, err)
return empty, err
}
balance, err := balanceList(details.Balances).balanceDescription()
if err != nil {
return empty, err
}
acct := stellar1.WalletAccountLocal{
AccountID: entry.AccountID,
IsDefault: entry.IsPrimary,
Name: entry.Name,
BalanceDescription: balance,
Seqno: details.Seqno,
}
return acct, nil
}
func (s *Server) GetAccountAssetsLocal(ctx context.Context, arg stellar1.GetAccountAssetsLocalArg) (assets []stellar1.AccountAssetLocal, err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "GetAccountAssetsLocal",
Err: &err,
})
defer fin()
if err != nil {
return nil, err
}
mctx := libkb.NewMetaContext(ctx, s.G())
details, err := s.remoter.Details(ctx, arg.AccountID)
if err != nil {
s.G().Log.CDebugf(ctx, "remote.Details failed for %q: %s", arg.AccountID, err)
return nil, err
}
if len(details.Balances) == 0 {
// add an empty xlm balance
s.G().Log.CDebugf(ctx, "Account has no balances - adding default 0 XLM balance")
details.Balances = []stellar1.Balance{
stellar1.Balance{
Amount: "0",
Asset: stellar1.Asset{Type: "native"},
},
}
}
displayCurrency, err := stellar.GetAccountDisplayCurrency(mctx, arg.AccountID)
if err != nil {
return nil, err
}
s.G().Log.CDebugf(ctx, "Display currency for account %q is %q", arg.AccountID, displayCurrency)
rate, rateErr := s.remoter.ExchangeRate(ctx, displayCurrency)
if rateErr != nil {
s.G().Log.CDebugf(ctx, "exchange rate error: %s", rateErr)
}
for _, d := range details.Balances {
fmtAmount, err := stellar.FormatAmount(d.Amount, false)
if err != nil {
s.G().Log.CDebugf(ctx, "FormatAmount error: %s", err)
return nil, err
}
if d.Asset.IsNativeXLM() {
availableAmount := subtractFeeSoft(s.mctx(ctx), details.Available)
fmtAvailable, err := stellar.FormatAmount(availableAmount, false)
if err != nil {
return nil, err
}
asset := stellar1.AccountAssetLocal{
Name: "Lumens",
AssetCode: "XLM",
IssuerName: "Stellar network",
IssuerAccountID: "",
BalanceTotal: fmtAmount,
BalanceAvailableToSend: fmtAvailable,
WorthCurrency: displayCurrency,
}
fillWorths := func() (err error) {
if rateErr != nil {
return fmt.Errorf("rate error: %v", rateErr)
}
outsideAmount, err := stellarnet.ConvertXLMToOutside(d.Amount, rate.Rate)
if err != nil {
return fmt.Errorf("converting amount: %v", err)
}
fmtWorth, err := stellar.FormatCurrency(ctx, s.G(), outsideAmount, rate.Currency)
if err != nil {
return fmt.Errorf("formatting converted amount: %v", err)
}
asset.Worth = fmtWorth
outsideAvailableAmount, err := stellarnet.ConvertXLMToOutside(availableAmount, rate.Rate)
if err != nil {
return fmt.Errorf("converting available amount: %v", err)
}
fmtAvailableWorth, err := stellar.FormatCurrency(ctx, s.G(), outsideAvailableAmount, rate.Currency)
if err != nil {
return fmt.Errorf("formatting converted available amount: %v", err)
}
asset.AvailableToSendWorth = fmtAvailableWorth
return nil
}
err = fillWorths()
if err != nil {
s.G().Log.CDebugf(ctx, "error populating converted worth fields: %v", err)
asset.WorthCurrency = WorthCurrencyErrorCode
asset.Worth = "Currency conversion error"
asset.AvailableToSendWorth = "Currency conversion error"
}
// Add account reserves info to main asset.
asset.Reserves = details.Reserves
assets = append(assets, asset)
} else {
assets = append(assets, stellar1.AccountAssetLocal{
Name: d.Asset.Code,
AssetCode: d.Asset.Code,
IssuerName: "", // TODO get verified asset names
IssuerAccountID: d.Asset.Issuer,
BalanceTotal: fmtAmount,
BalanceAvailableToSend: fmtAmount,
WorthCurrency: "",
Worth: "",
AvailableToSendWorth: "",
})
}
}
return assets, nil
}
func (s *Server) GetDisplayCurrenciesLocal(ctx context.Context, sessionID int) (currencies []stellar1.CurrencyLocal, err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "GetDisplayCurrenciesLocal",
Err: &err,
})
defer fin()
if err != nil {
return nil, err
}
conf, err := s.G().GetStellar().GetServerDefinitions(ctx)
if err != nil {
return nil, err
}
for code := range conf.Currencies {
c, ok := conf.GetCurrencyLocal(code)
if ok {
currencies = append(currencies, c)
}
}
sort.Slice(currencies, func(i, j int) bool {
if currencies[i].Code == "USD" {
return true
}
if currencies[j].Code == "USD" {
return false
}
return currencies[i].Code < currencies[j].Code
})
return currencies, nil
}
func (s *Server) GetWalletSettingsLocal(ctx context.Context, sessionID int) (ret stellar1.WalletSettings, err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "GetWalletSettingsLocal",
Err: &err,
})
defer fin()
if err != nil {
return ret, err
}
ret.AcceptedDisclaimer, err = remote.GetAcceptedDisclaimer(ctx, s.G())
if err != nil {
return ret, err
}
return ret, nil
}
func (s *Server) SetAcceptedDisclaimerLocal(ctx context.Context, sessionID int) (err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "SetAcceptedDisclaimerLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return err
}
return remote.SetAcceptedDisclaimer(ctx, s.G())
}
func (s *Server) LinkNewWalletAccountLocal(ctx context.Context, arg stellar1.LinkNewWalletAccountLocalArg) (accountID stellar1.AccountID, err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "LinkNewWalletAccountLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return "", err
}
_, accountID, _, err = libkb.ParseStellarSecretKey(string(arg.SecretKey))
if err != nil {
return "", err
}
err = stellar.ImportSecretKey(ctx, s.G(), arg.SecretKey, false, arg.Name)
if err != nil {
return "", err
}
return accountID, nil
}
func (s *Server) GetPaymentsLocal(ctx context.Context, arg stellar1.GetPaymentsLocalArg) (page stellar1.PaymentsPageLocal, err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "GetPaymentsLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return page, err
}
oc := stellar.NewOwnAccountLookupCache(ctx, s.G())
srvPayments, err := s.remoter.RecentPayments(ctx, arg.AccountID, arg.Cursor, 0, true)
if err != nil {
return page, err
}
mctx := libkb.NewMetaContext(ctx, s.G())
exchRate := s.accountExchangeRate(mctx, arg.AccountID)
page.Payments = make([]stellar1.PaymentOrErrorLocal, len(srvPayments.Payments))
for i, p := range srvPayments.Payments {
page.Payments[i].Payment, err = stellar.TransformPaymentSummaryAccount(mctx, p, oc, arg.AccountID, exchRate)
if err != nil {
s := err.Error()
page.Payments[i].Err = &s
page.Payments[i].Payment = nil // just to make sure
}
}
page.Cursor = srvPayments.Cursor
if srvPayments.OldestUnread != nil {
page.OldestUnread = &stellar1.PaymentID{TxID: *srvPayments.OldestUnread}
}
return page, nil
}
func (s *Server) GetPendingPaymentsLocal(ctx context.Context, arg stellar1.GetPendingPaymentsLocalArg) (payments []stellar1.PaymentOrErrorLocal, err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "GetPendingPaymentsLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return nil, err
}
oc := stellar.NewOwnAccountLookupCache(ctx, s.G())
pending, err := s.remoter.PendingPayments(ctx, arg.AccountID, 0)
if err != nil {
return nil, err
}
mctx := libkb.NewMetaContext(ctx, s.G())
exchRate := s.accountExchangeRate(mctx, arg.AccountID)
payments = make([]stellar1.PaymentOrErrorLocal, len(pending))
for i, p := range pending {
payment, err := stellar.TransformPaymentSummaryAccount(mctx, p, oc, arg.AccountID, exchRate)
if err != nil {
s := err.Error()
payments[i].Err = &s
payments[i].Payment = nil // just to make sure
} else {
payments[i].Payment = payment
payments[i].Err = nil
}
}
return payments, nil
}
func (s *Server) GetPaymentDetailsLocal(ctx context.Context, arg stellar1.GetPaymentDetailsLocalArg) (payment stellar1.PaymentDetailsLocal, err error) {
ctx = s.logTag(ctx)
defer s.G().CTraceTimed(ctx, "GetPaymentDetailsLocal", func() error { return err })()
err = s.assertLoggedIn(ctx)
if err != nil {
return payment, err
}
oc := stellar.NewOwnAccountLookupCache(ctx, s.G())
details, err := s.remoter.PaymentDetails(ctx, arg.Id.TxID.String())
if err != nil {
return payment, err
}
mctx := libkb.NewMetaContext(ctx, s.G())
var summary *stellar1.PaymentLocal
// AccountID argument is optional.
if arg.AccountID != nil {
exchRate := s.accountExchangeRate(mctx, *arg.AccountID)
summary, err = stellar.TransformPaymentSummaryAccount(mctx, details.Summary, oc, *arg.AccountID, exchRate)
} else {
summary, err = stellar.TransformPaymentSummaryGeneric(mctx, details.Summary, oc)
}
if err != nil {
return payment, err
}
payment = stellar1.PaymentDetailsLocal{
Id: summary.Id,
TxID: summary.Id.TxID,
Time: summary.Time,
StatusSimplified: summary.StatusSimplified,
StatusDescription: summary.StatusDescription,
StatusDetail: summary.StatusDetail,
AmountDescription: summary.AmountDescription,
Delta: summary.Delta,
Worth: summary.Worth,
WorthCurrency: summary.WorthCurrency,
FromType: summary.FromType,
ToType: summary.ToType,
FromAccountID: summary.FromAccountID,
FromAccountName: summary.FromAccountName,
FromUsername: summary.FromUsername,
ToAccountID: summary.ToAccountID,
ToAccountName: summary.ToAccountName,
ToUsername: summary.ToUsername,
ToAssertion: summary.ToAssertion,
Note: summary.Note,
NoteErr: summary.NoteErr,
PublicNote: details.Memo,
PublicNoteType: details.MemoType,
CurrentWorth: summary.CurrentWorth,
CurrentWorthCurrency: summary.CurrentWorthCurrency,
}
return payment, nil
}
type balanceList []stellar1.Balance
// Example: "56.0227002 XLM + more"
func (a balanceList) balanceDescription() (res string, err error) {
var more bool
for _, b := range a {
if b.Asset.IsNativeXLM() {
res, err = stellar.FormatAmountXLM(b.Amount)
if err != nil {
return "", err
}
} else {
more = true
}
}
if res == "" {
res = "0 XLM"
}
if more {
res += " + more"
}
return res, nil
}
func (s *Server) ValidateAccountIDLocal(ctx context.Context, arg stellar1.ValidateAccountIDLocalArg) (err error) {
_, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "ValidateAccountIDLocal",
Err: &err,
})
defer fin()
if err != nil {
return err
}
_, err = libkb.ParseStellarAccountID(arg.AccountID.String())
return err
}
func (s *Server) ValidateSecretKeyLocal(ctx context.Context, arg stellar1.ValidateSecretKeyLocalArg) (err error) {
_, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "ValidateSecretKeyLocal",
Err: &err,
})
defer fin()
if err != nil {
return err
}
_, _, _, err = libkb.ParseStellarSecretKey(arg.SecretKey.SecureNoLogString())
return err
}
func (s *Server) ValidateAccountNameLocal(ctx context.Context, arg stellar1.ValidateAccountNameLocalArg) (err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "ValidateAccountNameLocal",
Err: &err,
})
defer fin()
if err != nil {
return err
}
// Make sure to keep this validation in sync with ChangeAccountName.
if arg.Name == "" {
return fmt.Errorf("name required")
}
runes := utf8.RuneCountInString(arg.Name)
if runes > stellar.AccountNameMaxRunes {
return fmt.Errorf("account name can be %v characters at the longest but was %v", stellar.AccountNameMaxRunes, runes)
}
// If this becomes a bottleneck, cache non-critical wallet info on G.Stellar.
currentBundle, _, err := remote.Fetch(ctx, s.G())
if err != nil {
s.G().Log.CErrorf(ctx, "error fetching bundle: %v", err)
// Return nil since the name is probably fine.
return nil
}
for _, account := range currentBundle.Accounts {
if arg.Name == account.Name {
return fmt.Errorf("you already have an account with that name")
}
}
return nil
}
func (s *Server) ChangeWalletAccountNameLocal(ctx context.Context, arg stellar1.ChangeWalletAccountNameLocalArg) (err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "ChangeWalletAccountNameLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return err
}
return stellar.ChangeAccountName(s.mctx(ctx), arg.AccountID, arg.NewName)
}
func (s *Server) SetWalletAccountAsDefaultLocal(ctx context.Context, arg stellar1.SetWalletAccountAsDefaultLocalArg) (err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "SetWalletAccountAsDefaultLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return err
}
return stellar.SetAccountAsPrimary(s.mctx(ctx), arg.AccountID)
}
func (s *Server) DeleteWalletAccountLocal(ctx context.Context, arg stellar1.DeleteWalletAccountLocalArg) (err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "DeleteWalletAccountLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return err
}
if arg.UserAcknowledged != "yes" {
return errors.New("User did not acknowledge")
}
return stellar.DeleteAccount(s.mctx(ctx), arg.AccountID)
}
func (s *Server) ChangeDisplayCurrencyLocal(ctx context.Context, arg stellar1.ChangeDisplayCurrencyLocalArg) (err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "ChangeDisplayCurrencyLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return err
}
if arg.AccountID.IsNil() {
return errors.New("passed empty AccountID")
}
conf, err := s.G().GetStellar().GetServerDefinitions(ctx)
if err != nil {
return err
}
if _, ok := conf.Currencies[arg.Currency]; !ok {
return fmt.Errorf("Unknown currency code: %q", arg.Currency)
}
return remote.SetAccountDefaultCurrency(ctx, s.G(), arg.AccountID, string(arg.Currency))
}
func (s *Server) GetDisplayCurrencyLocal(ctx context.Context, arg stellar1.GetDisplayCurrencyLocalArg) (res stellar1.CurrencyLocal, err error) {
defer s.G().CTraceTimed(ctx, "GetDisplayCurrencyLocal", func() error { return err })()
if err = s.assertLoggedIn(ctx); err != nil {
return res, err
}
if arg.AccountID.IsNil() {
return res, errors.New("passed empty AccountID")
}
return stellar.GetCurrencySetting(s.mctx(ctx), s.remoter, arg.AccountID)
}
func (s *Server) GetWalletAccountPublicKeyLocal(ctx context.Context, arg stellar1.GetWalletAccountPublicKeyLocalArg) (res string, err error) {
_, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "GetWalletAccountPublicKeyLocal",
Err: &err,
AllowLoggedOut: true,
})
defer fin()
if err != nil {
return res, err
}
if arg.AccountID.IsNil() {
return res, errors.New("passed empty AccountID")
}
return arg.AccountID.String(), nil
}
func (s *Server) GetWalletAccountSecretKeyLocal(ctx context.Context, arg stellar1.GetWalletAccountSecretKeyLocalArg) (res stellar1.SecretKey, err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "GetWalletAccountSecretKeyLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return res, err
}
if arg.AccountID.IsNil() {
return res, errors.New("passed empty AccountID")
}
return stellar.ExportSecretKey(ctx, s.G(), arg.AccountID)
}
func (s *Server) GetSendAssetChoicesLocal(ctx context.Context, arg stellar1.GetSendAssetChoicesLocalArg) (res []stellar1.SendAssetChoiceLocal, err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "GetSendAssetChoicesLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return res, err
}
owns, err := stellar.OwnAccount(ctx, s.G(), arg.From)
if err != nil {
return res, err
}
if !owns {
return res, fmt.Errorf("account %s is not owned by current user", arg.From)
}
ourBalances, err := s.remoter.Balances(ctx, arg.From)
if err != nil {
return res, err
}
res = []stellar1.SendAssetChoiceLocal{}
for _, bal := range ourBalances {
asset := bal.Asset
if asset.IsNativeXLM() {
// We are only doing non-native assets here.
continue
}
choice := stellar1.SendAssetChoiceLocal{
Asset: asset,
Enabled: true,
Left: bal.Asset.Code,
Right: bal.Asset.Issuer,
}
res = append(res, choice)
}
if arg.To != "" {
mctx := s.mctx(ctx)
recipient, err := stellar.LookupRecipient(mctx, stellarcommon.RecipientInput(arg.To), false)
if err != nil {
s.G().Log.CDebugf(ctx, "Skipping asset filtering: stellar.LookupRecipient for %q failed with: %s",
arg.To, err)
return res, nil
}
theirBalancesHash := make(map[string]bool)
assetHashCode := func(a stellar1.Asset) string {
return fmt.Sprintf("%s%s%s", a.Type, a.Code, a.Issuer)
}
if recipient.AccountID != nil {
theirBalances, err := s.remoter.Balances(ctx, stellar1.AccountID(recipient.AccountID.String()))
if err != nil {
s.G().Log.CDebugf(ctx, "Skipping asset filtering: remoter.Balances for %q failed with: %s",
recipient.AccountID, err)
return res, nil
}
for _, bal := range theirBalances {
theirBalancesHash[assetHashCode(bal.Asset)] = true
}
}
for i, choice := range res {
available := theirBalancesHash[assetHashCode(choice.Asset)]
if !available {
choice.Enabled = false
recipientStr := "Recipient"
if recipient.User != nil {
recipientStr = recipient.User.Username.String()
}
choice.Subtext = fmt.Sprintf("%s does not accept %s", recipientStr, choice.Asset.Code)
res[i] = choice
}
}
}
return res, nil
}
func (s *Server) BuildPaymentLocal(ctx context.Context, arg stellar1.BuildPaymentLocalArg) (res stellar1.BuildPaymentResLocal, err error) {
ctx, err, fin := s.Preamble(ctx, preambleArg{
RPCName: "BuildPaymentLocal",
Err: &err,
RequireWallet: true,
})
defer fin()
if err != nil {
return res, err
}
tracer := s.G().CTimeTracer(ctx, "BuildPaymentLocal", true)
defer tracer.Finish()
readyChecklist := struct {
from bool
to bool
amount bool
secretNote bool
publicMemo bool
}{}
log := func(format string, args ...interface{}) {
s.G().Log.CDebugf(ctx, "bpl: "+format, args...)
}
bpc := stellar.GetBuildPaymentCache(s.mctx(ctx), s.remoter)
if bpc == nil {
return res, fmt.Errorf("missing build payment cache")
}
// -------------------- from --------------------
tracer.Stage("from")
fromInfo := struct {
available bool
from stellar1.AccountID
}{}
if arg.FromPrimaryAccount != arg.From.IsNil() {
// Exactly one of `from` and `fromPrimaryAccount` must be set.
return res, fmt.Errorf("invalid build payment parameters")
}
if arg.FromPrimaryAccount {
primaryAccountID, err := bpc.PrimaryAccount(s.mctx(ctx))
if err != nil {
log("PrimaryAccount -> err:%v", err)
res.Banners = append(res.Banners, stellar1.SendBannerLocal{
Level: "error",
Message: "Could not find primary account.",
})
} else {
fromInfo.from = primaryAccountID
fromInfo.available = true
}
} else {
owns, err := bpc.OwnsAccount(s.mctx(ctx), arg.From)
if err != nil || !owns {
log("OwnsAccount -> owns:%v err:%v", owns, err)
res.Banners = append(res.Banners, stellar1.SendBannerLocal{
Level: "error",
Message: "Could not find source account.",
})
} else {
fromInfo.from = arg.From
fromInfo.available = true
}
}
if fromInfo.available {
res.From = fromInfo.from
if arg.FromSeqno == "" {
readyChecklist.from = true
} else {
// Check that the seqno of the account matches the caller's expectation.
seqno, err := bpc.AccountSeqno(s.mctx(ctx), arg.From)
switch {
case err != nil:
log("AccountSeqno -> err:%v", err)
res.Banners = append(res.Banners, stellar1.SendBannerLocal{
Level: "error",
Message: "Could not get seqno for source account.",
})
case seqno != arg.FromSeqno:
log("AccountSeqno -> got:%v != want:%v", seqno, arg.FromSeqno)
res.Banners = append(res.Banners, stellar1.SendBannerLocal{
Level: "error",
Message: "Activity on account since initiating send. Take another look at account history.",
})
default:
readyChecklist.from = true
fromInfo.from = arg.From
fromInfo.available = true
}
}
}
// -------------------- to --------------------
tracer.Stage("to")
skipRecipient := len(arg.To) == 0
var minAmountXLM string
if !skipRecipient && arg.ToIsAccountID {
_, err := libkb.ParseStellarAccountID(arg.To)
if err != nil {
res.ToErrMsg = err.Error()
skipRecipient = true
} else {
readyChecklist.to = true
}
}
if !skipRecipient {
recipient, err := bpc.LookupRecipient(s.mctx(ctx), stellarcommon.RecipientInput(arg.To))
if err != nil {
log("error with recipient field %v: %v", arg.To, err)
res.ToErrMsg = "recipient not found"
skipRecipient = true
} else {
readyChecklist.to = true
addMinBanner := func(them, amount string) {
res.Banners = append(res.Banners, stellar1.SendBannerLocal{
Level: "info",
Message: fmt.Sprintf("Because it's %s first transaction, you must send at least %s XLM.", them, amount),
})
}
bannerThem := "their"
if recipient.User != nil {
res.ToUsername = recipient.User.Username.String()
bannerThem = fmt.Sprintf("%s's", recipient.User.Username)
}
if recipient.AccountID == nil {
// Sending a payment to a target with no account. (relay)
minAmountXLM = "2.01"
addMinBanner(bannerThem, minAmountXLM)
} else {
isFunded, err := bpc.IsAccountFunded(s.mctx(ctx), stellar1.AccountID(recipient.AccountID.String()))
if err != nil {
log("error checking recipient funding status %v: %v", *recipient.AccountID, err)
} else if !isFunded {
// Sending to a non-funded stellar account.
minAmountXLM = "1"
addMinBanner(bannerThem, minAmountXLM)
}
}
}
}
// -------------------- amount + asset --------------------
tracer.Stage("amount + asset")
bpaArg := buildPaymentAmountArg{
Amount: arg.Amount,
Currency: arg.Currency,
Asset: arg.Asset,
}
if fromInfo.available {
bpaArg.From = &fromInfo.from
}
amountX := s.buildPaymentAmountHelper(ctx, bpc, bpaArg)
res.AmountErrMsg = amountX.amountErrMsg
res.WorthDescription = amountX.worthDescription
res.WorthInfo = amountX.worthInfo
if amountX.haveAmount {
if !amountX.asset.IsNativeXLM() {
return res, fmt.Errorf("sending non-XLM assets is not supported")
}
readyChecklist.amount = true
if fromInfo.available {
// Check that the sender has enough asset available.
// Note: When adding support for sending non-XLM assets, check the asset instead of XLM here.
availableToSendXLM, err := bpc.AvailableXLMToSend(s.mctx(ctx), fromInfo.from)
availableToSendXLM = subtractFeeSoft(s.mctx(ctx), availableToSendXLM)
if err != nil {
log("error getting available balance: %v", err)
} else {
cmp, err := stellarnet.CompareStellarAmounts(availableToSendXLM, amountX.amountOfAsset)
switch {
case err != nil:
log("error comparing amounts", err)
case cmp == -1:
// Send amount is more than the available to send.
readyChecklist.amount = false // block sending
res.AmountErrMsg = fmt.Sprintf("Your available to send is *%s XLM*", availableToSendXLM)
availableToSendXLMFmt, err := stellar.FormatAmount(availableToSendXLM, false)
if err == nil {
res.AmountErrMsg = fmt.Sprintf("Your available to send is *%s XLM*", availableToSendXLMFmt)
}
if arg.Currency != nil && amountX.rate != nil {
// If the user entered an amount in outside currency and an exchange
// rate is available, attempt to show them available balance in that currency.
availableToSendOutside, err := stellarnet.ConvertXLMToOutside(availableToSendXLM, amountX.rate.Rate)
if err != nil {
log("error converting available-to-send", err)
} else {
formattedATS, err := stellar.FormatCurrency(ctx, s.G(), availableToSendOutside, amountX.rate.Currency)
if err != nil {
log("error formatting available-to-send", err)
} else {
res.AmountErrMsg = fmt.Sprintf("Your available to send is *%s*", formattedATS)
}
}
}
default:
// Welcome back. How was your stay at the error handling hotel?
}
}
}
if minAmountXLM != "" {
cmp, err := stellarnet.CompareStellarAmounts(amountX.amountOfAsset, minAmountXLM)
switch {
case err != nil:
log("error comparing amounts", err)
case cmp == -1:
// amount is less than minAmountXLM
readyChecklist.amount = false // block sending
res.AmountErrMsg = fmt.Sprintf("You must send at least *%s* XLM", minAmountXLM)
}
}
// Note: When adding support for sending non-XLM assets, check here that the recipient accepts the asset.
}
// -------------------- note + memo --------------------
tracer.Stage("note + memo")
if len(arg.SecretNote) <= 500 {
readyChecklist.secretNote = true
} else {
res.SecretNoteErrMsg = "Note is too long."
}
if len(arg.PublicMemo) <= 28 {
readyChecklist.publicMemo = true
} else {
res.PublicMemoErrMsg = "Memo is too long."
}
// -------------------- end --------------------
if readyChecklist.from && readyChecklist.to && readyChecklist.amount && readyChecklist.secretNote && readyChecklist.publicMemo {
res.ReadyToSend = true
}
return res, nil
}
type buildPaymentAmountArg struct {
// See buildPaymentLocal in avdl from which these args are copied.
Amount string
Currency *stellar1.OutsideCurrencyCode
Asset *stellar1.Asset
From *stellar1.AccountID
}
type buildPaymentAmountResult struct {
haveAmount bool // whether `amountOfAsset` and `asset` are valid
amountOfAsset string
asset stellar1.Asset
amountErrMsg string
worthDescription string
worthInfo string
// Rate may be nil if there was an error fetching it.
rate *stellar1.OutsideExchangeRate
}
func (s *Server) buildPaymentAmountHelper(ctx context.Context, bpc stellar.BuildPaymentCache, arg buildPaymentAmountArg) (res buildPaymentAmountResult) {
log := func(format string, args ...interface{}) {
s.G().Log.CDebugf(ctx, "bpl: "+format, args...)
}
res.asset = stellar1.AssetNative()
switch {