Search in sources :

Example 11 with BtcWalletService

use of bisq.core.btc.wallet.BtcWalletService in project bisq-desktop by bisq-network.

the class BsqTxView method getCompensationRequestTxListItems.

// We add manually a modified copy of the compensation request tx if it has become an issuance tx
// It is a bit weird to have one tx displayed 2 times but I think it is better to show both aspects
// separately. First the compensation request tx with the fee then after voting the issuance.
private List<BsqTxListItem> getCompensationRequestTxListItems(List<BsqTxListItem> items) {
    List<BsqTxListItem> issuanceTxList = new ArrayList<>();
    items.stream().filter(item -> item.getTxType() == TxType.COMPENSATION_REQUEST).peek(item -> {
        final Tx tx = readableBsqBlockChain.getTx(item.getTxId()).get();
        // We have mandatory BSQ change at output 0
        long changeValue = tx.getOutputs().get(0).getValue();
        long inputValue = tx.getInputs().stream().filter(input -> input.getConnectedTxOutput() != null).mapToLong(input -> input.getConnectedTxOutput().getValue()).sum();
        // We want to show fee as negative number
        long fee = changeValue - inputValue;
        item.setAmount(Coin.valueOf(fee));
    }).filter(item -> {
        final Optional<Tx> optionalTx = readableBsqBlockChain.getTx(item.getTxId());
        if (optionalTx.isPresent()) {
            final List<TxOutput> outputs = optionalTx.get().getOutputs();
            if (!outputs.isEmpty()) {
                return outputs.get(0).getTxOutputType() == TxOutputType.BSQ_OUTPUT;
            }
        }
        return false;
    }).forEach(item -> {
        final Tx tx = readableBsqBlockChain.getTx(item.getTxId()).get();
        final int blockHeight = tx.getBlockHeight();
        final int issuanceBlockHeight = daoPeriodService.getAbsoluteStartBlockOfPhase(blockHeight, DaoPeriodService.Phase.ISSUANCE);
        // We use the time of the block height of the start of the issuance period
        final long blockTimeInSec = readableBsqBlockChain.getBlockTime(issuanceBlockHeight);
        final BsqTxListItem issuanceItem = new BsqTxListItem(item.getTransaction(), bsqWalletService, btcWalletService, Optional.of(TxType.ISSUANCE), item.isBurnedBsqTx(), new Date(blockTimeInSec * 1000), bsqFormatter);
        // On output 1 we have the issuance candidate
        long issuanceValue = tx.getOutputs().get(1).getValue();
        issuanceItem.setAmount(Coin.valueOf(issuanceValue));
        issuanceTxList.add(issuanceItem);
    });
    return issuanceTxList;
}
Also used : Transaction(org.bitcoinj.core.Transaction) HyperlinkWithIcon(bisq.desktop.components.HyperlinkWithIcon) Coin(org.bitcoinj.core.Coin) Date(java.util.Date) ReadableBsqBlockChain(bisq.core.dao.blockchain.ReadableBsqBlockChain) VBox(javafx.scene.layout.VBox) BsqBalanceListener(bisq.core.btc.wallet.BsqBalanceListener) BsqNode(bisq.core.dao.node.BsqNode) ReadOnlyObjectWrapper(javafx.beans.property.ReadOnlyObjectWrapper) ListChangeListener(javafx.collections.ListChangeListener) Res(bisq.core.locale.Res) TableView(javafx.scene.control.TableView) Pane(javafx.scene.layout.Pane) SortedList(javafx.collections.transformation.SortedList) HBox(javafx.scene.layout.HBox) AutoTooltipTableColumn(bisq.desktop.components.AutoTooltipTableColumn) AutoTooltipLabel(bisq.desktop.components.AutoTooltipLabel) FormBuilder(bisq.desktop.util.FormBuilder) TxOutput(bisq.core.dao.blockchain.vo.TxOutput) Collectors(java.util.stream.Collectors) BsqWalletService(bisq.core.btc.wallet.BsqWalletService) BsqBalanceUtil(bisq.desktop.main.dao.wallet.BsqBalanceUtil) List(java.util.List) Preferences(bisq.core.user.Preferences) SimpleDoubleProperty(javafx.beans.property.SimpleDoubleProperty) Optional(java.util.Optional) ObservableList(javafx.collections.ObservableList) AwesomeIcon(de.jensd.fx.fontawesome.AwesomeIcon) GUIUtil(bisq.desktop.util.GUIUtil) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) ActivatableView(bisq.desktop.common.view.ActivatableView) FXCollections(javafx.collections.FXCollections) DoubleProperty(javafx.beans.property.DoubleProperty) BsqNodeProvider(bisq.core.dao.node.BsqNodeProvider) FxmlView(bisq.desktop.common.view.FxmlView) TableColumn(javafx.scene.control.TableColumn) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) TableCell(javafx.scene.control.TableCell) ProgressBar(javafx.scene.control.ProgressBar) Insets(javafx.geometry.Insets) AddressWithIconAndDirection(bisq.desktop.components.AddressWithIconAndDirection) Callback(javafx.util.Callback) Tooltip(javafx.scene.control.Tooltip) GridPane(javafx.scene.layout.GridPane) Label(javafx.scene.control.Label) DaoPeriodService(bisq.core.dao.DaoPeriodService) Tx(bisq.core.dao.blockchain.vo.Tx) AwesomeDude(de.jensd.fx.fontawesome.AwesomeDude) BisqEnvironment(bisq.core.app.BisqEnvironment) TxType(bisq.core.dao.blockchain.vo.TxType) BsqFormatter(bisq.desktop.util.BsqFormatter) TxOutputType(bisq.core.dao.blockchain.vo.TxOutputType) ChangeListener(javafx.beans.value.ChangeListener) Tx(bisq.core.dao.blockchain.vo.Tx) Optional(java.util.Optional) ArrayList(java.util.ArrayList) SortedList(javafx.collections.transformation.SortedList) List(java.util.List) ObservableList(javafx.collections.ObservableList) ArrayList(java.util.ArrayList) Date(java.util.Date)

