Skip to content

Commit

Permalink
Dissolve BSFormatter
Browse files Browse the repository at this point in the history
BSFormatter was a statefull catch all type class with a huge interface.
It had dependencies to globals and very many classes depended on it.

It was hard to reason about code flow due to how tangled up things were,
making refactoring attempts of higher level classes difficult.

To Dissolve BSFormatter the following changes were made:

- Move functions that only have 1 call-site to private functions on the caller.
- Make functions that do not depend on local state static.
- Move functions that are only depended on by the desktop project to DisplayUtils.
- Move functions that are Parsing related to ParsingUtils.
- Move remaining static functions to FormattingUtils.
- Create interface CoinFormatter and class ImmutableCoinFormatter to handle statefull functions.
- Remove dependency to globals by instantiating an instance in CoreModule and inject it via Guice.
  • Loading branch information
Justin Carter committed Sep 9, 2019
1 parent 990a998 commit 1f0d193
Show file tree
Hide file tree
Showing 172 changed files with 2,134 additions and 1,840 deletions.
6 changes: 6 additions & 0 deletions core/src/main/java/bisq/core/CoreModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
import bisq.core.proto.persistable.CorePersistenceProtoResolver;
import bisq.core.trade.TradeModule;
import bisq.core.user.Preferences;
import bisq.core.util.FormattingUtils;
import bisq.core.util.coin.CoinFormatter;
import bisq.core.util.coin.ImmutableCoinFormatter;

