Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 49 additions & 4 deletions Bitkit/Views/Wallets/Send/SendConfirmationView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ struct SendConfirmationView: View {
@State private var walletSwitchRun: WalletSwitchRun?
@State private var manualCoinsRequestedContext: ConfirmationContext?
@State private var isPreparingDirectOnchainSend = false
/// The hardware wallet Confirm switched to because Savings could not pay the fixed amount.
@State private var savingsFallbackWalletId: String?
@State private var onchainFeeCalculationId: Int?
@State private var presentationID: UUID?

Expand Down Expand Up @@ -844,6 +846,7 @@ struct SendConfirmationView: View {
}

private func selectFundingSource(_ source: SendFundingSource) {
savingsFallbackWalletId = nil
switch source {
case .usdt:
navigationPath = amountIsRoot ? [] : [.amount]
Expand Down Expand Up @@ -1203,15 +1206,36 @@ struct SendConfirmationView: View {
isHardwarePayment && !isContactPayment && !afterFundingSwitch
}

/// The first hardware wallet whose balance covers the amount, used only when Savings is short of it, so any
/// other coin-selection failure is reported instead. The wallet's fee preview decides whether it can pay.
/// The hardware wallet with the largest balance, when it covers the amount, used only when Savings is short of it, so
/// any other coin-selection failure is reported instead. The wallet's fee preview decides whether it can pay; a smaller
/// wallet cannot pay what the largest cannot.
static func hardwareWalletCovering(
amount: UInt64,
savingsBalanceSats: UInt64,
balances: [(walletId: String, balanceSats: UInt64)]
) -> String? {
guard savingsBalanceSats < amount else { return nil }
return balances.first { $0.balanceSats >= amount }?.walletId
guard savingsBalanceSats < amount, let largest = balances.max(by: { $0.balanceSats < $1.balanceSats }),
largest.balanceSats >= amount
else { return nil }
return largest.walletId
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}

/// A failed preview of the Savings fallback wallet is insufficient funds when the compose reports it, or when the amount
/// leaves less than the fee reserve; any other failure, such as Electrum being unreachable, keeps Try again.
static func isSavingsFallbackShortOfFee(
fallbackWalletId: String?,
walletId: String?,
previewErrorDetail: String?,
amountSats: UInt64,
balanceSats: UInt64,
feeReserveSats: UInt64
) -> Bool {
guard fallbackWalletId != nil, fallbackWalletId == walletId else { return false }
// The compose's coin selection names the shortfall, which can exceed the reserve when many inputs are spent.
if previewErrorDetail?.localizedCaseInsensitiveContains("insufficient funds") == true {
return true
}
return balanceSats < feeReserveSats || amountSats > balanceSats - feeReserveSats
Comment thread
jvsena42 marked this conversation as resolved.
Resolved
}

/// Only the newest fee calculation can hold the swipe, so a calculation superseded by a funding switch never leaves it disabled.
Expand Down Expand Up @@ -2044,6 +2068,7 @@ struct SendConfirmationView: View {
)
{
selectFundingSource(.hardware(walletId: walletId))
savingsFallbackWalletId = walletId
return
}
app.toast(type: .error, title: t("other__try_again"), description: error.localizedDescription)
Expand Down Expand Up @@ -2134,6 +2159,7 @@ struct SendConfirmationView: View {
satsPerVByte: UInt64(feeRate)
) else { return }
apply(fee)
savingsFallbackWalletId = nil
return
}

Expand Down Expand Up @@ -2170,6 +2196,25 @@ struct SendConfirmationView: View {
Logger.error("Failed to calculate actual fee: \(error)")
transactionFee = 0
if hwSend.isActive, app.contactPaymentContext == nil {
let balanceSats = hwSend.walletId.map { hwWalletManager.fundingBalance(walletId: $0) } ?? 0
if Self.isSavingsFallbackShortOfFee(
fallbackWalletId: savingsFallbackWalletId,
walletId: hwSend.walletId,
previewErrorDetail: (error as? AppError)?.debugMessage,
amountSats: amountSats,
balanceSats: balanceSats,
feeReserveSats: HwFundingSigner.feeReserve(balanceSats: balanceSats, satsPerVByte: UInt64(feeRate))
) {
savingsFallbackWalletId = nil
app.toast(
type: .error,
title: t("other__pay_insufficient_savings"),
description: t("other__pay_insufficient_savings_description"),
accessibilityIdentifier: "InsufficientSavingsToast"
)
leaveAfterPreparationFailure()
return
}
app.toast(type: .error, title: t("other__try_again"), description: error.localizedDescription)
if Self.leavesConfirmAfterFeeFailure(
isHardwarePayment: true,
Expand Down
42 changes: 42 additions & 0 deletions BitkitTests/SendConfirmationSwipeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,48 @@ final class SendConfirmationSwipeTests: XCTestCase {
XCTAssertNil(SendConfirmationView.hardwareWalletCovering(amount: 300_000, savingsBalanceSats: 209_714, balances: []))
}

func testAFixedAmountSavingsCannotPayMovesToTheLargestHardwareWallet() {
// The first wallet also covers the amount, but has less room for the fee.
let balances: [(walletId: String, balanceSats: UInt64)] = [("smaller", 300_100), ("larger", 549_577)]
XCTAssertEqual(
SendConfirmationView.hardwareWalletCovering(amount: 300_000, savingsBalanceSats: 0, balances: balances),
"larger"
)
}

func testAFailedPreviewOfTheSavingsFallbackWalletIsInsufficientSavingsOnlyWhenTheFeeDoesNotFit() {
func isShort(
fallback: String?,
wallet: String?,
amount: UInt64,
balance: UInt64 = 100_000,
reserve: UInt64 = 1200,
errorDetail: String? = "Electrum connection failed: Failed to connect to Electrum: Connection refused (os error 61)"
) -> Bool {
SendConfirmationView.isSavingsFallbackShortOfFee(
fallbackWalletId: fallback,
walletId: wallet,
previewErrorDetail: errorDetail,
amountSats: amount,
balanceSats: balance,
feeReserveSats: reserve
)
}
XCTAssertTrue(isShort(fallback: "trezor", wallet: "trezor", amount: 99970))
XCTAssertTrue(isShort(fallback: "trezor", wallet: "trezor", amount: 1000, balance: 1100))
// The fee fits, so the preview failed for another reason, such as Electrum being unreachable.
XCTAssertFalse(isShort(fallback: "trezor", wallet: "trezor", amount: 50000))
XCTAssertFalse(isShort(fallback: "trezor", wallet: "trezor", amount: 98800))
// Many inputs can need more than the reserve; the compose then reports the shortfall itself.
let shortfall = "Insufficient funds: 100000 sat available of 101310 sat needed"
XCTAssertTrue(isShort(fallback: "trezor", wallet: "trezor", amount: 98000, errorDetail: shortfall))
XCTAssertFalse(isShort(fallback: nil, wallet: "trezor", amount: 98000, errorDetail: shortfall))
// A source the user picked, or none, keeps the Try again handling.
XCTAssertFalse(isShort(fallback: nil, wallet: "trezor", amount: 99970))
XCTAssertFalse(isShort(fallback: "trezor", wallet: "jade", amount: 99970))
XCTAssertFalse(isShort(fallback: nil, wallet: nil, amount: 99970))
}

func testACoinSelectionFailureWithEnoughSavingsDoesNotMoveToAHardwareWallet() {
let balances: [(walletId: String, balanceSats: UInt64)] = [("large", 549_577)]
XCTAssertNil(SendConfirmationView.hardwareWalletCovering(amount: 10000, savingsBalanceSats: 209_714, balances: balances))
Expand Down
1 change: 1 addition & 0 deletions changelog.d/next/1228.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Scanning an on-chain request a hardware wallet's balance covers, but not with the network fee, now shows Insufficient Savings and closes the sheet instead of a Try again toast on Confirm.
3 changes: 2 additions & 1 deletion journeys/hardware-wallet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ Several journeys mutate pairing state. Run them in this order, or re-pair betwee
1. `connect-home-tile.xml` — pairs the emulator; every other journey assumes it ran.
2. `settings-hardware-wallets.xml`, `connect-flow.xml`, `suggestion-intro-sheet.xml` — each forgets
and re-pairs the device, ending paired.
3. `activity-blue-icons.xml`, `activity-detail-hw-tags.xml`, `reconnect.xml`, `send-onchain.xml`.
3. `activity-blue-icons.xml`, `activity-detail-hw-tags.xml`, `reconnect.xml`, `send-onchain.xml`,
`scan-onchain-amount-over-spendable.xml`.
4. `passphrase-pairing.xml` → `passphrase-duplicate.xml` → `passphrase-settings-remove.xml`.
5. `detail-overview.xml` **last** — its final step forgets the device.

Expand Down
22 changes: 22 additions & 0 deletions journeys/hardware-wallet/scan-onchain-amount-over-spendable.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<journey name="scan onchain amount over hardware spendable">
<description>
Verifies that an on-chain BIP21 request whose amount a paired hardware wallet's balance covers,
but not once the network fee is taken, shows the Insufficient Savings toast and closes the Send
sheet, instead of leaving the Confirm screen on the hardware wallet with a Try again toast and a
disabled swipe. Nothing is broadcast.
Precondition: an onboarded dev wallet with 0 sats in Savings and a paired Bridge emulator (see
README.md) whose native-segwit account holds a confirmed regtest balance B of at least 10 000
sats, read from its home tile. Use an amount between B minus 100 sats and B, which the balance
covers but the balance minus any non-zero fee does not, and a regtest address the wallet does
not own. Start on the wallet home screen.
iOS opens the Confirm screen (id "SendConfirm") while it checks the funding sources, so the sheet
may show briefly before it closes; Android shows the toast without opening Confirm.
</description>
<actions>
<action>Read the paired Trezor's balance B from its home tile (id "ActivityHardware") and pick an amount A with B - 100 &lt; A &lt; B, written in BTC</action>
<action>Run xcrun simctl openurl &lt;UDID&gt; "bitcoin:&lt;regtest address&gt;?amount=&lt;A&gt;"</action>
<action>Verify within 30 seconds the Insufficient Savings toast (id "InsufficientSavingsToast") appears (screenshot), the Send sheet closes back to the wallet home screen, and no "Please try again" toast is shown</action>
<action>Pick an amount below B by at least 2 000 sats and run the same openurl command with it</action>
<action>Verify the Confirm screen opens with the Trezor as the funding source (Show Details, id "SendConfirmAssetButton"), a non-zero network fee and an enabled swipe (id "GRAB"); close the sheet without sending</action>
</actions>
</journey>
Loading