Example 12 with BtcWalletService

use of bisq.core.btc.wallet.BtcWalletService in project bisq-desktop by bisq-network.

the class BuyerStep4View method reviewWithdrawal.

@SuppressWarnings("PointlessBooleanExpression")
private void reviewWithdrawal() {
    Coin amount = trade.getPayoutAmount();
    BtcWalletService walletService = model.dataModel.btcWalletService;
    AddressEntry fromAddressesEntry = walletService.getOrCreateAddressEntry(trade.getId(), AddressEntry.Context.TRADE_PAYOUT);
    String fromAddresses = fromAddressesEntry.getAddressString();
    String toAddresses = withdrawAddressTextField.getText();
    if (new BtcAddressValidator().validate(toAddresses).isValid) {
        Coin balance = walletService.getBalanceForAddress(fromAddressesEntry.getAddress());
        try {
            Transaction feeEstimationTransaction = walletService.getFeeEstimationTransaction(fromAddresses, toAddresses, amount, AddressEntry.Context.TRADE_PAYOUT);
            Coin fee = feeEstimationTransaction.getFee();
            // noinspection UnusedAssignment
            Coin receiverAmount = amount.subtract(fee);
            if (balance.isZero()) {
                new Popup<>().warning(Res.get("portfolio.pending.step5_buyer.alreadyWithdrawn")).show();
                model.dataModel.tradeManager.addTradeToClosedTrades(trade);
            } else {
                if (toAddresses.isEmpty()) {
                    validateWithdrawAddress();
                } else if (Restrictions.isAboveDust(amount, fee)) {
                    BSFormatter formatter = model.btcFormatter;
                    int txSize = feeEstimationTransaction.bitcoinSerialize().length;
                    double feePerByte = CoinUtil.getFeePerByte(fee, txSize);
                    double kb = txSize / 1000d;
                    String recAmount = formatter.formatCoinWithCode(receiverAmount);
                    new Popup<>().headLine(Res.get("portfolio.pending.step5_buyer.confirmWithdrawal")).confirmation(Res.get("shared.sendFundsDetailsWithFee", formatter.formatCoinWithCode(amount), fromAddresses, toAddresses, formatter.formatCoinWithCode(fee), feePerByte, kb, recAmount)).actionButtonText(Res.get("shared.yes")).onAction(() -> doWithdrawal(amount, fee)).closeButtonText(Res.get("shared.cancel")).onClose(() -> {
                        useSavingsWalletButton.setDisable(false);
                        withdrawToExternalWalletButton.setDisable(false);
                    }).show();
                } else {
                    new Popup<>().warning(Res.get("portfolio.pending.step5_buyer.amountTooLow")).show();
                }
            }
        } catch (AddressFormatException e) {
            validateWithdrawAddress();
        } catch (AddressEntryException e) {
            log.error(e.getMessage());
        } catch (InsufficientFundsException e) {
            log.error(e.getMessage());
            e.printStackTrace();
            new Popup<>().warning(e.getMessage()).show();
        }
    } else {
        new Popup<>().warning(Res.get("validation.btc.invalidAddress")).show();
    }
}
Also used : BtcAddressValidator(bisq.desktop.util.validation.BtcAddressValidator) Coin(org.bitcoinj.core.Coin) AddressFormatException(org.bitcoinj.core.AddressFormatException) AddressEntryException(bisq.core.btc.AddressEntryException) Transaction(org.bitcoinj.core.Transaction) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) AddressEntry(bisq.core.btc.AddressEntry) Popup(bisq.desktop.main.overlays.popups.Popup) InsufficientFundsException(bisq.core.btc.InsufficientFundsException) BSFormatter(bisq.desktop.util.BSFormatter)

