diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 6d2e09aa8..dfd78bd1e 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -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? @@ -844,6 +846,7 @@ struct SendConfirmationView: View { } private func selectFundingSource(_ source: SendFundingSource) { + savingsFallbackWalletId = nil switch source { case .usdt: navigationPath = amountIsRoot ? [] : [.amount] @@ -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 + } + + /// 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 } /// Only the newest fee calculation can hold the swipe, so a calculation superseded by a funding switch never leaves it disabled. @@ -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) @@ -2134,6 +2159,7 @@ struct SendConfirmationView: View { satsPerVByte: UInt64(feeRate) ) else { return } apply(fee) + savingsFallbackWalletId = nil return } @@ -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, diff --git a/BitkitTests/SendConfirmationSwipeTests.swift b/BitkitTests/SendConfirmationSwipeTests.swift index d7ebce872..212198911 100644 --- a/BitkitTests/SendConfirmationSwipeTests.swift +++ b/BitkitTests/SendConfirmationSwipeTests.swift @@ -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)) diff --git a/changelog.d/next/1228.fixed.md b/changelog.d/next/1228.fixed.md new file mode 100644 index 000000000..b94227a1e --- /dev/null +++ b/changelog.d/next/1228.fixed.md @@ -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. diff --git a/journeys/hardware-wallet/README.md b/journeys/hardware-wallet/README.md index 8916a48d2..8b70b600e 100644 --- a/journeys/hardware-wallet/README.md +++ b/journeys/hardware-wallet/README.md @@ -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. diff --git a/journeys/hardware-wallet/scan-onchain-amount-over-spendable.xml b/journeys/hardware-wallet/scan-onchain-amount-over-spendable.xml new file mode 100644 index 000000000..0930bf5bd --- /dev/null +++ b/journeys/hardware-wallet/scan-onchain-amount-over-spendable.xml @@ -0,0 +1,22 @@ + + + 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. + + + Read the paired Trezor's balance B from its home tile (id "ActivityHardware") and pick an amount A with B - 100 < A < B, written in BTC + Run xcrun simctl openurl <UDID> "bitcoin:<regtest address>?amount=<A>" + 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 + Pick an amount below B by at least 2 000 sats and run the same openurl command with it + 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 + +