import bisq.network.crypto.EncryptionServiceModule;
import bisq.network.p2p.P2PModule;
Expand Down Expand Up @@ -68,6 +71,9 @@ protected void configure() {

bind(SeedNodeRepository.class).to(DefaultSeedNodeRepository.class);

CoinFormatter btcFormatter = new ImmutableCoinFormatter(BisqEnvironment.getParameters().getMonetaryFormat());
bind(CoinFormatter.class).annotatedWith(named(FormattingUtils.BTC_FORMATTER_KEY)).toInstance(btcFormatter);

File storageDir = new File(environment.getRequiredProperty(Storage.STORAGE_DIR));
bind(File.class).annotatedWith(named(Storage.STORAGE_DIR)).toInstance(storageDir);

Expand Down
8 changes: 5 additions & 3 deletions core/src/main/java/bisq/core/app/BisqSetup.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
import bisq.core.trade.statistics.TradeStatisticsManager;
import bisq.core.user.Preferences;
import bisq.core.user.User;
import bisq.core.util.BSFormatter;
import bisq.core.util.FormattingUtils;
import bisq.core.util.coin.CoinFormatter;

import bisq.network.crypto.DecryptedDataTuple;
import bisq.network.crypto.EncryptionService;
Expand All @@ -73,6 +74,7 @@
import org.bitcoinj.core.Coin;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import com.google.common.net.InetAddresses;
Expand Down Expand Up @@ -156,7 +158,7 @@ public interface BisqSetupCompleteListener {
private final AssetService assetService;
private final TorSetup torSetup;
private final TradeLimits tradeLimits;
private final BSFormatter formatter;
private final CoinFormatter formatter;
@Setter
@Nullable
private Consumer<Runnable> displayTacHandler;
Expand Down Expand Up @@ -235,7 +237,7 @@ public BisqSetup(P2PNetworkSetup p2PNetworkSetup,
AssetService assetService,
TorSetup torSetup,
TradeLimits tradeLimits,
BSFormatter formatter) {
@Named(FormattingUtils.BTC_FORMATTER_KEY) CoinFormatter formatter) {


this.p2PNetworkSetup = p2PNetworkSetup;
Expand Down
11 changes: 5 additions & 6 deletions core/src/main/java/bisq/core/app/WalletAppSetup.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
import bisq.core.btc.wallet.WalletsManager;
import bisq.core.locale.Res;
import bisq.core.user.Preferences;
import bisq.core.util.BSFormatter;
import bisq.core.util.coin.CoinFormatter;
import bisq.core.util.coin.ImmutableCoinFormatter;
import bisq.core.util.FormattingUtils;

import org.bitcoinj.core.VersionMessage;
import org.bitcoinj.store.BlockStoreException;
Expand Down Expand Up @@ -57,7 +59,6 @@ public class WalletAppSetup {
private final WalletsSetup walletsSetup;
private final BisqEnvironment bisqEnvironment;
private final Preferences preferences;
private final BSFormatter formatter;

@SuppressWarnings("FieldCanBeLocal")
private MonadicBinding<String> btcInfoBinding;
Expand All @@ -79,13 +80,11 @@ public class WalletAppSetup {
public WalletAppSetup(WalletsManager walletsManager,
WalletsSetup walletsSetup,
BisqEnvironment bisqEnvironment,
Preferences preferences,
BSFormatter formatter) {
Preferences preferences) {
this.walletsManager = walletsManager;
this.walletsSetup = walletsSetup;
this.bisqEnvironment = bisqEnvironment;
this.preferences = preferences;
this.formatter = formatter;
this.useTorForBTC.set(preferences.getUseTorForBitcoinJ());
}

Expand Down Expand Up @@ -120,7 +119,7 @@ void init(@Nullable Consumer<String> chainFileLockedExceptionHandler,
result = Res.get("mainView.footer.btcInfo",
peers,
Res.get("mainView.footer.btcInfo.synchronizingWith"),
getBtcNetworkAsString() + ": " + formatter.formatToPercentWithSymbol(percentage));
getBtcNetworkAsString() + ": " + FormattingUtils.formatToPercentWithSymbol(percentage));
} else {
result = Res.get("mainView.footer.btcInfo",
peers,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
import bisq.core.locale.CurrencyUtil;
import bisq.core.trade.statistics.TradeStatistics2;
import bisq.core.trade.statistics.TradeStatisticsManager;
import bisq.core.util.BsqFormatter;
import bisq.core.util.coin.BsqFormatter;

import bisq.common.Timer;
import bisq.common.UserThread;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
import bisq.core.dao.state.model.governance.ChangeParamProposal;
import bisq.core.dao.state.model.governance.Proposal;
import bisq.core.locale.Res;
import bisq.core.util.BsqFormatter;
import bisq.core.util.coin.BsqFormatter;
import bisq.core.util.validation.BtcAddressValidator;
import bisq.core.util.validation.InputValidator;

Expand Down
16 changes: 8 additions & 8 deletions core/src/main/java/bisq/core/dao/presentation/DaoUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import bisq.core.dao.DaoFacade;
import bisq.core.dao.state.model.governance.DaoPhase;
import bisq.core.locale.Res;
import bisq.core.util.BSFormatter;
import bisq.core.util.FormattingUtils;

import java.text.SimpleDateFormat;

Expand All @@ -32,30 +32,30 @@
*/
public class DaoUtil {

public static String getNextPhaseDuration(int height, DaoPhase.Phase phase, DaoFacade daoFacade, BSFormatter formatter) {
public static String getNextPhaseDuration(int height, DaoPhase.Phase phase, DaoFacade daoFacade) {
final int currentCycleDuration = daoFacade.getCurrentCycleDuration();
long start = daoFacade.getFirstBlockOfPhaseForDisplay(height, phase) + currentCycleDuration;
long end = daoFacade.getLastBlockOfPhaseForDisplay(height, phase) + currentCycleDuration;

long now = new Date().getTime();
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM", Locale.getDefault());
SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm", Locale.getDefault());
String startDateTime = formatter.formatDateTime(new Date(now + (start - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter);
String endDateTime = formatter.formatDateTime(new Date(now + (end - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter);
String startDateTime = FormattingUtils.formatDateTime(new Date(now + (start - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter);
String endDateTime = FormattingUtils.formatDateTime(new Date(now + (end - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter);

return Res.get("dao.cycle.phaseDurationWithoutBlocks", start, end, startDateTime, endDateTime);
}

public static String getPhaseDuration(int height, DaoPhase.Phase phase, DaoFacade daoFacade, BSFormatter formatter) {
public static String getPhaseDuration(int height, DaoPhase.Phase phase, DaoFacade daoFacade) {
long start = daoFacade.getFirstBlockOfPhaseForDisplay(height, phase);
long end = daoFacade.getLastBlockOfPhaseForDisplay(height, phase);
long duration = daoFacade.getDurationForPhaseForDisplay(phase);
long now = new Date().getTime();
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM", Locale.getDefault());
SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm", Locale.getDefault());
String startDateTime = formatter.formatDateTime(new Date(now + (start - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter);
String endDateTime = formatter.formatDateTime(new Date(now + (end - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter);
String durationTime = formatter.formatDurationAsWords(duration * 10 * 60 * 1000, false, false);
String startDateTime = FormattingUtils.formatDateTime(new Date(now + (start - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter);
String endDateTime = FormattingUtils.formatDateTime(new Date(now + (end - height) * 10 * 60 * 1000L), dateFormatter, timeFormatter);
String durationTime = FormattingUtils.formatDurationAsWords(duration * 10 * 60 * 1000, false, false);
return Res.get("dao.cycle.phaseDuration", duration, durationTime, start, end, startDateTime, endDateTime);
}
}
5 changes: 3 additions & 2 deletions core/src/main/java/bisq/core/dao/state/DaoStateService.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
import bisq.core.dao.state.model.governance.Issuance;
import bisq.core.dao.state.model.governance.IssuanceType;
import bisq.core.dao.state.model.governance.ParamChange;
import bisq.core.util.BsqFormatter;
import bisq.core.util.coin.BsqFormatter;
import bisq.core.util.ParsingUtils;

import org.bitcoinj.core.Coin;

Expand Down Expand Up @@ -923,7 +924,7 @@ public Coin getParamValueAsCoin(Param param, String paramValue) {
}

public double getParamValueAsPercentDouble(String paramValue) {
return bsqFormatter.parsePercentStringToDouble(paramValue);
return ParsingUtils.parsePercentStringToDouble(paramValue);
}

public int getParamValueAsBlock(String paramValue) {
Expand Down
25 changes: 25 additions & 0 deletions core/src/main/java/bisq/core/locale/CurrencyUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -507,4 +507,29 @@ public static List<CryptoCurrency> getActiveSortedCryptoCurrencies(AssetService
.filter(e -> !filterManager.isCurrencyBanned(e.getCode()))
.collect(Collectors.toList());
}

public static String getCurrencyPair(String currencyCode) {
if (isFiatCurrency(currencyCode))
return Res.getBaseCurrencyCode() + "/" + currencyCode;
else
return currencyCode + "/" + Res.getBaseCurrencyCode();
}

public static String getCounterCurrency(String currencyCode) {
if (isFiatCurrency(currencyCode))
return currencyCode;
else
return Res.getBaseCurrencyCode();
}

public static String getPriceWithCurrencyCode(String currencyCode) {
return getPriceWithCurrencyCode(currencyCode, "shared.priceInCurForCur");
}

public static String getPriceWithCurrencyCode(String currencyCode, String translationKey) {
if (isCryptoCurrency(currencyCode))
return Res.get(translationKey, Res.getBaseCurrencyCode(), currencyCode);
else
return Res.get(translationKey, currencyCode, Res.getBaseCurrencyCode());
}
}
4 changes: 2 additions & 2 deletions core/src/main/java/bisq/core/monetary/Altcoin.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

package bisq.core.monetary;

import bisq.core.util.BSFormatter;
import bisq.core.util.ParsingUtils;

import org.bitcoinj.core.Monetary;
import org.bitcoinj.utils.MonetaryFormat;
Expand Down Expand Up @@ -89,7 +89,7 @@ public String getCurrencyCode() {
* @throws IllegalArgumentException if you try to specify fractional satoshis, or a value out of range.
*/
public static Altcoin parseAltcoin(final String currencyCode, String input) {
String cleaned = BSFormatter.convertCharsForNumber(input);
String cleaned = ParsingUtils.convertCharsForNumber(input);
try {
long val = new BigDecimal(cleaned).movePointRight(SMALLEST_UNIT_EXPONENT)
.toBigIntegerExact().longValue();
Expand Down
4 changes: 2 additions & 2 deletions core/src/main/java/bisq/core/monetary/Price.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
package bisq.core.monetary;

import bisq.core.locale.CurrencyUtil;
import bisq.core.util.BSFormatter;
import bisq.core.util.ParsingUtils;

import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Monetary;
Expand Down Expand Up @@ -58,7 +58,7 @@ public Price(Monetary monetary) {
* @return The parsed Price.
*/
public static Price parse(String currencyCode, String input) {
String cleaned = BSFormatter.convertCharsForNumber(input);
String cleaned = ParsingUtils.convertCharsForNumber(input);
if (CurrencyUtil.isFiatCurrency(currencyCode))
return new Price(Fiat.parseFiat(currencyCode, cleaned));
else
Expand Down
4 changes: 2 additions & 2 deletions core/src/main/java/bisq/core/monetary/Volume.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
package bisq.core.monetary;

import bisq.core.locale.CurrencyUtil;
import bisq.core.util.BSFormatter;
import bisq.core.util.ParsingUtils;

import org.bitcoinj.core.Monetary;
import org.bitcoinj.utils.Fiat;
Expand All @@ -36,7 +36,7 @@ public Volume(Monetary monetary) {
}

public static Volume parse(String input, String currencyCode) {
String cleaned = BSFormatter.convertCharsForNumber(input);
String cleaned = ParsingUtils.convertCharsForNumber(input);
if (CurrencyUtil.isFiatCurrency(currencyCode))
return new Volume(Fiat.parseFiat(currencyCode, cleaned));
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
import bisq.core.provider.price.MarketPrice;
import bisq.core.provider.price.PriceFeedService;
import bisq.core.user.User;
import bisq.core.util.BSFormatter;
import bisq.core.util.FormattingUtils;

import bisq.common.crypto.KeyRing;
import bisq.common.util.MathUtils;
Expand All @@ -53,17 +53,15 @@ public class MarketAlerts {
private final User user;
private final PriceFeedService priceFeedService;
private final KeyRing keyRing;
private final BSFormatter formatter;

@Inject
public MarketAlerts(OfferBookService offerBookService, MobileNotificationService mobileNotificationService,
User user, PriceFeedService priceFeedService, KeyRing keyRing, BSFormatter formatter) {
User user, PriceFeedService priceFeedService, KeyRing keyRing) {
this.offerBookService = offerBookService;
this.mobileNotificationService = mobileNotificationService;
this.user = user;
this.priceFeedService = priceFeedService;
this.keyRing = keyRing;
this.formatter = formatter;
}


Expand Down Expand Up @@ -180,9 +178,9 @@ else if (!isFiatCurrency && !isSellOffer)
ratio = Math.abs(ratio);
String msg = Res.get("account.notifications.marketAlert.message.msg",
direction,
formatter.getCurrencyPair(currencyCode),
formatter.formatPrice(offerPrice),
formatter.formatToPercentWithSymbol(ratio / 10000d),
CurrencyUtil.getCurrencyPair(currencyCode),
FormattingUtils.formatPrice(offerPrice),
FormattingUtils.formatToPercentWithSymbol(ratio / 10000d),
marketDir,
Res.get(offer.getPaymentMethod().getId()),
shortOfferId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
import bisq.core.provider.price.MarketPrice;
import bisq.core.provider.price.PriceFeedService;
import bisq.core.user.User;
import bisq.core.util.BSFormatter;
import bisq.core.util.coin.ImmutableCoinFormatter;
import bisq.core.util.FormattingUtils;

import bisq.common.util.MathUtils;

Expand All @@ -43,14 +44,12 @@ public class PriceAlert {
private final PriceFeedService priceFeedService;
private final MobileNotificationService mobileNotificationService;
private final User user;
private final BSFormatter formatter;

@Inject
public PriceAlert(PriceFeedService priceFeedService, MobileNotificationService mobileNotificationService, User user, BSFormatter formatter) {
public PriceAlert(PriceFeedService priceFeedService, MobileNotificationService mobileNotificationService, User user) {
this.priceFeedService = priceFeedService;
this.user = user;
this.mobileNotificationService = mobileNotificationService;
this.formatter = formatter;
}

public void onAllServicesInitialized() {
Expand All @@ -70,8 +69,8 @@ private void update() {
if (priceAsLong > filter.getHigh() || priceAsLong < filter.getLow()) {
String msg = Res.get("account.notifications.priceAlert.message.msg",
currencyName,
formatter.formatMarketPrice(priceAsDouble, currencyCode),
formatter.getCurrencyPair(currencyCode));
FormattingUtils.formatMarketPrice(priceAsDouble, currencyCode),
CurrencyUtil.getCurrencyPair(currencyCode));
MobileMessage message = new MobileMessage(Res.get("account.notifications.priceAlert.message.title", currencyName),
msg,
MobileMessageType.PRICE);
Expand Down
17 changes: 2 additions & 15 deletions core/src/main/java/bisq/core/offer/OfferUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,8 @@
import bisq.core.provider.price.PriceFeedService;
import bisq.core.trade.statistics.ReferralIdService;
import bisq.core.user.Preferences;
import bisq.core.util.BSFormatter;
import bisq.core.util.BsqFormatter;
import bisq.core.util.CoinUtil;
import bisq.core.util.coin.BsqFormatter;
import bisq.core.util.coin.CoinUtil;

import bisq.network.p2p.P2PService;

Expand Down Expand Up @@ -306,18 +305,6 @@ public static Optional<Volume> getFeeInUserFiatCurrency(Coin makerFee, boolean i
}
}

public static String getFeeWithFiatAmount(Coin makerFeeAsCoin, Optional<Volume> optionalFeeInFiat, BSFormatter formatter) {
String fee = makerFeeAsCoin != null ? formatter.formatCoinWithCode(makerFeeAsCoin) : Res.get("shared.na");
String feeInFiatAsString;
if (optionalFeeInFiat != null && optionalFeeInFiat.isPresent()) {
feeInFiatAsString = formatter.formatVolumeWithCode(optionalFeeInFiat.get());
} else {
feeInFiatAsString = Res.get("shared.na");
}
return Res.get("feeOptionWindow.fee", fee, feeInFiatAsString);
}


public static Map<String, String> getExtraDataMap(AccountAgeWitnessService accountAgeWitnessService,
ReferralIdService referralIdService,
PaymentAccount paymentAccount,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@
package bisq.core.presentation;

import bisq.core.btc.Balances;
import bisq.core.util.BSFormatter;
import bisq.core.util.FormattingUtils;
import bisq.core.util.coin.CoinFormatter;
import bisq.core.util.coin.ImmutableCoinFormatter;

import javax.inject.Inject;
import javax.inject.Named;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
Expand All @@ -38,7 +41,7 @@ public class BalancePresentation {
private final StringProperty lockedBalance = new SimpleStringProperty();

@Inject
public BalancePresentation(Balances balances, BSFormatter formatter) {
public BalancePresentation(Balances balances, @Named(FormattingUtils.BTC_FORMATTER_KEY) CoinFormatter formatter) {
balances.getAvailableBalance().addListener((observable, oldValue, newValue) -> {
String value = formatter.formatCoinWithCode(newValue);
// If we get full precision the BTC postfix breaks layout so we omit it
Expand Down
Loading

0 comments on commit 1f0d193

Please sign in to comment.