Example 13 with BtcWalletService

use of bisq.core.btc.wallet.BtcWalletService in project bisq-desktop by bisq-network.

the class DisplayedTransactionsTest method testUpdate.

@Test
public void testUpdate() {
    Set<Transaction> transactions = Sets.newHashSet(mock(Transaction.class), mock(Transaction.class));
    BtcWalletService walletService = mock(BtcWalletService.class);
    when(walletService.getTransactions(false)).thenReturn(transactions);
    TransactionListItemFactory transactionListItemFactory = mock(TransactionListItemFactory.class, RETURNS_DEEP_STUBS);
    @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") DisplayedTransactions testedEntity = new DisplayedTransactions(walletService, mock(TradableRepository.class), transactionListItemFactory, mock(TransactionAwareTradableFactory.class));
    testedEntity.update();
    assertEquals(transactions.size(), testedEntity.size());
}
Also used : Transaction(org.bitcoinj.core.Transaction) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) Test(org.junit.Test)

Example 14 with BtcWalletService

use of bisq.core.btc.wallet.BtcWalletService in project bisq-desktop by bisq-network.

the class DisplayedTransactionsTest method testUpdateWhenRepositoryIsEmpty.

@Test
public void testUpdateWhenRepositoryIsEmpty() {
    BtcWalletService walletService = mock(BtcWalletService.class);
    when(walletService.getTransactions(false)).thenReturn(Collections.singleton(mock(Transaction.class)));
    TradableRepository tradableRepository = mock(TradableRepository.class);
    when(tradableRepository.getAll()).thenReturn(Collections.emptySet());
    TransactionListItemFactory transactionListItemFactory = mock(TransactionListItemFactory.class);
    @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") DisplayedTransactions testedEntity = new DisplayedTransactions(walletService, tradableRepository, transactionListItemFactory, mock(TransactionAwareTradableFactory.class));
    testedEntity.update();
    assertEquals(1, testedEntity.size());
    verify(transactionListItemFactory).create(any(), nullable(TransactionAwareTradable.class));
}
Also used : BtcWalletService(bisq.core.btc.wallet.BtcWalletService) Test(org.junit.Test)

Example 15 with BtcWalletService

use of bisq.core.btc.wallet.BtcWalletService in project bisq-desktop by bisq-network.

the class CreateOfferViewModelTest method setUp.

