forked from bisq-network/bisq
/
MutableOfferViewModel.java
1209 lines (1044 loc) · 53.7 KB
/
MutableOfferViewModel.java
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 part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.desktop.main.offer;
import bisq.desktop.Navigation;
import bisq.desktop.common.model.ActivatableWithDataModel;
import bisq.desktop.main.MainView;
import bisq.desktop.main.funds.FundsView;
import bisq.desktop.main.funds.deposit.DepositView;
import bisq.desktop.main.overlays.popups.Popup;
import bisq.desktop.main.settings.SettingsView;
import bisq.desktop.main.settings.preferences.PreferencesView;
import bisq.desktop.util.GUIUtil;
import bisq.desktop.util.validation.AltcoinValidator;
import bisq.desktop.util.validation.BsqValidator;
import bisq.desktop.util.validation.BtcValidator;
import bisq.desktop.util.validation.FiatPriceValidator;
import bisq.desktop.util.validation.FiatVolumeValidator;
import bisq.desktop.util.validation.MonetaryValidator;
import bisq.desktop.util.validation.SecurityDepositValidator;
import bisq.core.btc.setup.WalletsSetup;
import bisq.core.btc.wallet.Restrictions;
import bisq.core.locale.CurrencyUtil;
import bisq.core.locale.Res;
import bisq.core.locale.TradeCurrency;
import bisq.core.monetary.Altcoin;
import bisq.core.monetary.Price;
import bisq.core.monetary.Volume;
import bisq.core.offer.Offer;
import bisq.core.offer.OfferPayload;
import bisq.core.offer.OfferRestrictions;
import bisq.core.offer.OfferUtil;
import bisq.core.payment.PaymentAccount;
import bisq.core.provider.price.MarketPrice;
import bisq.core.provider.price.PriceFeedService;
import bisq.core.user.Preferences;
import bisq.core.util.BSFormatter;
import bisq.core.util.BsqFormatter;
import bisq.core.util.validation.InputValidator;
import bisq.network.p2p.P2PService;
import bisq.common.Timer;
import bisq.common.UserThread;
import bisq.common.app.DevEnv;
import bisq.common.util.MathUtils;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.Coin;
import org.bitcoinj.utils.Fiat;
import javax.inject.Inject;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import static javafx.beans.binding.Bindings.createStringBinding;
public abstract class MutableOfferViewModel<M extends MutableOfferDataModel> extends ActivatableWithDataModel<M> {
private final BtcValidator btcValidator;
private final BsqValidator bsqValidator;
protected final SecurityDepositValidator securityDepositValidator;
private final P2PService p2PService;
private final WalletsSetup walletsSetup;
private final PriceFeedService priceFeedService;
private final Navigation navigation;
private final Preferences preferences;
protected final BSFormatter btcFormatter;
private final BsqFormatter bsqFormatter;
private final FiatVolumeValidator fiatVolumeValidator;
private final FiatPriceValidator fiatPriceValidator;
private final AltcoinValidator altcoinValidator;
private String amountDescription;
private String directionLabel;
private String addressAsString;
private final String paymentLabel;
private boolean createOfferRequested;
public final StringProperty amount = new SimpleStringProperty();
public final StringProperty minAmount = new SimpleStringProperty();
protected final StringProperty buyerSecurityDeposit = new SimpleStringProperty();
final StringProperty buyerSecurityDepositInBTC = new SimpleStringProperty();
final StringProperty buyerSecurityDepositLabel = new SimpleStringProperty();
// Price in the viewModel is always dependent on fiat/altcoin: Fiat Fiat/BTC, for altcoins we use inverted price.
// The domain (dataModel) uses always the same price model (otherCurrencyBTC)
// If we would change the price representation in the domain we would not be backward compatible
public final StringProperty price = new SimpleStringProperty();
final StringProperty tradeFee = new SimpleStringProperty();
final StringProperty tradeFeeInBtcWithFiat = new SimpleStringProperty();
final StringProperty tradeFeeInBsqWithFiat = new SimpleStringProperty();
final StringProperty tradeFeeCurrencyCode = new SimpleStringProperty();
final StringProperty tradeFeeDescription = new SimpleStringProperty();
final BooleanProperty isTradeFeeVisible = new SimpleBooleanProperty(false);
// Positive % value means always a better price form the maker's perspective:
// Buyer (with fiat): lower price as market
// Buyer (with altcoin): higher (display) price as market (display price is inverted)
public final StringProperty marketPriceMargin = new SimpleStringProperty();
public final StringProperty volume = new SimpleStringProperty();
final StringProperty volumeDescriptionLabel = new SimpleStringProperty();
final StringProperty volumePromptLabel = new SimpleStringProperty();
final StringProperty tradeAmount = new SimpleStringProperty();
final StringProperty totalToPay = new SimpleStringProperty();
final StringProperty errorMessage = new SimpleStringProperty();
final StringProperty tradeCurrencyCode = new SimpleStringProperty();
final StringProperty waitingForFundsText = new SimpleStringProperty("");
final BooleanProperty isPlaceOfferButtonDisabled = new SimpleBooleanProperty(true);
final BooleanProperty cancelButtonDisabled = new SimpleBooleanProperty();
public final BooleanProperty isNextButtonDisabled = new SimpleBooleanProperty(true);
final BooleanProperty placeOfferCompleted = new SimpleBooleanProperty();
final BooleanProperty showPayFundsScreenDisplayed = new SimpleBooleanProperty();
private final BooleanProperty showTransactionPublishedScreen = new SimpleBooleanProperty();
final BooleanProperty isWaitingForFunds = new SimpleBooleanProperty();
final ObjectProperty<InputValidator.ValidationResult> amountValidationResult = new SimpleObjectProperty<>();
final ObjectProperty<InputValidator.ValidationResult> minAmountValidationResult = new SimpleObjectProperty<>();
final ObjectProperty<InputValidator.ValidationResult> priceValidationResult = new SimpleObjectProperty<>();
final ObjectProperty<InputValidator.ValidationResult> volumeValidationResult = new SimpleObjectProperty<>();
final ObjectProperty<InputValidator.ValidationResult> buyerSecurityDepositValidationResult = new SimpleObjectProperty<>();
// Those are needed for the addressTextField
private final ObjectProperty<Address> address = new SimpleObjectProperty<>();
private ChangeListener<String> amountStringListener;
private ChangeListener<String> minAmountStringListener;
private ChangeListener<String> priceStringListener, marketPriceMarginStringListener;
private ChangeListener<String> volumeStringListener;
private ChangeListener<String> securityDepositStringListener;
private ChangeListener<Coin> amountAsCoinListener;
private ChangeListener<Coin> minAmountAsCoinListener;
private ChangeListener<Price> priceListener;
private ChangeListener<Volume> volumeListener;
private ChangeListener<Number> securityDepositAsDoubleListener;
private ChangeListener<Boolean> isWalletFundedListener;
//private ChangeListener<Coin> feeFromFundingTxListener;
private ChangeListener<String> errorMessageListener;
private Offer offer;
private Timer timeoutTimer;
private boolean inputIsMarketBasedPrice;
private ChangeListener<Boolean> useMarketBasedPriceListener;
private boolean ignorePriceStringListener, ignoreVolumeStringListener, ignoreAmountStringListener, ignoreSecurityDepositStringListener;
private MarketPrice marketPrice;
final IntegerProperty marketPriceAvailableProperty = new SimpleIntegerProperty(-1);
private ChangeListener<Number> currenciesUpdateListener;
protected boolean syncMinAmountWithAmount = true;
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor, lifecycle
///////////////////////////////////////////////////////////////////////////////////////////
@Inject
public MutableOfferViewModel(M dataModel,
FiatVolumeValidator fiatVolumeValidator,
FiatPriceValidator fiatPriceValidator,
AltcoinValidator altcoinValidator,
BtcValidator btcValidator,
BsqValidator bsqValidator,
SecurityDepositValidator securityDepositValidator,
P2PService p2PService,
WalletsSetup walletsSetup,
PriceFeedService priceFeedService,
Navigation navigation,
Preferences preferences,
BSFormatter btcFormatter,
BsqFormatter bsqFormatter) {
super(dataModel);
this.fiatVolumeValidator = fiatVolumeValidator;
this.fiatPriceValidator = fiatPriceValidator;
this.altcoinValidator = altcoinValidator;
this.btcValidator = btcValidator;
this.bsqValidator = bsqValidator;
this.securityDepositValidator = securityDepositValidator;
this.p2PService = p2PService;
this.walletsSetup = walletsSetup;
this.priceFeedService = priceFeedService;
this.navigation = navigation;
this.preferences = preferences;
this.btcFormatter = btcFormatter;
this.bsqFormatter = bsqFormatter;
paymentLabel = Res.get("createOffer.fundsBox.paymentLabel", dataModel.shortOfferId);
if (dataModel.getAddressEntry() != null) {
addressAsString = dataModel.getAddressEntry().getAddressString();
address.set(dataModel.getAddressEntry().getAddress());
}
createListeners();
}
@Override
public void activate() {
if (DevEnv.isDevMode()) {
UserThread.runAfter(() -> {
amount.set("1");
price.set("0.03");
minAmount.set(amount.get());
onFocusOutPriceAsPercentageTextField(true, false);
applyMakerFee();
setAmountToModel();
setMinAmountToModel();
setPriceToModel();
dataModel.calculateVolume();
dataModel.calculateTotalToPay();
updateButtonDisableState();
updateSpinnerInfo();
}, 100, TimeUnit.MILLISECONDS);
}
addBindings();
addListeners();
updateButtonDisableState();
updateMarketPriceAvailable();
}
@Override
protected void deactivate() {
removeBindings();
removeListeners();
stopTimeoutTimer();
}
private void addBindings() {
if (dataModel.getDirection() == OfferPayload.Direction.BUY) {
volumeDescriptionLabel.bind(createStringBinding(
() -> Res.get("createOffer.amountPriceBox.buy.volumeDescription", dataModel.getTradeCurrencyCode().get()),
dataModel.getTradeCurrencyCode()));
} else {
volumeDescriptionLabel.bind(createStringBinding(
() -> Res.get("createOffer.amountPriceBox.sell.volumeDescription", dataModel.getTradeCurrencyCode().get()),
dataModel.getTradeCurrencyCode()));
}
volumePromptLabel.bind(createStringBinding(
() -> Res.get("createOffer.volume.prompt", dataModel.getTradeCurrencyCode().get()),
dataModel.getTradeCurrencyCode()));
totalToPay.bind(createStringBinding(() -> btcFormatter.formatCoinWithCode(dataModel.totalToPayAsCoinProperty().get()),
dataModel.totalToPayAsCoinProperty()));
tradeAmount.bind(createStringBinding(() -> btcFormatter.formatCoinWithCode(dataModel.getAmount().get()),
dataModel.getAmount()));
tradeCurrencyCode.bind(dataModel.getTradeCurrencyCode());
}
private void removeBindings() {
totalToPay.unbind();
tradeAmount.unbind();
tradeCurrencyCode.unbind();
volumeDescriptionLabel.unbind();
volumePromptLabel.unbind();
}
private void createListeners() {
amountStringListener = (ov, oldValue, newValue) -> {
if (!ignoreAmountStringListener) {
if (isBtcInputValid(newValue).isValid) {
setAmountToModel();
dataModel.calculateVolume();
dataModel.calculateTotalToPay();
}
updateButtonDisableState();
}
};
minAmountStringListener = (ov, oldValue, newValue) -> {
if (isBtcInputValid(newValue).isValid)
setMinAmountToModel();
updateButtonDisableState();
};
priceStringListener = (ov, oldValue, newValue) -> {
updateMarketPriceAvailable();
final String currencyCode = dataModel.getTradeCurrencyCode().get();
if (!ignorePriceStringListener) {
if (isPriceInputValid(newValue).isValid) {
setPriceToModel();
dataModel.calculateVolume();
dataModel.calculateTotalToPay();
if (!inputIsMarketBasedPrice) {
if (marketPrice != null && marketPrice.isRecentExternalPriceAvailable()) {
double marketPriceAsDouble = marketPrice.getPrice();
try {
double priceAsDouble = btcFormatter.parseNumberStringToDouble(price.get());
double relation = priceAsDouble / marketPriceAsDouble;
final OfferPayload.Direction compareDirection = CurrencyUtil.isCryptoCurrency(currencyCode) ?
OfferPayload.Direction.SELL :
OfferPayload.Direction.BUY;
double percentage = dataModel.getDirection() == compareDirection ? 1 - relation : relation - 1;
percentage = MathUtils.roundDouble(percentage, 4);
dataModel.setMarketPriceMargin(percentage);
marketPriceMargin.set(btcFormatter.formatToPercent(percentage));
applyMakerFee();
} catch (NumberFormatException t) {
marketPriceMargin.set("");
new Popup<>().warning(Res.get("validation.NaN")).show();
}
} else {
log.debug("We don't have a market price. We use the static price instead.");
}
}
}
}
updateButtonDisableState();
};
marketPriceMarginStringListener = (ov, oldValue, newValue) -> {
if (inputIsMarketBasedPrice) {
try {
if (!newValue.isEmpty() && !newValue.equals("-")) {
double percentage = btcFormatter.parsePercentStringToDouble(newValue);
if (percentage >= 1 || percentage <= -1) {
new Popup<>().warning(Res.get("popup.warning.tooLargePercentageValue") + "\n" +
Res.get("popup.warning.examplePercentageValue"))
.show();
} else {
final String currencyCode = dataModel.getTradeCurrencyCode().get();
MarketPrice marketPrice = priceFeedService.getMarketPrice(currencyCode);
if (marketPrice != null && marketPrice.isRecentExternalPriceAvailable()) {
percentage = MathUtils.roundDouble(percentage, 4);
double marketPriceAsDouble = marketPrice.getPrice();
final boolean isCryptoCurrency = CurrencyUtil.isCryptoCurrency(currencyCode);
final OfferPayload.Direction compareDirection = isCryptoCurrency ?
OfferPayload.Direction.SELL :
OfferPayload.Direction.BUY;
double factor = dataModel.getDirection() == compareDirection ?
1 - percentage :
1 + percentage;
double targetPrice = marketPriceAsDouble * factor;
int precision = isCryptoCurrency ?
Altcoin.SMALLEST_UNIT_EXPONENT : Fiat.SMALLEST_UNIT_EXPONENT;
// protect from triggering unwanted updates
ignorePriceStringListener = true;
price.set(btcFormatter.formatRoundedDoubleWithPrecision(targetPrice, precision));
ignorePriceStringListener = false;
setPriceToModel();
dataModel.setMarketPriceMargin(percentage);
dataModel.calculateVolume();
dataModel.calculateTotalToPay();
updateButtonDisableState();
applyMakerFee();
} else {
marketPriceMargin.set("");
String id = "showNoPriceFeedAvailablePopup";
if (preferences.showAgain(id)) {
new Popup<>().warning(Res.get("popup.warning.noPriceFeedAvailable"))
.dontShowAgainId(id)
.show();
}
}
}
}
} catch (NumberFormatException t) {
log.error(t.toString());
t.printStackTrace();
new Popup<>().warning(Res.get("validation.NaN")).show();
} catch (Throwable t) {
log.error(t.toString());
t.printStackTrace();
new Popup<>().warning(Res.get("validation.inputError", t.toString())).show();
}
}
};
useMarketBasedPriceListener = (observable, oldValue, newValue) -> {
if (newValue)
priceValidationResult.set(new InputValidator.ValidationResult(true));
};
volumeStringListener = (ov, oldValue, newValue) -> {
if (!ignoreVolumeStringListener) {
if (isVolumeInputValid(newValue).isValid) {
setVolumeToModel();
setPriceToModel();
dataModel.calculateAmount();
dataModel.calculateTotalToPay();
}
updateButtonDisableState();
}
};
securityDepositStringListener = (ov, oldValue, newValue) -> {
if (!ignoreSecurityDepositStringListener) {
if (securityDepositValidator.validate(newValue).isValid) {
setBuyerSecurityDepositToModel();
dataModel.calculateTotalToPay();
}
updateButtonDisableState();
}
};
amountAsCoinListener = (ov, oldValue, newValue) -> {
if (newValue != null) {
amount.set(btcFormatter.formatCoin(newValue));
buyerSecurityDepositInBTC.set(btcFormatter.formatCoinWithCode(dataModel.getBuyerSecurityDepositAsCoin()));
} else {
amount.set("");
buyerSecurityDepositInBTC.set("");
}
applyMakerFee();
};
minAmountAsCoinListener = (ov, oldValue, newValue) -> {
if (newValue != null)
minAmount.set(btcFormatter.formatCoin(newValue));
else
minAmount.set("");
};
priceListener = (ov, oldValue, newValue) -> {
ignorePriceStringListener = true;
if (newValue != null)
price.set(btcFormatter.formatPrice(newValue));
else
price.set("");
ignorePriceStringListener = false;
applyMakerFee();
};
volumeListener = (ov, oldValue, newValue) -> {
ignoreVolumeStringListener = true;
if (newValue != null)
volume.set(btcFormatter.formatVolume(newValue));
else
volume.set("");
ignoreVolumeStringListener = false;
applyMakerFee();
};
securityDepositAsDoubleListener = (ov, oldValue, newValue) -> {
if (newValue != null) {
buyerSecurityDeposit.set(btcFormatter.formatToPercent((double) newValue));
if (dataModel.getAmount().get() != null)
buyerSecurityDepositInBTC.set(btcFormatter.formatCoinWithCode(dataModel.getBuyerSecurityDepositAsCoin()));
} else {
buyerSecurityDeposit.set("");
buyerSecurityDepositInBTC.set("");
}
};
isWalletFundedListener = (ov, oldValue, newValue) -> updateButtonDisableState();
/* feeFromFundingTxListener = (ov, oldValue, newValue) -> {
updateButtonDisableState();
};*/
currenciesUpdateListener = (observable, oldValue, newValue) -> {
updateMarketPriceAvailable();
updateButtonDisableState();
};
}
private void applyMakerFee() {
Coin makerFeeAsCoin = dataModel.getMakerFee();
if (makerFeeAsCoin != null) {
isTradeFeeVisible.setValue(true);
tradeFee.set(getFormatterForMakerFee().formatCoin(makerFeeAsCoin));
Coin makerFeeInBtc = dataModel.getMakerFeeInBtc();
Optional<Volume> optionalBtcFeeInFiat = OfferUtil.getFeeInUserFiatCurrency(makerFeeInBtc,
true, preferences, priceFeedService, bsqFormatter);
String btcFeeWithFiatAmount = OfferUtil.getFeeWithFiatAmount(makerFeeInBtc, optionalBtcFeeInFiat, btcFormatter);
if (DevEnv.isDaoActivated()) {
tradeFeeInBtcWithFiat.set(btcFeeWithFiatAmount);
} else {
tradeFeeInBtcWithFiat.set(btcFormatter.formatCoinWithCode(makerFeeAsCoin));
}
Coin makerFeeInBsq = dataModel.getMakerFeeInBsq();
Optional<Volume> optionalBsqFeeInFiat = OfferUtil.getFeeInUserFiatCurrency(makerFeeInBsq,
false, preferences, priceFeedService, bsqFormatter);
String bsqFeeWithFiatAmount = OfferUtil.getFeeWithFiatAmount(makerFeeInBsq, optionalBsqFeeInFiat, bsqFormatter);
if (DevEnv.isDaoActivated()) {
tradeFeeInBsqWithFiat.set(bsqFeeWithFiatAmount);
} else {
// Before DAO is enabled we show fee as fiat and % in second line
String feeInFiatAsString;
if (optionalBtcFeeInFiat != null && optionalBtcFeeInFiat.isPresent()) {
feeInFiatAsString = btcFormatter.formatVolumeWithCode(optionalBtcFeeInFiat.get());
} else {
feeInFiatAsString = Res.get("shared.na");
}
double amountAsLong = (double) dataModel.getAmount().get().value;
double makerFeeInBtcAsLong = (double) makerFeeInBtc.value;
double percent = makerFeeInBtcAsLong / amountAsLong;
tradeFeeInBsqWithFiat.set(Res.get("createOffer.tradeFee.fiatAndPercent",
feeInFiatAsString,
btcFormatter.formatToPercentWithSymbol(percent)));
}
}
tradeFeeCurrencyCode.set(dataModel.isCurrencyForMakerFeeBtc() ? Res.getBaseCurrencyCode() : "BSQ");
tradeFeeDescription.set(DevEnv.isDaoActivated() ? Res.get("createOffer.tradeFee.descriptionBSQEnabled") :
Res.get("createOffer.tradeFee.descriptionBTCOnly"));
}
private void updateMarketPriceAvailable() {
marketPrice = priceFeedService.getMarketPrice(dataModel.getTradeCurrencyCode().get());
marketPriceAvailableProperty.set(marketPrice == null || !marketPrice.isExternallyProvidedPrice() ? 0 : 1);
dataModel.setMarketPriceAvailable(marketPrice != null && marketPrice.isExternallyProvidedPrice());
}
private void addListeners() {
// Bidirectional bindings are used for all input fields: amount, price, volume and minAmount
// We do volume/amount calculation during input, so user has immediate feedback
amount.addListener(amountStringListener);
minAmount.addListener(minAmountStringListener);
price.addListener(priceStringListener);
marketPriceMargin.addListener(marketPriceMarginStringListener);
dataModel.getUseMarketBasedPrice().addListener(useMarketBasedPriceListener);
volume.addListener(volumeStringListener);
buyerSecurityDeposit.addListener(securityDepositStringListener);
// Binding with Bindings.createObjectBinding does not work because of bi-directional binding
dataModel.getAmount().addListener(amountAsCoinListener);
dataModel.getMinAmount().addListener(minAmountAsCoinListener);
dataModel.getPrice().addListener(priceListener);
dataModel.getVolume().addListener(volumeListener);
dataModel.getBuyerSecurityDeposit().addListener(securityDepositAsDoubleListener);
// dataModel.feeFromFundingTxProperty.addListener(feeFromFundingTxListener);
dataModel.getIsBtcWalletFunded().addListener(isWalletFundedListener);
priceFeedService.updateCounterProperty().addListener(currenciesUpdateListener);
}
private void removeListeners() {
amount.removeListener(amountStringListener);
minAmount.removeListener(minAmountStringListener);
price.removeListener(priceStringListener);
marketPriceMargin.removeListener(marketPriceMarginStringListener);
dataModel.getUseMarketBasedPrice().removeListener(useMarketBasedPriceListener);
volume.removeListener(volumeStringListener);
buyerSecurityDeposit.removeListener(securityDepositStringListener);
// Binding with Bindings.createObjectBinding does not work because of bi-directional binding
dataModel.getAmount().removeListener(amountAsCoinListener);
dataModel.getMinAmount().removeListener(minAmountAsCoinListener);
dataModel.getPrice().removeListener(priceListener);
dataModel.getVolume().removeListener(volumeListener);
dataModel.getBuyerSecurityDeposit().removeListener(securityDepositAsDoubleListener);
//dataModel.feeFromFundingTxProperty.removeListener(feeFromFundingTxListener);
dataModel.getIsBtcWalletFunded().removeListener(isWalletFundedListener);
if (offer != null && errorMessageListener != null)
offer.getErrorMessageProperty().removeListener(errorMessageListener);
priceFeedService.updateCounterProperty().removeListener(currenciesUpdateListener);
}
///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
boolean initWithData(OfferPayload.Direction direction, TradeCurrency tradeCurrency) {
boolean result = dataModel.initWithData(direction, tradeCurrency);
if (dataModel.paymentAccount != null)
btcValidator.setMaxValue(dataModel.paymentAccount.getPaymentMethod().getMaxTradeLimitAsCoin(dataModel.getTradeCurrencyCode().get()));
btcValidator.setMaxTradeLimit(Coin.valueOf(dataModel.getMaxTradeLimit()));
btcValidator.setMinValue(Restrictions.getMinTradeAmount());
final boolean isBuy = dataModel.getDirection() == OfferPayload.Direction.BUY;
directionLabel = isBuy ? Res.get("shared.buyBitcoin") : Res.get("shared.sellBitcoin");
amountDescription = Res.get("createOffer.amountPriceBox.amountDescription",
isBuy ? Res.get("shared.buy") : Res.get("shared.sell"));
securityDepositValidator.setPaymentAccount(dataModel.paymentAccount);
buyerSecurityDeposit.set(btcFormatter.formatToPercent(dataModel.getBuyerSecurityDeposit().get()));
buyerSecurityDepositLabel.set(getSecurityDepositLabel());
applyMakerFee();
return result;
}
///////////////////////////////////////////////////////////////////////////////////////////
// UI actions
///////////////////////////////////////////////////////////////////////////////////////////
void onPlaceOffer(Offer offer, Runnable resultHandler) {
errorMessage.set(null);
createOfferRequested = true;
if (timeoutTimer == null) {
timeoutTimer = UserThread.runAfter(() -> {
stopTimeoutTimer();
createOfferRequested = false;
errorMessage.set(Res.get("createOffer.timeoutAtPublishing"));
updateButtonDisableState();
updateSpinnerInfo();
resultHandler.run();
}, 60);
}
errorMessageListener = (observable, oldValue, newValue) -> {
if (newValue != null) {
stopTimeoutTimer();
createOfferRequested = false;
if (offer.getState() == Offer.State.OFFER_FEE_PAID)
errorMessage.set(newValue + Res.get("createOffer.errorInfo"));
else
errorMessage.set(newValue);
updateButtonDisableState();
updateSpinnerInfo();
resultHandler.run();
}
};
offer.errorMessageProperty().addListener(errorMessageListener);
dataModel.onPlaceOffer(offer, transaction -> {
stopTimeoutTimer();
resultHandler.run();
placeOfferCompleted.set(true);
errorMessage.set(null);
});
updateButtonDisableState();
updateSpinnerInfo();
}
public void onPaymentAccountSelected(PaymentAccount paymentAccount) {
dataModel.onPaymentAccountSelected(paymentAccount);
if (amount.get() != null)
amountValidationResult.set(isBtcInputValid(amount.get()));
btcValidator.setMaxValue(dataModel.paymentAccount.getPaymentMethod().getMaxTradeLimitAsCoin(dataModel.getTradeCurrencyCode().get()));
btcValidator.setMaxTradeLimit(Coin.valueOf(dataModel.getMaxTradeLimit()));
securityDepositValidator.setPaymentAccount(paymentAccount);
}
public void onCurrencySelected(TradeCurrency tradeCurrency) {
dataModel.onCurrencySelected(tradeCurrency);
marketPrice = priceFeedService.getMarketPrice(dataModel.getTradeCurrencyCode().get());
marketPriceAvailableProperty.set(marketPrice == null || !marketPrice.isExternallyProvidedPrice() ? 0 : 1);
updateButtonDisableState();
}
void onShowPayFundsScreen(Runnable actionHandler) {
dataModel.estimateTxSize();
dataModel.requestTxFee(actionHandler);
showPayFundsScreenDisplayed.set(true);
updateSpinnerInfo();
}
boolean fundFromSavingsWallet() {
dataModel.fundFromSavingsWallet();
if (dataModel.getIsBtcWalletFunded().get()) {
updateButtonDisableState();
return true;
} else {
new Popup<>().warning(Res.get("shared.notEnoughFunds",
btcFormatter.formatCoinWithCode(dataModel.totalToPayAsCoinProperty().get()),
btcFormatter.formatCoinWithCode(dataModel.getTotalAvailableBalance())))
.actionButtonTextWithGoTo("navigation.funds.depositFunds")
.onAction(() -> navigation.navigateTo(MainView.class, FundsView.class, DepositView.class))
.show();
return false;
}
}
public void setIsCurrencyForMakerFeeBtc(boolean isCurrencyForMakerFeeBtc) {
dataModel.setPreferredCurrencyForMakerFeeBtc(isCurrencyForMakerFeeBtc);
applyMakerFee();
}
///////////////////////////////////////////////////////////////////////////////////////////
// Handle focus
///////////////////////////////////////////////////////////////////////////////////////////
// On focus out we do validation and apply the data to the model
void onFocusOutAmountTextField(boolean oldValue, boolean newValue) {
if (oldValue && !newValue) {
InputValidator.ValidationResult result = isBtcInputValid(amount.get());
amountValidationResult.set(result);
if (result.isValid) {
setAmountToModel();
ignoreAmountStringListener = true;
amount.set(btcFormatter.formatCoin(dataModel.getAmount().get()));
ignoreAmountStringListener = false;
dataModel.calculateVolume();
if (!dataModel.isMinAmountLessOrEqualAmount())
minAmount.set(amount.get());
else
amountValidationResult.set(result);
if (minAmount.get() != null)
minAmountValidationResult.set(isBtcInputValid(minAmount.get()));
} else if (btcValidator.getMaxTradeLimit() != null && btcValidator.getMaxTradeLimit().value == OfferRestrictions.TOLERATED_SMALL_TRADE_AMOUNT.value) {
new Popup<>().information(Res.get("popup.warning.tradeLimitDueAccountAgeRestriction.buyer",
Res.get("offerbook.warning.newVersionAnnouncement")))
.width(900)
.show();
}
// We want to trigger a recalculation of the volume
UserThread.execute(() -> {
onFocusOutVolumeTextField(true, false);
onFocusOutMinAmountTextField(true, false);
});
}
}
public void onFocusOutMinAmountTextField(boolean oldValue, boolean newValue) {
if (oldValue && !newValue) {
InputValidator.ValidationResult result = isBtcInputValid(minAmount.get());
minAmountValidationResult.set(result);
if (result.isValid) {
Coin minAmountAsCoin = dataModel.getMinAmount().get();
syncMinAmountWithAmount = minAmountAsCoin != null && minAmountAsCoin.equals(dataModel.getAmount().get());
setMinAmountToModel();
dataModel.calculateMinVolume();
if (dataModel.getMinVolume().get() != null) {
InputValidator.ValidationResult minVolumeResult = isVolumeInputValid(
btcFormatter.formatVolume(dataModel.getMinVolume().get()));
volumeValidationResult.set(minVolumeResult);
updateButtonDisableState();
}
this.minAmount.set(btcFormatter.formatCoin(minAmountAsCoin));
if (!dataModel.isMinAmountLessOrEqualAmount()) {
this.amount.set(this.minAmount.get());
} else {
minAmountValidationResult.set(result);
if (this.amount.get() != null)
amountValidationResult.set(isBtcInputValid(this.amount.get()));
}
} else {
syncMinAmountWithAmount = true;
}
}
}
void onFocusOutPriceTextField(boolean oldValue, boolean newValue) {
if (oldValue && !newValue) {
InputValidator.ValidationResult result = isPriceInputValid(price.get());
boolean isValid = result.isValid;
priceValidationResult.set(result);
if (isValid) {
setPriceToModel();
ignorePriceStringListener = true;
if (dataModel.getPrice().get() != null)
price.set(btcFormatter.formatPrice(dataModel.getPrice().get()));
ignorePriceStringListener = false;
dataModel.calculateVolume();
dataModel.calculateAmount();
applyMakerFee();
}
// We want to trigger a recalculation of the volume and minAmount
UserThread.execute(() -> {
onFocusOutVolumeTextField(true, false);
// We also need to update minAmount
onFocusOutAmountTextField(true, false);
onFocusOutMinAmountTextField(true, false);
});
}
}
public void onFocusOutPriceAsPercentageTextField(boolean oldValue, boolean newValue) {
inputIsMarketBasedPrice = !oldValue && newValue;
if (oldValue && !newValue)
if (marketPriceMargin.get() == null) {
// field wasn't set manually
inputIsMarketBasedPrice = true;
}
marketPriceMargin.set(btcFormatter.formatRoundedDoubleWithPrecision(dataModel.getMarketPriceMargin() * 100, 2));
// We want to trigger a recalculation of the volume
UserThread.execute(() -> {
onFocusOutVolumeTextField(true, false);
});
}
void onFocusOutVolumeTextField(boolean oldValue, boolean newValue) {
if (oldValue && !newValue) {
InputValidator.ValidationResult result = isVolumeInputValid(volume.get());
volumeValidationResult.set(result);
if (result.isValid) {
setVolumeToModel();
ignoreVolumeStringListener = true;
Volume volume = dataModel.getVolume().get();
if (volume != null) {
// For HalCash we want multiple of 10 EUR
if (dataModel.isHalCashAccount())
volume = OfferUtil.getAdjustedVolumeForHalCash(volume);
else if (CurrencyUtil.isFiatCurrency(tradeCurrencyCode.get()))
volume = OfferUtil.getRoundedFiatVolume(volume);
this.volume.set(btcFormatter.formatVolume(volume));
}
ignoreVolumeStringListener = false;
dataModel.calculateAmount();
if (!dataModel.isMinAmountLessOrEqualAmount()) {
minAmount.set(amount.getValue());
} else {
if (amount.get() != null)
amountValidationResult.set(isBtcInputValid(amount.get()));
// We only check minAmountValidationResult if amountValidationResult is valid, otherwise we would get
// triggered a close of the popup when the minAmountValidationResult is applied
if (amountValidationResult.getValue() != null && amountValidationResult.getValue().isValid && minAmount.get() != null)
minAmountValidationResult.set(isBtcInputValid(minAmount.get()));
}
}
}
}
void onFocusOutBuyerSecurityDepositTextField(boolean oldValue, boolean newValue) {
if (oldValue && !newValue) {
InputValidator.ValidationResult result = securityDepositValidator.validate(buyerSecurityDeposit.get());
buyerSecurityDepositValidationResult.set(result);
if (result.isValid) {
double defaultSecurityDeposit = Restrictions.getDefaultBuyerSecurityDepositAsPercent(getPaymentAccount());
String key = "buyerSecurityDepositIsLowerAsDefault";
double depositAsDouble = btcFormatter.parsePercentStringToDouble(buyerSecurityDeposit.get());
if (preferences.showAgain(key) && depositAsDouble < defaultSecurityDeposit) {
String postfix = dataModel.isBuyOffer() ?
Res.get("createOffer.tooLowSecDeposit.makerIsBuyer") :
Res.get("createOffer.tooLowSecDeposit.makerIsSeller");
new Popup<>()
.warning(Res.get("createOffer.tooLowSecDeposit.warning",
btcFormatter.formatToPercentWithSymbol(defaultSecurityDeposit)) + "\n\n" + postfix)
.width(800)
.actionButtonText(Res.get("createOffer.resetToDefault"))
.onAction(() -> {
dataModel.setBuyerSecurityDeposit(defaultSecurityDeposit);
ignoreSecurityDepositStringListener = true;
buyerSecurityDeposit.set(btcFormatter.formatToPercent(dataModel.getBuyerSecurityDeposit().get()));
ignoreSecurityDepositStringListener = false;
})
.closeButtonText(Res.get("createOffer.useLowerValue"))
.onClose(this::applyBuyerSecurityDepositOnFocusOut)
.dontShowAgainId(key)
.show();
} else {
applyBuyerSecurityDepositOnFocusOut();
}
}
}
}
private void applyBuyerSecurityDepositOnFocusOut() {
setBuyerSecurityDepositToModel();
ignoreSecurityDepositStringListener = true;
buyerSecurityDeposit.set(btcFormatter.formatToPercent(dataModel.getBuyerSecurityDeposit().get()));
ignoreSecurityDepositStringListener = false;
}
///////////////////////////////////////////////////////////////////////////////////////////
// Getters
///////////////////////////////////////////////////////////////////////////////////////////
public boolean isPriceInRange() {
if (marketPriceMargin.get() != null && !marketPriceMargin.get().isEmpty()) {
if (Math.abs(btcFormatter.parsePercentStringToDouble(marketPriceMargin.get())) > preferences.getMaxPriceDistanceInPercent()) {
displayPriceOutOfRangePopup();
return false;
} else {
return true;
}
} else {
return true;
}
}
private void displayPriceOutOfRangePopup() {
Popup popup = new Popup<>();
popup.warning(Res.get("createOffer.priceOutSideOfDeviation",
btcFormatter.formatToPercentWithSymbol(preferences.getMaxPriceDistanceInPercent())))
.actionButtonText(Res.get("createOffer.changePrice"))
.onAction(popup::hide)
.closeButtonTextWithGoTo("navigation.settings.preferences")
.onClose(() -> navigation.navigateTo(MainView.class, SettingsView.class, PreferencesView.class))
.show();
}
BSFormatter getBtcFormatter() {
return btcFormatter;
}
public boolean isSellOffer() {
return dataModel.getDirection() == OfferPayload.Direction.SELL;
}
public TradeCurrency getTradeCurrency() {
return dataModel.getTradeCurrency();
}
public String getTradeAmount() {
return btcFormatter.formatCoinWithCode(dataModel.getAmount().get());
}
public String getSecurityDepositLabel() {
return dataModel.isBuyOffer() ? Res.get("createOffer.setDepositAsBuyer") : Res.get("createOffer.setDeposit");
}
public String getSecurityDepositPopOverLabel(String depositInBTC) {
return dataModel.isBuyOffer() ? Res.get("createOffer.securityDepositInfoAsBuyer", depositInBTC) :
Res.get("createOffer.securityDepositInfo", depositInBTC);
}
public String getSecurityDepositInfo() {
return btcFormatter.formatCoinWithCode(dataModel.getSecurityDeposit()) +
GUIUtil.getPercentageOfTradeAmount(dataModel.getSecurityDeposit(), dataModel.getAmount().get(), btcFormatter);
}
public String getSecurityDepositWithCode() {
return btcFormatter.formatCoinWithCode(dataModel.getSecurityDeposit());
}
public String getTradeFee() {
//TODO use last bisq market price to estimate BSQ val
final Coin makerFeeAsCoin = dataModel.getMakerFee();
final String makerFee = getFormatterForMakerFee().formatCoinWithCode(makerFeeAsCoin);
if (dataModel.isCurrencyForMakerFeeBtc())
return makerFee + GUIUtil.getPercentageOfTradeAmount(makerFeeAsCoin, dataModel.getAmount().get(), btcFormatter);
else
return makerFee + " (" + Res.get("shared.tradingFeeInBsqInfo", btcFormatter.formatCoinWithCode(makerFeeAsCoin)) + ")";
}
public String getMakerFeePercentage() {
final Coin makerFeeAsCoin = dataModel.getMakerFee();
if (dataModel.isCurrencyForMakerFeeBtc())
return GUIUtil.getPercentage(makerFeeAsCoin, dataModel.getAmount().get(), btcFormatter);
else
return Res.get("dao.paidWithBsq");
}
public String getTotalToPayInfo() {
final String totalToPay = this.totalToPay.get();
if (dataModel.isCurrencyForMakerFeeBtc())
return totalToPay;
else
return totalToPay + " + " + bsqFormatter.formatCoinWithCode(dataModel.getMakerFee());
}
public String getFundsStructure() {
String fundsStructure;
if (dataModel.isCurrencyForMakerFeeBtc()) {
fundsStructure = Res.get("createOffer.fundsBox.fundsStructure",
getSecurityDepositWithCode(), getMakerFeePercentage(), getTxFeePercentage());
} else {
fundsStructure = Res.get("createOffer.fundsBox.fundsStructure.BSQ",
getSecurityDepositWithCode(), getTxFeePercentage(), bsqFormatter.formatCoinWithCode(dataModel.getMakerFee()));
}
return fundsStructure;
}