@Before
public void setUp() {
    final CryptoCurrency btc = new CryptoCurrency("BTC", "bitcoin");
    GlobalSettings.setDefaultTradeCurrency(btc);
    Res.setBaseCurrencyCode(btc.getCode());
    Res.setBaseCurrencyName(btc.getName());
    final BSFormatter bsFormatter = new BSFormatter();
    final BtcValidator btcValidator = new BtcValidator(bsFormatter);
    final AltcoinValidator altcoinValidator = new AltcoinValidator();
    final FiatPriceValidator fiatPriceValidator = new FiatPriceValidator();
    FeeService feeService = mock(FeeService.class);
    AddressEntry addressEntry = mock(AddressEntry.class);
    BtcWalletService btcWalletService = mock(BtcWalletService.class);
    PriceFeedService priceFeedService = mock(PriceFeedService.class);
    User user = mock(User.class);
    PaymentAccount paymentAccount = mock(PaymentAccount.class);
    BsqWalletService bsqWalletService = mock(BsqWalletService.class);
    SecurityDepositValidator securityDepositValidator = mock(SecurityDepositValidator.class);
    when(btcWalletService.getOrCreateAddressEntry(anyString(), any())).thenReturn(addressEntry);
    when(btcWalletService.getBalanceForAddress(any())).thenReturn(Coin.valueOf(1000L));
    when(priceFeedService.updateCounterProperty()).thenReturn(new SimpleIntegerProperty());
    when(priceFeedService.getMarketPrice(anyString())).thenReturn(new MarketPrice("USD", 12684.0450, Instant.now().getEpochSecond(), true));
    when(feeService.getTxFee(anyInt())).thenReturn(Coin.valueOf(1000L));
    when(user.findFirstPaymentAccountWithCurrency(any())).thenReturn(paymentAccount);
    when(user.getPaymentAccountsAsObservable()).thenReturn(FXCollections.observableSet());
    when(securityDepositValidator.validate(any())).thenReturn(new InputValidator.ValidationResult(false));
    CreateOfferDataModel dataModel = new CreateOfferDataModel(null, btcWalletService, bsqWalletService, empty, user, null, null, priceFeedService, null, null, null, feeService, bsFormatter);
    dataModel.initWithData(OfferPayload.Direction.BUY, new CryptoCurrency("BTC", "bitcoin"));
    dataModel.activate();
    model = new CreateOfferViewModel(dataModel, null, fiatPriceValidator, altcoinValidator, btcValidator, null, securityDepositValidator, null, null, priceFeedService, null, null, bsFormatter, null);
    model.activate();
}
Also used : BtcValidator(bisq.desktop.util.validation.BtcValidator) FiatPriceValidator(bisq.desktop.util.validation.FiatPriceValidator) User(bisq.core.user.User) AddressEntry(bisq.core.btc.AddressEntry) PaymentAccount(bisq.core.payment.PaymentAccount) FeeService(bisq.core.provider.fee.FeeService) BSFormatter(bisq.desktop.util.BSFormatter) AltcoinValidator(bisq.desktop.util.validation.AltcoinValidator) CryptoCurrency(bisq.core.locale.CryptoCurrency) SecurityDepositValidator(bisq.desktop.util.validation.SecurityDepositValidator) MarketPrice(bisq.core.provider.price.MarketPrice) InputValidator(bisq.core.util.validation.InputValidator) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) PriceFeedService(bisq.core.provider.price.PriceFeedService) BsqWalletService(bisq.core.btc.wallet.BsqWalletService) SimpleIntegerProperty(javafx.beans.property.SimpleIntegerProperty) Before(org.junit.Before)

Aggregations

BtcWalletService (bisq.core.btc.wallet.BtcWalletService)23 AddressEntry (bisq.core.btc.AddressEntry)15 Coin (org.bitcoinj.core.Coin)11 Transaction (org.bitcoinj.core.Transaction)10 Address (org.bitcoinj.core.Address)8 TradingPeer (bisq.core.trade.protocol.TradingPeer)7 NodeAddress (bisq.network.p2p.NodeAddress)5 RawTransactionInput (bisq.core.btc.data.RawTransactionInput)4 BsqWalletService (bisq.core.btc.wallet.BsqWalletService)4 Offer (bisq.core.offer.Offer)4 PaymentAccountPayload (bisq.core.payment.payload.PaymentAccountPayload)4 Contract (bisq.core.trade.Contract)3 Date (java.util.Date)3 Slf4j (lombok.extern.slf4j.Slf4j)3 UserThread (bisq.common.UserThread)2 TaskRunner (bisq.common.taskrunner.TaskRunner)2 Arbitrator (bisq.core.arbitration.Arbitrator)2 InputsAndChangeOutput (bisq.core.btc.data.InputsAndChangeOutput)2 PreparedDepositTxAndMakerInputs (bisq.core.btc.data.PreparedDepositTxAndMakerInputs)2 AddressConfidenceListener (bisq.core.btc.listeners.AddressConfidenceListener)2