diff --git a/Bitkit.xcodeproj/project.pbxproj b/Bitkit.xcodeproj/project.pbxproj index 39daf2e7cf..482f088e21 100644 --- a/Bitkit.xcodeproj/project.pbxproj +++ b/Bitkit.xcodeproj/project.pbxproj @@ -1278,7 +1278,7 @@ repositoryURL = "https://github.com/synonymdev/bitkit-core"; requirement = { kind = exactVersion; - version = "0.8.0-rc11"; + version = "0.8.0-spark.3"; }; }; 96E493A22C942FD1000E8BC2 /* XCRemoteSwiftPackageReference "swift-secp256k1" */ = { diff --git a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 73abd5e0e2..0a523f43b6 100644 --- a/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Bitkit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -6,8 +6,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/synonymdev/bitkit-core", "state" : { - "revision" : "22e0acc31a97b65205e71f4190cfc659fdecd3ca", - "version" : "0.8.0-rc11" + "revision" : "ac704166d07935e393f3bcf363959b83f0ed3445", + "version" : "0.8.0-spark.3" } }, { diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index d663771d28..29386d23bc 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -14,6 +14,8 @@ import Observation @Observable @MainActor final class SparkManager: ChannelFreeLightningRail { static let shared = SparkManager() + nonisolated static let routeService = "spark" + private nonisolated static let routeAtomicity = "trusted" private nonisolated(unsafe) static let exitStateChanged = PassthroughSubject() private nonisolated static let exitStateLock = NSLock() private nonisolated(unsafe) static var exitStateGenerationValue = 0 @@ -29,6 +31,15 @@ final class SparkManager: ChannelFreeLightningRail { exitStateChanged.send() } + private nonisolated(unsafe) static let contactWithdrawalResolutionSubject = PassthroughSubject() + /// How each contact withdrawal's journal closes, which a pending send screen waits on. + static var contactWithdrawalResolutionPublisher: AnyPublisher { + contactWithdrawalResolutionSubject.eraseToAnyPublisher() + } + + /// The latest journal close in this process, for a pending screen that opens after it; a new journal clears it. + private(set) static var lastContactWithdrawalResolution: SparkContactWithdrawalResolution? + /// Fires once Spark connects and whenever its unilateral exit data changes, so the exit data backup is redone. nonisolated static var exitStateChangedPublisher: AnyPublisher { exitStateChanged.eraseToAnyPublisher() @@ -81,6 +92,8 @@ final class SparkManager: ChannelFreeLightningRail { /// The refresh in flight; callers during it wait for it, and it reads once more for them. @ObservationIgnored private var refreshTask: Task? @ObservationIgnored private var refreshAgain = false + /// A contact withdrawal is being sent, so its journal entry isn't settled from a list that can't show it yet. + @ObservationIgnored private var isWithdrawingToContact = false /// Set once a full activity sync succeeded in this process; `wipe` clears it. @ObservationIgnored private var activitiesSynced = false @@ -154,6 +167,7 @@ final class SparkManager: ChannelFreeLightningRail { }, syncActivities: { try await syncActivities() } ) + await settleContactWithdrawal(allowClear: false) } catch { connectTask = nil Logger.error("Failed to start Spark wallet: \(error)", context: "SparkManager") @@ -270,6 +284,8 @@ final class SparkManager: ChannelFreeLightningRail { unsavedPayments = [] sentWithdrawalTxIds = [] preparedWithdrawal = nil + Self.pendingContactWithdrawal = nil + Self.contactWithdrawalTxIds = [] onStateChanged?() try Self.removeIfPresent(Env.sparkStorage(walletIndex: walletIndex)) try Self.removeIfPresent(Env.sparkExitRestore(walletIndex: walletIndex)) @@ -564,6 +580,32 @@ final class SparkManager: ChannelFreeLightningRail { sent.contains(txid) || withdrawals.contains { $0.txid == txid } } + /// Whether `txid` is a Spark withdrawal, which LDK never held and so can't boost: one this app sent, to Savings or a + /// contact, or one Spark lists. + func isSparkWithdrawal(txid: String, isSent: Bool) async -> Bool { + let known = sentWithdrawalTxIds.union(Self.contactWithdrawalTxIds).union(withdrawals.map(\.txid)) + if Self.isSparkWithdrawal(txid: txid, isSent: isSent, known: known, payments: []) { + return true + } + guard isReady else { return false } + do { + let payments = try await requireSdk().listPayments(request: ListPaymentsRequest(sortAscending: false)).payments + return Self.isSparkWithdrawal(txid: txid, isSent: isSent, known: known, payments: payments) + } catch { + Logger.warn("Failed to list Spark payments for \(txid): \(error)", context: "SparkManager") + return false + } + } + + nonisolated static func isSparkWithdrawal(txid: String, isSent: Bool, known: Set, payments: [Payment]) -> Bool { + // Only the sent side was Spark's; Savings owns the output a withdrawal to it pays, so its receipt can be boosted. + guard isSent else { return false } + return known.contains(txid) || payments.contains { payment in + guard case let .withdraw(txId, _, _) = payment.details else { return false } + return txId == txid + } + } + /// Reuses the provider's withdrawal quote while it holds for the same address and balance, so the withdrawal /// pays the fee the confirm screen showed; a second full-balance quote can take minutes. private func prepareWithdrawAll(to address: String) async throws -> PrepareSendPaymentResponse { @@ -580,6 +622,457 @@ final class SparkManager: ChannelFreeLightningRail { return response } + /// A Paykit route that withdraws exactly `amountSats` to the contact's on-chain `endpoint` at medium speed, with + /// Spark's fee on top, or nil while Spark cannot send it. bitkit-core's Paykit router weighs it against the contact's + /// other endpoints. Throws `SparkLegUnaffordable` when the balance can't cover the amount and its fee. + func withdrawalRouteLeg(endpoint: PaykitEndpoint, amountSats: UInt64) async throws -> ServiceRouteLeg? { + guard isReady else { return nil } + guard balanceSats >= amountSats else { throw SparkLegUnaffordable(debitSats: amountSats, balanceSats: balanceSats) } + let prepared = try await prepareSend(paymentRequest: endpoint.value, amountSats: amountSats) + guard case let .bitcoinAddress(_, feeQuote) = prepared.paymentMethod else { + throw AppError(message: "Unexpected Spark payment method", debugMessage: "\(prepared.paymentMethod)") + } + guard !feeQuote.isEstimate else { return nil } + return try Self.withdrawalRouteLeg( + endpoint: endpoint, + amountSats: amountSats, + fee: feeQuote.speedMedium, + validUntilUnix: feeQuote.expiresAt, + balanceSats: balanceSats + ) + } + + /// The leg that withdraws `amountSats` to `endpoint` with `fee` on top. Throws `SparkLegUnaffordable` when + /// `balanceSats` can't cover both. + nonisolated static func withdrawalRouteLeg( + endpoint: PaykitEndpoint, + amountSats: UInt64, + fee: SendOnchainSpeedFeeQuote, + validUntilUnix: UInt64, + balanceSats: UInt64 + ) throws -> ServiceRouteLeg { + let debitSats = withdrawalDebitSats(amountSats: amountSats, fee: fee) + guard balanceSats >= debitSats else { throw SparkLegUnaffordable(debitSats: debitSats, balanceSats: balanceSats) } + return ServiceRouteLeg( + service: routeService, + endpoint: endpoint, + deliveredSat: amountSats, + debitSat: debitSats, + atomicity: routeAtomicity, + validUntilUnix: validUntilUnix + ) + } + + /// What a withdrawal of `amountSats` takes from the balance: the amount, Spark's fee and the L1 broadcast fee. + nonisolated static func withdrawalDebitSats(amountSats: UInt64, fee: SendOnchainSpeedFeeQuote) -> UInt64 { + amountSats.saturatingAdd(fee.userFeeSat).saturatingAdd(fee.l1BroadcastFeeSat) + } + + /// Withdraws exactly `amountSats` to a contact's on-chain `address` at medium speed and returns its txid. The + /// withdrawal is written to a journal before it is sent, so one interrupted mid-send settles from Spark's payment + /// list; a second one is refused while it is open. It is recorded as a sent on-chain activity for the contact. + /// A withdrawal that pays a Paykit request (`request`) completes the request's on-chain proof with its txid, also when + /// it settles from the journal. `beforeSend` runs right before Spark sends, after the quote. + func withdraw( + to address: String, + amountSats: UInt64, + contact: String?, + request: SparkContactWithdrawal.PaykitRequest? = nil, + tags: [String] = [], + maxFeeSats: UInt64? = nil, + paymentDeadline: PaykitPreciseInstant? = nil, + beforeSend: () async throws -> Void = {} + ) async throws -> String { + // Everything before the journal is written sends nothing, so a refusal here says so to the caller. + let sdk: BreezSdk + let prepared: PrepareSendPaymentResponse + let earlierPayments: [Payment] + do { + try claimContactWithdrawal() + } catch { + throw SparkWithdrawalNotSent(underlying: error) + } + defer { releaseContactWithdrawalClaim() } + do { + sdk = try await requireSdk() + prepared = try await prepareSend(paymentRequest: address, amountSats: amountSats) + if let maxFeeSats, case let .bitcoinAddress(_, feeQuote) = prepared.paymentMethod { + // The fee Confirm showed caps the one sent, broadcast fee included. + try Self.checkWithdrawalFee( + Self.withdrawalDebitSats(amountSats: amountSats, fee: feeQuote.speedMedium) - amountSats, + shownFeeSats: maxFeeSats + ) + } + // Withdrawals Spark already lists for this address and amount belong to earlier attempts, so recovery never + // takes one of them for this attempt. + earlierPayments = try await sdk.listPayments(request: ListPaymentsRequest(sortAscending: false)).payments + } catch { + throw SparkWithdrawalNotSent(underlying: error) + } + var pending = SparkContactWithdrawal( + address: address, + amountSats: amountSats, + contact: contact, + startedAt: UInt64(Date().timeIntervalSince1970), + request: request, + tags: tags, + earlierPaymentIds: Self.withdrawalIds(to: address, amountSats: amountSats, in: earlierPayments), + idempotencyKey: UUID().uuidString.lowercased() + ) + let journaled = pending + try await Self.startJournaledWithdrawal( + writeJournal: { + Self.pendingContactWithdrawal = journaled + Self.lastContactWithdrawalResolution = nil + }, + beforeSend: beforeSend, + closeUnsent: { + await Self.closeUnsentWithdrawal(journaled, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) + }, + paymentDeadline: paymentDeadline + ) + let response: SendPaymentResponse + do { + response = try await sdk.sendPayment(request: SendPaymentRequest( + prepareResponse: prepared, + options: .bitcoinAddress(confirmationSpeed: .medium), + idempotencyKey: pending.idempotencyKey + )) + } catch { + throw await Self.withdrawalSendFailure( + error, + closeUnsent: { + await Self.closeUnsentWithdrawal(journaled, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) + }, + settleLater: { + let failedAt = UInt64(Date().timeIntervalSince1970) + Task { + await Self.settleAfterFailedWithdrawal( + failedAt: failedAt, + syncWallet: { + _ = try await self.requireSdk().syncWallet(request: SyncWalletRequest()) + self.syncedThisRun = true + }, + hasSynced: { await self.hasSynced(after: $0) }, + settle: { await self.settleContactWithdrawal(allowClear: $0) } + ) + } + } + ) + } + Logger.info("Sent Spark withdrawal '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") + pending.paymentId = response.payment.id + Self.pendingContactWithdrawal = pending + if case let .withdraw(txId, _, _) = response.payment.details { + await recordContactWithdrawal(response.payment, txId: txId, pending: pending) + } + await refreshState() + return try Self.sentWithdrawalId(response.payment) + } + + /// Claims the one contact withdrawal slot before anything awaits, so a second send started meanwhile is refused + /// instead of overwriting the first one's journal. + func claimContactWithdrawal() throws { + guard Self.pendingContactWithdrawal == nil, !isWithdrawingToContact else { + throw AppError(message: "wallet__payment_failed_description", debugMessage: "A Spark withdrawal to a contact is still settling") + } + isWithdrawingToContact = true + } + + func releaseContactWithdrawalClaim() { + isWithdrawingToContact = false + } + + /// What `withdraw` returns for the payment Spark sent: its txid, or its id while Spark gives none yet. A withdrawal + /// Spark returned as failed paid nothing, so the call ends as a refusal: the caller releases the request's proof, + /// private list and allowance attempt and shows a failure, never a success. One still pending can fail until the + /// provider accepts its payout, so the caller holds it as unknown, on the pending screen, until its journal settles. + nonisolated static func sentWithdrawalId(_ payment: Payment) throws -> String { + guard payment.status != .failed else { + throw SparkWithdrawalNotSent(underlying: AppError( + message: "wallet__payment_failed_description", + debugMessage: "Spark returned withdrawal '\(payment.id)' as failed" + )) + } + guard payment.status == .completed else { + throw AppError(message: "wallet__payment_failed_description", debugMessage: "Spark withdrawal '\(payment.id)' is still pending") + } + guard case let .withdraw(txId, _, _) = payment.details else { return payment.id } + return txId + } + + /// What a failed `sendPayment` of a journaled withdrawal means. A refusal Spark makes before anything reaches the + /// operators, as on the Lightning rail, closes the journal at once; an outcome that may have sent it stays journaled + /// and settles from the sync after it. + static func withdrawalSendFailure( + _ error: Error, + closeUnsent: () async -> Void, + settleLater: () -> Void + ) async -> Error { + let failure = sendPaymentFailure(error) + if failure is ChannelFreeRailSendRefused || isWithdrawalFeeRise(error) { + Logger.warn("Spark refused a withdrawal to a contact before sending it: \(error)", context: "SparkManager") + await closeUnsent() + return SparkWithdrawalNotSent(underlying: failure) + } + Logger.warn("Spark withdrawal to a contact failed or its outcome is unknown: \(error)", context: "SparkManager") + settleLater() + return error + } + + /// Spark refetches a withdrawal's quote near its expiry and refuses one whose fee rose past the prepared one at every + /// speed with this input error, before it withdraws (`affordable_speed` in the 0.28.0 SDK's `send/bitcoin_address.rs`). + nonisolated static func isWithdrawalFeeRise(_ error: Error) -> Bool { + guard case let SdkError.InvalidInput(message) = error else { return false } + return message.localizedCaseInsensitiveContains("onchain fee rose to") + } + + /// Settles the open contact withdrawal from Spark's payments: its own payment, once Spark returned it, or else a + /// withdrawal to its address and amount that wasn't listed before it started. With `allowClear` (after a sync that + /// succeeded), a list without one closes it as never sent and releases the request's proof, but only once the + /// attempt is past `contactWithdrawalExpirySecs`, so a withdrawal Spark hasn't listed yet is never dropped. One still + /// in flight in this process is never settled. + func settleContactWithdrawal(allowClear: Bool, now: UInt64 = UInt64(Date().timeIntervalSince1970)) async { + guard let pending = Self.pendingContactWithdrawal, !isWithdrawingToContact, + let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest(sortAscending: false)).payments + else { return } + let payment = Self.matchingWithdrawal(pending, in: payments) + if let payment, case let .withdraw(txId, _, _) = payment.details { + await recordContactWithdrawal(payment, txId: txId, pending: pending) + } else if allowClear, Self.canCloseUnlisted(pending, listed: payment, now: now) { + Logger.info("Closed a Spark contact withdrawal Spark never listed", context: "SparkManager") + await Self.closeUnsentWithdrawal(pending, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) + } + } + + /// Settles a withdrawal whose send failed or has an unknown outcome from the sync after it. That sync returns even + /// when it never reached Spark, so only one that completed after `failedAt` may close an unlisted one as unsent. + static func settleAfterFailedWithdrawal( + failedAt: UInt64, + syncWallet: () async throws -> Void, + hasSynced: (UInt64) async -> Bool, + settle: (_ allowClear: Bool) async -> Void + ) async { + guard await (try? syncWallet()) != nil else { return } + await settleAfterSync(since: failedAt, hasSynced: hasSynced, settle: settle) + } + + /// Spark reports a sync that never reached it as done too, its `.synced` event included, so only one that completed + /// after `since` may close an unlisted withdrawal as unsent. + static func settleAfterSync( + since: UInt64, + hasSynced: (UInt64) async -> Bool, + settle: (_ allowClear: Bool) async -> Void + ) async { + let synced = await hasSynced(since) + await settle(synced) + } + + /// Writes the attempt's journal before `beforeSend` starts the request's proof, so a kill between the two leaves a + /// journal that recovery closes as unsent once it expires, releasing the proof; a refusal in `beforeSend`, or a + /// `paymentDeadline` passed by then, closes it at once, releasing what it started. + static func startJournaledWithdrawal( + writeJournal: () -> Void, + beforeSend: () async throws -> Void, + closeUnsent: () async -> Void, + paymentDeadline: PaykitPreciseInstant? = nil, + now: () -> Date = Date.init + ) async throws { + writeJournal() + do { + try await beforeSend() + // A quote can expire while the request and its allowance are checked, so it is checked last. + try PaykitPaymentRequest.checkPaymentDeadline(paymentDeadline, at: now()) + } catch { + await closeUnsent() + throw SparkWithdrawalNotSent(underlying: error) + } + } + + nonisolated static let contactWithdrawalExpirySecs: UInt64 = 600 + + /// An attempt Spark never returned nor listed is taken as unsent only after the expiry. Spark can list its payment + /// without withdrawal details while the payout may still go out, so only one it failed is unsent too. + nonisolated static func canCloseUnlisted(_ pending: SparkContactWithdrawal, listed: Payment? = nil, now: UInt64) -> Bool { + pending.paymentId == nil && (listed?.status ?? .failed) == .failed && now >= pending.startedAt + contactWithdrawalExpirySecs + } + + /// The attempt's own payment, by the id Spark returned or the idempotency key it keeps as the id, also while Spark + /// lists it without withdrawal details; else, for one Spark never returned, a new withdrawal to its address and amount. + nonisolated static func matchingWithdrawal(_ pending: SparkContactWithdrawal, in payments: [Payment]) -> Payment? { + if let ownId = pending.paymentId ?? pending.idempotencyKey, let own = payments.first(where: { $0.id == ownId }) { + return own + } + guard pending.paymentId == nil else { return nil } + let earlier = Set(pending.earlierPaymentIds ?? []) + return payments.first { payment in + !earlier.contains(payment.id) && withdrawalIds(to: pending.address, amountSats: pending.amountSats, in: [payment]) == [payment.id] + } + } + + nonisolated static func withdrawalIds(to address: String, amountSats: UInt64, in payments: [Payment]) -> [String] { + payments.compactMap { payment in + guard payment.paymentType == .send, case let .withdraw(_, _, destination) = payment.details, + destination == address, sats(payment.amount) == amountSats + else { return nil } + return payment.id + } + } + + /// What an open withdrawal's journal does with the payment Spark returned or lists for it. Spark keeps a withdrawal + /// pending until the provider accepts its payout, and one it never accepts still fails, so only a completed one paid. + nonisolated static func settlement(of status: BreezSdkSpark.PaymentStatus) -> SparkWithdrawalSettlement { + switch status { + case .completed: .record + case .failed: .closeUnsent + case .pending: .wait + } + } + + /// Writes the withdrawal's sent activity, tags and request proof, and closes the journal only once all of them are + /// saved, so a failed or interrupted write is retried from the journal. + private func recordContactWithdrawal(_ payment: Payment, txId: String, pending: SparkContactWithdrawal) async { + // A settle that raced this one already saved everything; its request's proof and allowance may be a retry's now. + guard Self.isOpenJournal(pending) else { return } + switch Self.settlement(of: payment.status) { + case .wait: + return + case .closeUnsent: + await Self.closeUnsentWithdrawal(pending, releaseProof: Self.releaseUnsentProof, failAllowance: Self.failAllowance) + return + case .record: + break + } + Self.contactWithdrawalTxIds.insert(txId) + let isDurable = await Self.recordWithdrawalLocally( + saveProof: { + guard let request = pending.request else { return true } + return await PaykitPaymentProofService.shared.completeSparkOnchainPayment( + requestId: request.id, + identity: request.identity, + txid: txId + ) + }, + saveActivity: { + await CoreService.shared.activity.createSentOnchainActivityFromSendResult( + txid: txId, + address: pending.address, + amount: pending.amountSats, + fee: Self.sats(payment.fees), + feeRate: 0, + contact: pending.contact, + feeIsExact: true + ) + }, + saveTags: { + guard let tags = pending.tags, !tags.isEmpty else { return true } + return await (try? CoreService.shared.activity.appendTags(toActivity: txId, tags)) != nil + } + ) + Self.confirmMinedContactPayouts(Self.completedContactPayouts([payment], contactWithdrawals: [txId])) + if isDurable { + if let request = pending.request { + await PaykitAllowanceExecutor.shared.settleManualPayment(requestId: request.id, outcome: .succeeded, transactionId: txId) + } + if Self.clearJournal(pending) { + Self.resolveContactWithdrawal(pending, txId: txId) + } + } else { + Logger.warn("Kept the Spark contact withdrawal journal: its local records are not all saved yet", context: "SparkManager") + } + } + + /// Closes the journal of a withdrawal that never went out, but only once its request's started proof is released: + /// a proof left behind would block the request, so the journal stays for the next sync to retry. The request's + /// allowance attempt, left unknown when the send's outcome was, then fails, so the ledger lets it be paid again. + static func closeUnsentWithdrawal( + _ pending: SparkContactWithdrawal, + releaseProof: (SparkContactWithdrawal.PaykitRequest, _ failAllowance: () async -> Bool) async -> SparkProofRelease, + failAllowance: @escaping (SparkContactWithdrawal.PaykitRequest) async -> Bool + ) async { + // The proof and allowance attempt match by request, so a stale close would release a retry's. + guard isOpenJournal(pending) else { return } + // The allowance attempt begins only once the proof started, so only a started proof fails one, and it fails + // before that proof goes, so a restart in between still finds the proof to settle it from. + if let request = pending.request, await releaseProof(request, { await failAllowance(request) }) == .failed { + Logger.warn("Kept the Spark contact withdrawal journal: its unsent proof is not released yet", context: "SparkManager") + return + } + if clearJournal(pending) { + resolveContactWithdrawal(pending, txId: nil) + } + } + + nonisolated static func isOpenJournal(_ pending: SparkContactWithdrawal) -> Bool { + pendingContactWithdrawal == pending + } + + /// Clears `pending`'s journal only while it is still the open one, so a stale recovery never drops a newer + /// withdrawal's journal, which could then be paid twice. Returns whether it cleared it: only then is the resolution + /// this attempt's to publish, since a retry of the same request shares its attempt. + nonisolated static func clearJournal(_ pending: SparkContactWithdrawal) -> Bool { + guard isOpenJournal(pending) else { return false } + pendingContactWithdrawal = nil + return true + } + + static func resolveContactWithdrawal(_ pending: SparkContactWithdrawal, txId: String?) { + let resolution = SparkContactWithdrawalResolution(attempt: pending.attempt, txId: txId) + lastContactWithdrawalResolution = resolution + contactWithdrawalResolutionSubject.send(resolution) + } + + private static func releaseUnsentProof( + _ request: SparkContactWithdrawal.PaykitRequest, + failAllowance: () async -> Bool + ) async -> SparkProofRelease { + await PaykitPaymentProofService.shared.failSparkOnchainPayment( + requestId: request.id, + identity: request.identity, + unstartedPaymentList: request.paymentList, + settleAllowance: failAllowance + ) + } + + private static func failAllowance(_ request: SparkContactWithdrawal.PaykitRequest) async -> Bool { + await PaykitAllowanceExecutor.shared.settleManualPayment(requestId: request.id, outcome: .failed) + } + + /// Saves the proof, then the activity, then its tags; true only when every write succeeded. + static func recordWithdrawalLocally( + saveProof: () async -> Bool, + saveActivity: () async -> Bool, + saveTags: () async -> Bool + ) async -> Bool { + let proofSaved = await saveProof() + let activitySaved = await saveActivity() + let tagsSaved = activitySaved ? await saveTags() : false + return proofSaved && activitySaved && tagsSaved + } + + private nonisolated static let pendingContactWithdrawalKey = "sparkPendingContactWithdrawal" + private nonisolated static let contactWithdrawalTxIdsKey = "sparkContactWithdrawalTxIds" + + nonisolated static var pendingContactWithdrawal: SparkContactWithdrawal? { + get { + UserDefaults.standard.data(forKey: pendingContactWithdrawalKey) + .flatMap { try? JSONDecoder().decode(SparkContactWithdrawal.self, from: $0) } + } + set { + if let newValue, let data = try? JSONEncoder().encode(newValue) { + UserDefaults.standard.set(data, forKey: pendingContactWithdrawalKey) + } else { + UserDefaults.standard.removeObject(forKey: pendingContactWithdrawalKey) + } + } + } + + /// Withdrawals paid to contacts, which stay sent payments rather than transfers to Savings. + nonisolated static var contactWithdrawalTxIds: Set { + get { Set(UserDefaults.standard.stringArray(forKey: contactWithdrawalTxIdsKey) ?? []) } + set { UserDefaults.standard.set(Array(newValue), forKey: contactWithdrawalTxIdsKey) } + } + /// What a unilateral exit needs if the Spark operators stop cooperating; it can reach several MB. func exportExitState() async throws -> String { try await requireSdk().exportUnilateralExitState().exitState @@ -756,9 +1249,71 @@ final class SparkManager: ChannelFreeLightningRail { for payment in Self.paymentsToRecordAgain(payments, unsaved: unsavedPayments, recordedWithoutFee: sendsRecordedWithoutFee) { await recordActivity(payment) } - for txId in Self.transferTxIds(unclaimed: unclaimed, payments: payments) { + let contactWithdrawals = Self.contactWithdrawalTxIds + for txId in Self.savingsTransferTxIds(unclaimed: unclaimed, payments: payments, contactWithdrawals: contactWithdrawals) { await CoreService.shared.activity.markOnchainActivityAsTransfer(txId: txId) } + Self.confirmMinedContactPayouts(Self.completedContactPayouts(payments, contactWithdrawals: contactWithdrawals)) + } + + /// The output of a contact withdrawal's transaction that pays the contact. + struct ContactPayout: Equatable { + let txId: String + let vout: UInt32 + let address: String + } + + /// The payouts of the contact withdrawals Spark lists as completed. + nonisolated static func completedContactPayouts(_ payments: [Payment], contactWithdrawals: Set) -> [ContactPayout] { + payments.compactMap { payment in + guard payment.status == .completed, case let .withdraw(txId, vout, address) = payment.details, + contactWithdrawals.contains(txId) + else { return nil } + return ContactPayout(txId: txId, vout: vout, address: address) + } + } + + /// Looks the payouts up on chain off the refresh, so a slow Electrum server never holds a send that waits for it. + private static func confirmMinedContactPayouts(_ payouts: [ContactPayout]) { + guard !payouts.isEmpty else { return } + Task { + await confirmMinedPayouts( + payouts, + needsConfirmation: { txId in + await (try? CoreService.shared.activity.getOnchainActivityByTxId(txid: txId))?.confirmed == false + }, + unspentOutputs: { address in + try await OnChainHwService.shared.getAddressInfo( + address: address, + electrumUrl: OnChainHwService.getElectrumUrl(), + network: OnChainHwService.appDefaultCoinType + ).utxos + }, + markConfirmed: { await CoreService.shared.activity.markOnchainActivityAsConfirmed(txId: $0) } + ) + } + } + + /// Spark lists a withdrawal completed once its provider took the payout on, which can be before the payout transaction + /// is broadcast or mined, so a payout's activity is confirmed only once the chain lists its output in a block. An + /// output the contact already spent drops out of that list, so its activity then stays unconfirmed. + nonisolated static func confirmMinedPayouts( + _ payouts: [ContactPayout], + needsConfirmation: (String) async -> Bool, + unspentOutputs: (String) async throws -> [AccountUtxo], + markConfirmed: (String) async -> Void + ) async { + for payout in payouts { + guard await needsConfirmation(payout.txId) else { continue } + do { + let outputs = try await unspentOutputs(payout.address) + if outputs.contains(where: { $0.txid == payout.txId && $0.vout == payout.vout && $0.confirmations > 0 }) { + await markConfirmed(payout.txId) + } + } catch { + Logger.warn("Failed to look up the payout of Spark withdrawal '\(payout.txId)': \(error)", context: "SparkManager") + } + } } /// Whether balances and the receive invoice must follow a refresh: the read balance counts too, as sends use it, and @@ -801,13 +1356,23 @@ final class SparkManager: ChannelFreeLightningRail { return unclaimed.filter { !claimedOutputs.contains("\($0.txid.lowercased()):\($0.vout)") } } + /// Spark's withdrawals to Savings, without the ones that paid contacts: those recorded as sent, and the open + /// journal's, which Spark keeps pending until its payout is accepted. nonisolated static func withdrawals(_ payments: [Payment]) -> [SparkWithdrawal] { - payments.compactMap { payment in - guard payment.status != .failed, case let .withdraw(txId, _, _) = payment.details else { return nil } + let contactWithdrawals = contactWithdrawalTxIds + let journaledId = pendingContactWithdrawal.flatMap { matchingWithdrawal($0, in: payments)?.id } + return payments.compactMap { payment in + guard payment.status != .failed, payment.id != journaledId, case let .withdraw(txId, _, _) = payment.details, + !contactWithdrawals.contains(txId) else { return nil } return SparkWithdrawal(txid: txId, amountSats: sats(payment.amount), feeSats: sats(payment.fees)) } } + /// The transfers between Savings and Spark, without the withdrawals that paid contacts, which stay sends to them. + nonisolated static func savingsTransferTxIds(unclaimed: [DepositInfo], payments: [Payment], contactWithdrawals: Set) -> [String] { + transferTxIds(unclaimed: unclaimed, payments: payments).filter { !contactWithdrawals.contains($0) } + } + /// On-chain transactions that moved funds between Savings and Spark, so their activities show as transfers. nonisolated static func transferTxIds(unclaimed: [DepositInfo], payments: [Payment]) -> [String] { unclaimed.map(\.txid) + payments.compactMap { payment in @@ -921,6 +1486,11 @@ final class SparkManager: ChannelFreeLightningRail { syncedThisRun = true await LightningService.shared.listRailSendsIfUnseeded() await refreshState() + await Self.settleAfterSync( + since: Self.pendingContactWithdrawal?.startedAt ?? 0, + hasSynced: { await self.hasSynced(after: $0) }, + settle: { await self.settleContactWithdrawal(allowClear: $0) } + ) case .newDeposits, .claimedDeposits: await refreshState() case let .unclaimedDeposits(deposits): @@ -1168,6 +1738,76 @@ enum SparkErrorCopy { } } +/// A Spark withdrawal to a contact's on-chain address, journaled before it is sent. +/// A contact withdrawal refused before its journal was written: nothing was sent. +enum SparkWithdrawalSettlement: Equatable { + /// Paid: its records are saved and its journal closes. + case record + /// Never paid: its journal closes as unsent, releasing what it started. + case closeUnsent + /// Still in flight: its journal stays open until Spark settles it. + case wait +} + +struct SparkWithdrawalNotSent: Error { + let underlying: Error +} + +/// Spark's balance can't cover a contact withdrawal's amount and fee, so the route offers no Spark leg. +struct SparkLegUnaffordable: Error { + let debitSats: UInt64 + let balanceSats: UInt64 +} + +struct SparkContactWithdrawal: Codable, Equatable { + /// The Paykit request a withdrawal pays, and the identity its proof belongs to. + struct PaykitRequest: Codable, Equatable { + let id: PaykitPaymentRequest.ID + let identity: String + /// The contact's private list the request consumed, given back when the withdrawal never started its proof. + var paymentList: PaymentList? + } + + /// A private payment list version a send consumed, and the one before it. + struct PaymentList: Codable, Equatable { + let version: UInt64 + let previousVersion: UInt64? + } + + let address: String + let amountSats: UInt64 + let contact: String? + let startedAt: UInt64 + var request: PaykitRequest? + /// Tags picked on Confirm, saved on the sent activity. + var tags: [String]? + /// Withdrawals to the same address and amount Spark listed before this attempt; recovery skips them. + var earlierPaymentIds: [String]? + /// This attempt's Spark payment, once Spark returned it. + var paymentId: String? + /// The UUID the send passed as its idempotency key, which Spark keeps as the payment's id. + var idempotencyKey: String? +} + +/// One contact withdrawal, which a pending send screen follows until its journal closes. +struct SparkWithdrawalAttempt: Hashable { + let address: String + let amountSats: UInt64 + let requestId: PaykitPaymentRequest.ID? +} + +/// How a contact withdrawal's journal closed: sent with its txid, or never sent when `txId` is nil. +struct SparkContactWithdrawalResolution: Equatable { + let attempt: SparkWithdrawalAttempt + let txId: String? +} + +extension SparkContactWithdrawal { + var attempt: SparkWithdrawalAttempt { + SparkWithdrawalAttempt(address: address, amountSats: amountSats, requestId: request?.id) + } +} + struct SparkWithdrawal: Identifiable, Equatable { let txid: String let amountSats: UInt64 diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index c6fd65522c..fca7583af7 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -1069,6 +1069,9 @@ "wallet__send_sync_long_title" = "مشاكل\nالاتصال"; "wallet__send_sync_long_description" = "يبدو أنك غير متصل. يرجى التحقق من اتصالك. سيحاول Bitkit إعادة الاتصال كل بضع ثوانٍ."; "wallet__send_to" = "إلى"; +"wallet__send_swap_route" = "المسار"; +"wallet__send_paykit_no_route__title" = "تعذّر الدفع لجهة الاتصال هذه"; +"wallet__send_paykit_no_route__description" = "ليس لدى جهة الاتصال هذه طريقة دفع يمكن لـ Bitkit استخدامها حاليًا."; "wallet__recipient_contact" = "جهة الاتصال"; "wallet__recipient_invoice" = "لصق فاتورة"; "wallet__recipient_manual" = "إدخال يدوي"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index ca99075ca6..43a9d07bec 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1188,6 +1188,9 @@ "wallet__send_sync_long_title" = "Problemes de\nconnexió"; "wallet__send_sync_long_description" = "Sembla que estàs desconnectat. Comprova la connexió. Bitkit intentarà tornar a connectar-se cada pocs segons."; "wallet__send_to" = "A"; +"wallet__send_swap_route" = "Ruta"; +"wallet__send_paykit_no_route__title" = "No es pot pagar aquest contacte"; +"wallet__send_paykit_no_route__description" = "Aquest contacte no té cap mètode de pagament que Bitkit pugui fer servir ara mateix."; "wallet__recipient_contact" = "Contacte"; "wallet__recipient_invoice" = "Enganxa factura"; "wallet__recipient_manual" = "Introdueix manualment"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 45e0963f15..cef8cfd4c1 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1295,6 +1295,9 @@ "wallet__send_sync_long_title" = "Problémy\ns připojením"; "wallet__send_sync_long_description" = "Zdá se, že jste odpojeni. Zkontrolujte prosím připojení. Bitkit se bude každých několik sekund pokoušet znovu připojit."; "wallet__send_to" = "Komu"; +"wallet__send_swap_route" = "Trasa"; +"wallet__send_paykit_no_route__title" = "Tomuto kontaktu nelze zaplatit"; +"wallet__send_paykit_no_route__description" = "Tento kontakt teď nemá žádný platební způsob, který by Bitkit mohl použít."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Vložit fakturu"; "wallet__recipient_manual" = "Zadat ručně"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 7d09c7ed08..ffaf43a731 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1293,6 +1293,9 @@ "wallet__send_sync_long_title" = "Verbindungs-\nprobleme"; "wallet__send_sync_long_description" = "Anscheinend bist du nicht verbunden. Bitte überprüfe deine Verbindung. Bitkit versucht alle paar Sekunden, sich erneut zu verbinden."; "wallet__send_to" = "An"; +"wallet__send_swap_route" = "Route"; +"wallet__send_paykit_no_route__title" = "Zahlung an diesen Kontakt nicht möglich"; +"wallet__send_paykit_no_route__description" = "Dieser Kontakt hat derzeit keine Zahlungsmethode, die Bitkit nutzen kann."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Rechnung einfügen"; "wallet__recipient_manual" = "Manuell eingeben"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index d344927b35..b2ba14fd91 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -1087,6 +1087,9 @@ "wallet__send_sync_long_title" = "Προβλήματα\nσύνδεσης"; "wallet__send_sync_long_description" = "Φαίνεται ότι είστε αποσυνδεδεμένοι. Ελέγξτε τη σύνδεσή σας. Το Bitkit θα προσπαθεί να επανασυνδεθεί κάθε λίγα δευτερόλεπτα."; "wallet__send_to" = "Προς"; +"wallet__send_swap_route" = "Διαδρομή"; +"wallet__send_paykit_no_route__title" = "Δεν είναι δυνατή η πληρωμή αυτής της επαφής"; +"wallet__send_paykit_no_route__description" = "Αυτή η επαφή δεν έχει αυτή τη στιγμή κάποια μέθοδο πληρωμής που μπορεί να χρησιμοποιήσει το Bitkit."; "wallet__recipient_contact" = "Επαφή"; "wallet__recipient_invoice" = "Επικόλληση Τιμολογίου"; "wallet__recipient_manual" = "Χειροκίνητη Εισαγωγή"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index c3414587de..0705f67fce 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1310,6 +1310,10 @@ "wallet__send_sync_long_title" = "Connection\nissues"; "wallet__send_sync_long_description" = "It appears you’re disconnected. Please check your connection. Bitkit will try to reconnect every few seconds."; "wallet__send_to" = "To"; +"wallet__send_swap_route" = "Route"; +"wallet__send_paykit_no_route__title" = "Can't pay this contact"; +"wallet__send_paykit_no_route__description" = "This contact has no payment method Bitkit can use right now."; +"wallet__send_paykit_withdrawal_settling__description" = "An earlier withdrawal from your spending balance is still settling. Try again once it completes."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Paste Invoice"; "wallet__recipient_manual" = "Enter Manually"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index fdf238a2c7..614b579a73 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1298,6 +1298,9 @@ "wallet__send_sync_long_title" = "Problemas de\nconexión"; "wallet__send_sync_long_description" = "Parece que está desconectado. Revise su conexión. Bitkit intentará reconectarse cada pocos segundos."; "wallet__send_to" = "Para"; +"wallet__send_swap_route" = "Ruta"; +"wallet__send_paykit_no_route__title" = "No se puede pagar a este contacto"; +"wallet__send_paykit_no_route__description" = "Este contacto no tiene ningún método de pago que Bitkit pueda usar en este momento."; "wallet__recipient_contact" = "Contacto"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index 82239b63d5..0b7b7819b3 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1206,6 +1206,9 @@ "wallet__send_sync_long_title" = "Problemas de\nconexión"; "wallet__send_sync_long_description" = "Parece que está desconectado. Compruebe su conexión. Bitkit intentará reconectarse cada pocos segundos."; "wallet__send_to" = "Para"; +"wallet__send_swap_route" = "Ruta"; +"wallet__send_paykit_no_route__title" = "No se puede pagar a este contacto"; +"wallet__send_paykit_no_route__description" = "Este contacto no tiene ningún método de pago que Bitkit pueda usar ahora mismo."; "wallet__recipient_contact" = "Contactar"; "wallet__recipient_invoice" = "Pegar factura"; "wallet__recipient_manual" = "Introducir manualmente"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index 6b3d80fe8a..2591522790 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1306,6 +1306,9 @@ "wallet__send_sync_long_title" = "Problèmes de\nconnexion"; "wallet__send_sync_long_description" = "Il semble que vous soyez déconnecté. Veuillez vérifier votre connexion. Bitkit tentera de se reconnecter toutes les quelques secondes."; "wallet__send_to" = "Pour"; +"wallet__send_swap_route" = "Itinéraire"; +"wallet__send_paykit_no_route__title" = "Impossible de payer ce contact"; +"wallet__send_paykit_no_route__description" = "Ce contact n’a actuellement aucun moyen de paiement que Bitkit peut utiliser."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Coller la facture"; "wallet__recipient_manual" = "Entrer manuellement"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index e7b4928132..d04621d141 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1271,6 +1271,9 @@ "wallet__send_sync_long_title" = "Problemi di\nconnessione"; "wallet__send_sync_long_description" = "Sembra che tu sia disconnesso. Controlla la connessione. Bitkit proverà a riconnettersi ogni pochi secondi."; "wallet__send_to" = "A"; +"wallet__send_swap_route" = "Percorso"; +"wallet__send_paykit_no_route__title" = "Impossibile pagare questo contatto"; +"wallet__send_paykit_no_route__description" = "Al momento questo contatto non ha un metodo di pagamento che Bitkit possa usare."; "wallet__recipient_contact" = "Contatto"; "wallet__recipient_invoice" = "Incolla fattura"; "wallet__recipient_manual" = "Inserisci Manualmente"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index d2eb114167..d2a7a7a4f9 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1301,6 +1301,9 @@ "wallet__send_sync_long_title" = "Verbindings\nproblemen"; "wallet__send_sync_long_description" = "Het lijkt erop dat u niet verbonden bent. Controleer uw verbinding. Bitkit probeert om de paar seconden opnieuw verbinding te maken."; "wallet__send_to" = "Naar"; +"wallet__send_swap_route" = "Route"; +"wallet__send_paykit_no_route__title" = "Kan dit contact niet betalen"; +"wallet__send_paykit_no_route__description" = "Dit contact heeft op dit moment geen betaalmethode die Bitkit kan gebruiken."; "wallet__recipient_contact" = "Contact"; "wallet__recipient_invoice" = "Factuur Plakken"; "wallet__recipient_manual" = "Handmatig Invoeren"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index ddbfe5db75..ffa9e799b3 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1305,6 +1305,9 @@ "wallet__send_sync_long_title" = "Problemy\nz połączeniem"; "wallet__send_sync_long_description" = "Wygląda na to, że nie masz połączenia. Sprawdź połączenie. Bitkit będzie próbował połączyć się ponownie co kilka sekund."; "wallet__send_to" = "Do"; +"wallet__send_swap_route" = "Trasa"; +"wallet__send_paykit_no_route__title" = "Nie można zapłacić temu kontaktowi"; +"wallet__send_paykit_no_route__description" = "Ten kontakt nie ma obecnie żadnej metody płatności, której Bitkit może użyć."; "wallet__recipient_contact" = "Kontakt"; "wallet__recipient_invoice" = "Wklej fakturę"; "wallet__recipient_manual" = "Wprowadź ręcznie"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index 9c88717679..230392076c 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1306,6 +1306,9 @@ "wallet__send_sync_long_title" = "Problemas de\nconexão"; "wallet__send_sync_long_description" = "Parece que você está desconectado. Verifique sua conexão. A Bitkit tentará se reconectar a cada poucos segundos."; "wallet__send_to" = "Para"; +"wallet__send_swap_route" = "Rota"; +"wallet__send_paykit_no_route__title" = "Não é possível pagar este contato"; +"wallet__send_paykit_no_route__description" = "Este contato não tem nenhum método de pagamento que o Bitkit possa usar agora."; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index 693ffcadf3..1457e53197 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -1060,6 +1060,9 @@ "wallet__send_sync_long_title" = "Problemas\nde ligação"; "wallet__send_sync_long_description" = "Parece que está desligado. Verifique a sua ligação. A Bitkit vai tentar voltar a ligar a cada poucos segundos."; "wallet__send_to" = "Para"; +"wallet__send_swap_route" = "Rota"; +"wallet__send_paykit_no_route__title" = "Não é possível pagar a este contacto"; +"wallet__send_paykit_no_route__description" = "Este contacto não tem neste momento nenhum método de pagamento que a Bitkit possa usar."; "wallet__recipient_contact" = "Contato"; "wallet__recipient_invoice" = "Colar Invoice"; "wallet__recipient_manual" = "Inserir Manualmente"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index b1f825c5ce..3dcab32598 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1290,6 +1290,9 @@ "wallet__send_sync_long_title" = "Проблемы\nс подключением"; "wallet__send_sync_long_description" = "Похоже, вы отключены. Проверьте подключение. Bitkit будет пытаться переподключиться каждые несколько секунд."; "wallet__send_to" = "Кому"; +"wallet__send_swap_route" = "Маршрут"; +"wallet__send_paykit_no_route__title" = "Не удаётся оплатить этому контакту"; +"wallet__send_paykit_no_route__description" = "У этого контакта сейчас нет способа оплаты, который может использовать Bitkit."; "wallet__recipient_contact" = "Контакт"; "wallet__recipient_invoice" = "Вставить Инвойс"; "wallet__recipient_manual" = "Ввести Вручную"; diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 7f30aed58f..bd115b169b 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1495,6 +1495,24 @@ class ActivityService { } } + /// Marks a sent on-chain activity the node doesn't watch, such as a Spark withdrawal to a contact, as confirmed once + /// its sender reports it complete. + func markOnchainActivityAsConfirmed(txId: String) async { + do { + try await ServiceQueue.background(.core) { + guard let existing = try BitkitCore.getActivityByTxId(walletId: WalletScope.default, txId: txId), + !existing.confirmed + else { return } + var updated = existing + updated.confirmed = true + try updateActivity(activityId: existing.id, activity: .onchain(updated)) + self.activitiesChangedSubject.send() + } + } catch { + Logger.error("Failed to mark activity as confirmed for \(txId): \(error)", context: "ActivityService") + } + } + /// Marks the on-chain activity for `txId` as a transfer between Savings and Spending that has no channel, /// such as a Spark deposit or withdrawal. No-op until the activity exists or once it is marked. func markOnchainActivityAsTransfer(txId: String) async { diff --git a/Bitkit/Services/PaykitAllowanceExecutor.swift b/Bitkit/Services/PaykitAllowanceExecutor.swift index 3a743e6a9e..d69eb7eeb8 100644 --- a/Bitkit/Services/PaykitAllowanceExecutor.swift +++ b/Bitkit/Services/PaykitAllowanceExecutor.swift @@ -1358,8 +1358,10 @@ actor PaykitAllowanceExecutor { setStage(.sending, attemptId: attemptId, identity: identity) } - func finishManualPayment(attemptId: String, outcome: Paykit.PaymentOutcome, transactionId: String? = nil) async { - guard let identity = activeIdentity else { return } + /// Returns whether the outcome was recorded. + @discardableResult + func finishManualPayment(attemptId: String, outcome: Paykit.PaymentOutcome, transactionId: String? = nil) async -> Bool { + guard let identity = activeIdentity else { return false } if let transactionId { updateLocalState(identity: identity) { state in guard let index = state.journal.firstIndex(where: { $0.attemptId == attemptId }) else { return } @@ -1368,11 +1370,26 @@ actor PaykitAllowanceExecutor { } do { try await record(attemptId: attemptId, outcome: outcome, identity: identity) + return true } catch { Logger.warn("Failed to record a manual payment outcome: \(error)", context: "PaykitAllowance") + return false } } + /// Settles the manual attempt still open for a request once its outcome is learned later, as a Spark withdrawal's + /// journal learns it, so an unsent send no longer blocks the request on the ledger. + /// Returns whether no attempt is left open for the request. + @discardableResult + func settleManualPayment(requestId: PaykitPaymentRequest.ID, outcome: Paykit.PaymentOutcome, transactionId: String? = nil) async -> Bool { + guard let identity = activeIdentity else { return false } + guard let entry = localState(identity: identity).journal.last(where: { + !$0.isAutomatic && $0.requestId == requestId && !$0.stage.isTerminal + }) + else { return true } + return await finishManualPayment(attemptId: entry.attemptId, outcome: outcome, transactionId: transactionId) + } + // MARK: Helpers private func checks(_ request: PaykitPaymentRequest, endpointIdentifier: String, trustedTime: String) throws -> Paykit.PaymentExecutionChecks { diff --git a/Bitkit/Services/PaykitPaymentProofService.swift b/Bitkit/Services/PaykitPaymentProofService.swift index 710027e4b7..1681752454 100644 --- a/Bitkit/Services/PaykitPaymentProofService.swift +++ b/Bitkit/Services/PaykitPaymentProofService.swift @@ -76,6 +76,8 @@ struct PendingPaykitPaymentProof: Codable, Equatable { var onchainLocalFollowupComplete: Bool? /// Retain the bounded original proof until its payer consumes the local resolution. var onchainResolutionAwaitingConsumption: Bool? = false + /// A Spark withdrawal pays this proof, so only that withdrawal's journal may complete or drop it. + var sparkWithdrawal: Bool? var hasUnsupportedOnchainWallet: Bool { kind == .onchain && onchainWalletId != nil && onchainWalletId != WalletScope.default @@ -818,7 +820,8 @@ actor PaykitPaymentProofService { paymentIdentity: String? = nil, signedTx: HwFundingSignedTx? = nil, privatePaymentListVersion: UInt64? = nil, - previousPrivatePaymentListVersion: UInt64? = nil + previousPrivatePaymentListVersion: UInt64? = nil, + sparkWithdrawal: Bool = false ) async throws { let identity = try await currentIdentity() try await mutationLock.withLock { @@ -831,7 +834,8 @@ actor PaykitPaymentProofService { serializedTx: signedTx?.serializedTx, signedTx: signedTx, privatePaymentListVersion: privatePaymentListVersion, - previousPrivatePaymentListVersion: previousPrivatePaymentListVersion + previousPrivatePaymentListVersion: previousPrivatePaymentListVersion, + sparkWithdrawal: sparkWithdrawal ) } } @@ -845,7 +849,8 @@ actor PaykitPaymentProofService { serializedTx: String?, signedTx: HwFundingSignedTx?, privatePaymentListVersion: UInt64?, - previousPrivatePaymentListVersion: UInt64? + previousPrivatePaymentListVersion: UInt64?, + sparkWithdrawal: Bool = false ) async throws { if let hardwareWalletId { guard hardwareWalletId != WalletScope.default, hardwareTransactionLookup.hasWallet(walletId: hardwareWalletId) @@ -887,6 +892,7 @@ actor PaykitPaymentProofService { pendingProofs[index].hardwareDispatchAttempted = signedTx.map { _ in false } pendingProofs[index].privatePaymentListVersion = privatePaymentListVersion pendingProofs[index].previousPrivatePaymentListVersion = privatePaymentListVersion == nil ? nil : previousPrivatePaymentListVersion + pendingProofs[index].sparkWithdrawal = sparkWithdrawal ? true : nil try await persist(pendingProofs) } @@ -1329,6 +1335,95 @@ actor PaykitPaymentProofService { return true } + /// Completes the on-chain proof of a request Spark paid by withdrawing to the payee's address. Spark's withdrawal + /// isn't one of the node's send attempts, so its txid is the proof as soon as Spark returns it. + func completeSparkOnchainPayment(requestId: PaykitPaymentRequest.ID, identity: String, txid: String) async -> Bool { + guard Self.isHex(txid, byteCount: 32) else { return false } + do { + let completed: PendingPaykitPaymentProof? = try await mutationLock.withLock { + var proofs = try await loadProofs() + guard let index = proofs.lastIndex(where: { + PubkyPublicKeyFormat.matches($0.identity, identity) && $0.requestId == requestId && $0.kind == .onchain && + $0.paymentStarted && $0.onchainWalletId == nil && $0.sparkWithdrawal == true && + ($0.paymentIdentifier == nil || $0.paymentIdentifier?.caseInsensitiveCompare(txid) == .orderedSame) + }) else { return nil } + proofs[index].paymentIdentifier = txid.lowercased() + proofs[index].proofData = txid.lowercased() + proofs[index].onchainAcceptanceVerified = true + proofs[index].onchainLocalFollowupComplete = true + try await persist(proofs) + return proofs[index] + } + // No started proof left means an earlier pass already saved it, or the request no longer waits on one. + if let completed { + submitInBackground(completed, priority: .interactive) + } + return true + } catch { + logWarning("Failed to retain a Spark on-chain proof for retry: \(error)") + return false + } + } + + /// Drops the started on-chain proof of a request whose Spark withdrawal never went out, giving back the private list + /// version it consumed when the contact's list is still at exactly that version. Only a proof the withdrawal started + /// goes, never a direct on-chain send's for the same request. `.failed` when it could not be dropped, so the + /// withdrawal's journal stays open for a retry. + @discardableResult + func failSparkOnchainPayment( + requestId: PaykitPaymentRequest.ID, + identity: String, + unstartedPaymentList: SparkContactWithdrawal.PaymentList? = nil, + privatePaykitService: PrivatePaykitService = .shared, + settleAllowance: () async -> Bool = { true } + ) async -> SparkProofRelease { + do { + return try await mutationLock.withLock { + let proofs = try await loadProofs() + let unsent = proofs.filter { + PubkyPublicKeyFormat.matches($0.identity, identity) && $0.requestId == requestId && $0.kind == .onchain && + $0.paymentStarted && $0.onchainWalletId == nil && $0.sparkWithdrawal == true && + $0.paymentIdentifier == nil && $0.proofData == nil + } + guard !unsent.isEmpty else { + // A kill before the proof started leaves the list the request consumed only in the journal. + if let list = unstartedPaymentList { + try await privatePaykitService.releaseUnsentPaymentListVersion( + publicKey: requestId.counterparty, + version: list.version, + previousVersion: list.previousVersion + ) + } + return .nothingStarted + } + // The allowance attempt is settled before the proof goes: a restart in between, or a failed ledger + // write, leaves the proof and so the journal, which retry the settlement. + guard await settleAllowance() else { return .failed } + for proof in unsent { + guard let version = proof.privatePaymentListVersion else { continue } + try await privatePaykitService.releaseUnsentPaymentListVersion( + publicKey: proof.requestId.counterparty, + version: version, + previousVersion: proof.previousPrivatePaymentListVersion + ) + } + do { + try await persist(proofs.filter { !unsent.contains($0) }) + } catch { + for proof in unsent { + guard let version = proof.privatePaymentListVersion else { continue } + try await privatePaykitService.retainOriginalPaymentListVersion(publicKey: proof.requestId.counterparty, version: version) + } + throw error + } + return .released + } + } catch { + logWarning("Failed to clear an unsent Spark on-chain proof: \(error)") + return .failed + } + } + @discardableResult func failOnchainPayment(_ request: PaykitPaymentRequest, paymentIdentity: String? = nil) async -> Bool { let liveIdentity = paymentIdentity == nil ? try? await currentIdentity() : nil @@ -1960,3 +2055,13 @@ actor PaykitPaymentProofService { } } } + +/// What dropping a Spark withdrawal's started proof did. +enum SparkProofRelease: Equatable { + /// The withdrawal's started proof is gone. + case released + /// The withdrawal never started a proof: a kill came before it, or a direct send owns the request's proof. + case nothingStarted + /// The proof could not be dropped, so it stays for a retry. + case failed +} diff --git a/Bitkit/Services/PaykitPaymentRequestService.swift b/Bitkit/Services/PaykitPaymentRequestService.swift index 27d5f5996d..0834ed1e90 100644 --- a/Bitkit/Services/PaykitPaymentRequestService.swift +++ b/Bitkit/Services/PaykitPaymentRequestService.swift @@ -2053,6 +2053,16 @@ final class PaykitPaymentRequestManager { } } + private static let declinedLifecycleStates: [Paykit.PaymentRequestLifecycleState] = [.rejected, .canceled] + + /// Requests the user declined stay marked as presented while the SDK still lists them, so one never pops up again + /// if a later read reports it as proposed. + private var declinedRequestIds: Set { + Set(historyRequests.filter { + $0.direction == .incoming && Self.declinedLifecycleStates.contains($0.lifecycleState) + }.map(\.id)) + } + func canDismiss(_ request: PaykitPaymentRequest) -> Bool { retainedHardwareRetries[request.id] == nil } @@ -2693,7 +2703,7 @@ final class PaykitPaymentRequestManager { clockOffset: subscriptionClockOffset ) let currentRequestIds = Set(pendingRequests.map(\.id)) - presentedRequestIds.formIntersection(currentRequestIds) + presentedRequestIds.formIntersection(currentRequestIds.union(declinedRequestIds)) presentationRetryAttempts = presentationRetryAttempts.filter { currentRequestIds.contains($0.key) } presentationRetryDeadlines = presentationRetryDeadlines.filter { currentRequestIds.contains($0.key) } automaticPresentationDiagnosticReasons = automaticPresentationDiagnosticReasons.filter { currentRequestIds.contains($0.key) } @@ -2804,7 +2814,11 @@ final class PaykitPaymentRequestManager { historyRequests.removeAll { $0.id == request.id } historyRequests.insert(updatedRequest, at: 0) pendingRequests.removeAll { $0.id == request.id } - presentedRequestIds.remove(request.id) + if Self.declinedLifecycleStates.contains(resultingState) { + presentedRequestIds.insert(request.id) + } else { + presentedRequestIds.remove(request.id) + } presentationRetryAttempts.removeValue(forKey: request.id) presentationRetryDeadlines.removeValue(forKey: request.id) automaticPresentationDiagnosticReasons.removeValue(forKey: request.id) @@ -2877,7 +2891,7 @@ final class PaykitPaymentRequestManager { requestedSubscriptionProposalId = nil } let requestIds = Set(pendingRequests.map(\.id)) - presentedRequestIds.formIntersection(requestIds) + presentedRequestIds.formIntersection(requestIds.union(declinedRequestIds)) presentationRetryAttempts = presentationRetryAttempts.filter { requestIds.contains($0.key) } presentationRetryDeadlines = presentationRetryDeadlines.filter { requestIds.contains($0.key) } automaticPresentationDiagnosticReasons = automaticPresentationDiagnosticReasons.filter { requestIds.contains($0.key) } diff --git a/Bitkit/Services/PaykitRouteService.swift b/Bitkit/Services/PaykitRouteService.swift new file mode 100644 index 0000000000..79439a3a1f --- /dev/null +++ b/Bitkit/Services/PaykitRouteService.swift @@ -0,0 +1,464 @@ +import BitkitCore +import Foundation +import Paykit + +/// A contact payment bitkit-core's Paykit router picks the way for: the contact's bitcoin endpoints, whether a Spark leg +/// may reach its on-chain ones, the leg once the router picked one, and the decoded invoice and LNURL a Direct pick pays. +struct PaykitRouteUi: Equatable { + let endpoints: [PaykitEndpoint] + let offersSparkLeg: Bool + var serviceLeg: ServiceRouteLeg? + var invoice: LightningInvoice? + var lnurl: LnurlPayData? + + var deliveredSat: UInt64? { + serviceLeg?.deliveredSat + } + + var totalFeeSat: UInt64? { + serviceLeg.map { $0.debitSat.saturatingSub($0.deliveredSat) } + } + + var onchainEndpoints: [PaykitEndpoint] { + endpoints.filter(\.isOnchain) + } +} + +extension PaykitEndpoint { + var isOnchain: Bool { + PublicPaykitService.MethodId(rawValue: methodId)?.onchainNetwork != nil + } + + var isLnurl: Bool { + methodId == PublicPaykitService.MethodId.bitcoinLightningLnurl.rawValue + } +} + +/// Routes every bitcoin contact payment through bitkit-core's Paykit router: Direct pays one of the contact's +/// endpoints, Service pays through a service the wallet holds a balance on (a Spark withdrawal to the contact's on-chain +/// address), None pays nothing. +enum PaykitRouteService { + /// The source the payment is paid from, as picked on the amount screen. + enum Source { + case spending + case savings + } + + /// Spark can carry a leg while it is ready and holds a sendable balance. + @MainActor + static var canRouteThroughSpark: Bool { + SparkManager.shared.isReady && SparkManager.shared.sendableSats > 0 + } + + /// The route for a contact payment, or nil without bitcoin endpoints. A Spark leg is offered to a contact with an + /// on-chain endpoint while Spark can route, whatever Lightning can pay, since the router still picks a direct payment + /// that works; a request it pays gets its on-chain proof from the withdrawal's txid. + static func routeUi(for context: ContactPaymentContext, canRouteThroughSpark: Bool) -> PaykitRouteUi? { + let endpoints = context.endpoints + .filter { $0.methodId != .usdtArbitrum } + .map { PaykitEndpoint(methodId: $0.methodId.rawValue, value: $0.value) } + guard !endpoints.isEmpty else { return nil } + let offersSparkLeg = canRouteThroughSpark && endpoints.contains(where: \.isOnchain) + return PaykitRouteUi(endpoints: endpoints, offersSparkLeg: offersSparkLeg) + } + + /// What the router is asked from `source`: Spending offers every endpoint but an LNURL whose limits refuse the amount, + /// Savings only the on-chain ones. + static func request( + route: PaykitRouteUi, + amountSats: UInt64, + source: Source, + lightningSpendableSats: UInt64, + onchainSpendableSats: UInt64, + serviceLegs: [ServiceRouteLeg] + ) -> PaykitRouteRequest { + switch source { + case .spending: + PaykitRouteRequest( + amountSat: amountSats, + contactEndpoints: route.endpoints.filter { !$0.isLnurl || route.lnurl?.accepts(amountSats: amountSats) != false }, + lightningSpendableSat: lightningSpendableSats, + onchainSpendableSat: 0, + serviceLegs: serviceLegs + ) + case .savings: + PaykitRouteRequest( + amountSat: amountSats, + contactEndpoints: route.onchainEndpoints, + lightningSpendableSat: 0, + onchainSpendableSat: onchainSpendableSats, + serviceLegs: [] + ) + } + } + + /// Asks the router how to pay `amountSats` from `source`. The router pays directly before it weighs any leg, so a + /// Spark leg to each on-chain endpoint is quoted only when the route offers one and no balance pays. Spark takes one + /// contact withdrawal at a time, so while an earlier one's journal is open no leg is quoted and this throws + /// `SparkWithdrawalSettling`. + static func route( + _ route: PaykitRouteUi, + amountSats: UInt64, + source: Source, + lightningSpendableSats: UInt64, + onchainSpendableSats: UInt64, + quoteLegs: ([PaykitEndpoint], UInt64) async throws -> [ServiceRouteLeg] = { try await sparkLegs(to: $0, amountSats: $1) } + ) async throws -> PaykitRoute { + func pick(_ serviceLegs: [ServiceRouteLeg]) throws -> PaykitRoute { + try paykitRoutePayment( + request: request( + route: route, + amountSats: amountSats, + source: source, + lightningSpendableSats: lightningSpendableSats, + onchainSpendableSats: onchainSpendableSats, + serviceLegs: serviceLegs + ), + network: Env.bitkitCoreNetwork + ) + } + let direct = try pick([]) + guard case .none = direct, source == .spending, route.offersSparkLeg else { return direct } + guard SparkManager.pendingContactWithdrawal == nil else { throw SparkWithdrawalSettling() } + let serviceLegs = try await quoteLegs(route.onchainEndpoints, amountSats) + return serviceLegs.isEmpty ? direct : try pick(serviceLegs) + } + + /// Spark's leg to each of `endpoints`, from `quote`. Throws `SparkLegUnaffordable` when no leg is quoted and one + /// was dropped because Spark's balance can't cover the amount and its fee. + static func sparkLegs( + to endpoints: [PaykitEndpoint], + amountSats: UInt64, + quote: (PaykitEndpoint, UInt64) async throws -> ServiceRouteLeg? = { + try await SparkManager.shared.withdrawalRouteLeg(endpoint: $0, amountSats: $1) + } + ) async throws -> [ServiceRouteLeg] { + var legs: [ServiceRouteLeg] = [] + var unaffordable: SparkLegUnaffordable? + for endpoint in endpoints { + do { + if let leg = try await quote(endpoint, amountSats) { + legs.append(leg) + } + } catch { + unaffordable = unaffordable ?? error as? SparkLegUnaffordable + Logger.warn("No Spark route to \(endpoint.methodId): \(error)", context: "PaykitRoute") + } + } + if legs.isEmpty, let unaffordable { + throw unaffordable + } + return legs + } + + /// Whether a Spark withdrawal carries `amountSats` on `route`, or nil when Lightning's limit decides. A withdrawal + /// is paid from Spark's whole balance, so Lightning's limit never caps it: a quoted leg fits when its debit, fees + /// included, does, and before the quote an amount the balance covers lets Continue ask for one. + static func sparkWithdrawalValidity(route: PaykitRouteUi?, amountSats: UInt64, sparkBalanceSats: UInt64) -> Bool? { + guard let route, route.offersSparkLeg, amountSats > 0 else { return nil } + if let leg = route.serviceLeg, leg.deliveredSat == amountSats { + return sparkBalanceSats >= leg.debitSat + } + return sparkBalanceSats >= amountSats ? true : nil + } + + /// Whether a None route is a short balance rather than a contact Bitkit can't pay. + static func isBalanceShort(amountSats: UInt64, lightningSpendableSats: UInt64, onchainSpendableSats: UInt64) -> Bool { + amountSats > lightningSpendableSats.saturatingAdd(onchainSpendableSats) + } + + /// Runs a service leg the router picked and returns the txid that pays the contact. + /// Whether a failed leg send releases this call's started proof: only when Spark refused it before sending, and no + /// open journal of the same request (an earlier attempt that may have paid) still owns that proof. Another + /// request's open journal never decides it. + static func legFailureReleasesProof( + _ error: Error, + openJournalRequest: SparkContactWithdrawal.PaykitRequest?, + proofRequest: SparkContactWithdrawal.PaykitRequest + ) -> Bool { + error is SparkWithdrawalNotSent && openJournalRequest != proofRequest + } + + /// Prepares the on-chain proof of a request a Spark leg pays, in a direct send's order: the proof is prepared, then + /// the request (its checks and private list consumption). Spark's withdrawal marks the proof started once its journal + /// is written. Any failure releases the private payment list as unsent, and one after the proof was prepared cancels + /// it, so the request can be paid again. + static func startLegRequestProof( + prepareProof: () async throws -> Void, + prepareRequest: () async throws -> Void, + paymentIdentity: () async throws -> String, + cancelProof: () async -> Void, + releasePaymentList: () async -> Void + ) async throws -> String { + do { + try await prepareProof() + } catch { + await releasePaymentList() + throw error + } + do { + try await prepareRequest() + return try await paymentIdentity() + } catch { + await cancelProof() + await releasePaymentList() + throw error + } + } + + /// Pays a leg as a manual payment the allowance ledger counts, as a direct send is: the attempt is reserved right + /// before Spark's send, marked sending once the request is authorized, and closed with the send's outcome: + /// succeeded with its txid, failed when Spark refused it before sending, and unknown otherwise. + static func payReportingAllowance( + beginAllowance: @escaping () async throws -> String?, + authorize: @escaping () async throws -> Void, + markSending: @escaping (String) async -> Void, + finishAllowance: (String, Paykit.PaymentOutcome, String?) async -> Void, + pay: (_ beforeSend: () async throws -> Void) async throws -> String + ) async throws -> String { + var attemptId: String? + do { + let txid = try await pay { + attemptId = try await beginAllowance() + try await authorize() + if let attemptId { + await markSending(attemptId) + } + } + if let attemptId { + await finishAllowance(attemptId, .succeeded, txid) + } + return txid + } catch { + if let attemptId { + await finishAllowance(attemptId, error is SparkWithdrawalNotSent ? .failed : .unknown, nil) + } + throw error + } + } + + static func pay( + _ leg: ServiceRouteLeg, + contact: String?, + request: SparkContactWithdrawal.PaykitRequest? = nil, + tags: [String] = [], + paymentDeadline: PaykitPreciseInstant? = nil, + beforeSend: () async throws -> Void = {} + ) async throws -> String { + guard leg.service == SparkManager.routeService else { + throw AppError(message: "wallet__payment_failed_description", debugMessage: "Unsupported route service \(leg.service)") + } + return try await SparkManager.shared.withdraw( + to: leg.endpoint.value, + amountSats: leg.deliveredSat, + contact: contact, + request: request, + tags: tags, + maxFeeSats: leg.debitSat.saturatingSub(leg.deliveredSat), + paymentDeadline: paymentDeadline, + beforeSend: beforeSend + ) + } +} + +/// Only a Spark leg could pay, but an earlier contact withdrawal's journal is still open. +struct SparkWithdrawalSettling: Error {} + +/// What asking the router did to a contact payment. +enum PaykitRouteOutcome: Equatable { + /// The send pays the endpoint the router picked. + case direct + /// The send pays through the service leg in `AppViewModel.paykitRoute`. + case leg + /// No route pays the contact; the app's copy says why. + case refused + /// The payment changed while the router answered, so its answer was dropped. + case stale +} + +@MainActor +extension AppViewModel { + /// Asks bitkit-core's router how to pay the contact from `source`. Direct switches the send to the endpoint it + /// names, a service leg is kept in `paykitRoute` for Confirm, and none shows the app's copy, its reason going to the + /// log only. + func routeContactPayment( + _ route: PaykitRouteUi, + amountSats: UInt64, + source: PaykitRouteService.Source, + lightningSpendableSats: UInt64, + onchainSpendableSats: UInt64, + request: PaykitPaymentRequest?, + router: (PaykitRouteUi, UInt64, PaykitRouteService.Source, UInt64, UInt64) async throws -> PaykitRoute = { + try await PaykitRouteService.route($0, amountSats: $1, source: $2, lightningSpendableSats: $3, onchainSpendableSats: $4) + }, + decodeEndpoint: (String) async throws -> BitkitCore.Scanner = { try await decode(invoice: $0) } + ) async -> PaykitRouteOutcome { + var unrouted = route + unrouted.serviceLeg = nil + unrouted.invoice = route.invoice ?? scannedLightningInvoice + unrouted.lnurl = route.lnurl ?? lnurlPayData + let contactId = contactPaymentContext?.id + paykitRoutingGeneration += 1 + let generation = paykitRoutingGeneration + // A dismissed or replaced payment, a newer routing request (a new amount or source) or a source picked since + // makes the answer stale, so it never lands on what followed it. + // A short balance names itself first, then the limit of an LNURL that refused the amount (the router never saw + // it), then a Spark leg the balance can't cover with its fee. + func refuse(sparkLegShort: Bool) -> PaykitRouteOutcome { + paykitRoute = unrouted + let isBalanceShort = PaykitRouteService.isBalanceShort( + amountSats: amountSats, + lightningSpendableSats: lightningSpendableSats, + onchainSpendableSats: onchainSpendableSats + ) + if isBalanceShort || unrouted.lnurl.map({ validateLnurlAmount($0, amountSats: amountSats) }) != false { + showNoPaykitRouteToast(isBalanceShort: isBalanceShort || sparkLegShort) + } + return .refused + } + let isCurrent = { + self.contactPaymentContext?.id == contactId && self.paykitRoutingGeneration == generation && + (self.selectedWalletToPayFrom == .lightning) == (source == .spending) && + (self.paykitRoute.map { $0.endpoints == route.endpoints } ?? true) + } + do { + // The known invoice and LNURL go to the router too, so it never picks an LNURL whose limits refuse the amount. + let picked = try await router(unrouted, amountSats, source, lightningSpendableSats, onchainSpendableSats) + guard isCurrent() else { return .stale } + switch picked { + case let .direct(endpoint): + paykitRoute = unrouted + guard await payDirectly(endpoint, route: unrouted, decode: decodeEndpoint) else { return .refused } + if let request { + paykitPaymentTerms = try request.payment(using: paykitPaymentMethod) + } + return .direct + case let .service(leg): + var routed = unrouted + routed.serviceLeg = leg + paykitRoute = routed + selectedWalletToPayFrom = .lightning + return .leg + case let .none(reason): + Logger.warn("Found no Paykit route: '\(reason)'", context: "PaykitRoute") + return refuse(sparkLegShort: false) + } + } catch is SparkWithdrawalSettling { + Logger.warn("Found no Paykit route: an earlier Spark contact withdrawal is still settling", context: "PaykitRoute") + guard isCurrent() else { return .stale } + // A short balance and an LNURL limit name themselves first, as for any other refusal. + let lnurlRefuses = unrouted.lnurl.map { !$0.accepts(amountSats: amountSats) } ?? false + if lnurlRefuses || PaykitRouteService.isBalanceShort( + amountSats: amountSats, + lightningSpendableSats: lightningSpendableSats, + onchainSpendableSats: onchainSpendableSats + ) { + return refuse(sparkLegShort: false) + } + paykitRoute = unrouted + toast( + type: .error, + title: t("wallet__send_paykit_no_route__title"), + description: t("wallet__send_paykit_withdrawal_settling__description"), + accessibilityIdentifier: "PaykitRouteSettlingToast" + ) + return .refused + } catch let error as SparkLegUnaffordable { + Logger.warn("Found no Paykit route: \(error)", context: "PaykitRoute") + guard isCurrent() else { return .stale } + return refuse(sparkLegShort: true) + } catch { + Logger.error("Failed to route Paykit payment: \(error)", context: "PaykitRoute") + guard isCurrent() else { return .stale } + showNoPaykitRouteToast(isBalanceShort: false) + return .refused + } + } + + /// Switches the send to exactly the endpoint the router picked, clearing the other Lightning one. An earlier pick may + /// have cleared the picked one, so it comes back from `route`; one never decoded is decoded here. + private func payDirectly( + _ endpoint: PaykitEndpoint, + route: PaykitRouteUi, + decode: (String) async throws -> BitkitCore.Scanner + ) async -> Bool { + if endpoint.isOnchain { + selectedWalletToPayFrom = .onchain + if scannedOnchainInvoice?.address != endpoint.value { + scannedOnchainInvoice = OnChainInvoice(address: endpoint.value, amountSatoshis: 0, label: nil, message: nil, params: nil) + } + return true + } + selectedWalletToPayFrom = .lightning + if endpoint.isLnurl { + if let lnurl = lnurlPayData ?? route.lnurl { + lnurlPayData = lnurl + } else { + // A route built once Spark became ready after the scan holds the contact's LNURL undecoded. + guard case let .lnurlPay(data) = try? await decode(endpoint.value) else { + Logger.warn("Failed to decode the LNURL endpoint the router picked", context: "PaykitRoute") + showNoPaykitRouteToast(isBalanceShort: false) + return false + } + lnurlPayData = data + paykitRoute?.lnurl = data + } + scannedLightningInvoice = nil + return true + } + let known = [scannedLightningInvoice, route.invoice].compactMap { $0 } + .first { $0.bolt11.caseInsensitiveCompare(endpoint.value) == .orderedSame } + if let known { + scannedLightningInvoice = known + } else { + guard case let .lightning(invoice) = try? await decode(endpoint.value) else { + Logger.warn("Failed to decode the Lightning endpoint the router picked", context: "PaykitRoute") + showNoPaykitRouteToast(isBalanceShort: false) + return false + } + scannedLightningInvoice = invoice + } + lnurlPayData = nil + return true + } + + func showNoPaykitRouteToast(isBalanceShort: Bool) { + toast( + type: .error, + title: t(isBalanceShort ? "wallet__send_amount_exceeded__title" : "wallet__send_paykit_no_route__title"), + description: t(isBalanceShort ? "wallet__send_amount_exceeded__description" : "wallet__send_paykit_no_route__description"), + accessibilityIdentifier: isBalanceShort ? "PaykitRouteBalanceToast" : "PaykitRouteNoneToast" + ) + } + + /// The route can restore an LNURL a BOLT11 pick cleared, so Amount checks its limits after routing. + func validateRoutedLnurlAmount(amountSats: UInt64) -> Bool { + guard let lnurlPayData else { return true } + return validateLnurlAmount(lnurlPayData, amountSats: amountSats) + } + + /// Shows `lnurl`'s too-low or too-high toast when `amountSats` is outside its limits; true when it accepts it. + func validateLnurlAmount(_ lnurlPayData: LnurlPayData, amountSats: UInt64) -> Bool { + guard !lnurlPayData.accepts(amountSats: amountSats) else { return true } + let minimumAmount = max(1, lnurlPayData.minSendableSat) + if amountSats < minimumAmount { + toast( + type: .error, + title: t("wallet__lnurl_pay__error_min__title"), + description: t( + "wallet__lnurl_pay__error_min__description", + variables: ["amount": CurrencyFormatter.formatSats(minimumAmount)] + ), + accessibilityIdentifier: "LnurlPayAmountTooLowToast" + ) + } else { + toast( + type: .error, + title: t("wallet__lnurl_pay__error_max__title"), + description: t("wallet__lnurl_pay__error_max__description"), + accessibilityIdentifier: "LnurlPayAmountTooHighToast" + ) + } + return false + } +} diff --git a/Bitkit/Services/PrivatePaykitService+Contacts.swift b/Bitkit/Services/PrivatePaykitService+Contacts.swift index 3056c4b0e1..6c5433eed8 100644 --- a/Bitkit/Services/PrivatePaykitService+Contacts.swift +++ b/Bitkit/Services/PrivatePaykitService+Contacts.swift @@ -894,10 +894,12 @@ extension PrivatePaykitService { updates.removeAll { !knownSavedContactKeys.contains($0.counterparty) } guard generation == preparationGeneration else { throw PrivatePaykitError.privateUnavailable } guard !updates.isEmpty else { + Logger.debug("Skipped private payment list publication during \(reason): no list changed", context: "PrivatePaykit") schedulePendingPrivateMessageDrainRetries(reason: reason, retryKeys: linkRetryKeys) return } let report = try await operations.syncPaymentLists(updates) + Logger.debug("Published private payment lists to \(updates.count) contacts during \(reason)", context: "PrivatePaykit") let deliveryError = applyPrivatePaymentListDeliveryReport(report, reason: reason) firstError = firstError ?? deliveryError let retryKeys = linkRetryKeys + privatePaymentListDeliveryRetryKeys(from: report) diff --git a/Bitkit/Utilities/PaymentNavigationHelper.swift b/Bitkit/Utilities/PaymentNavigationHelper.swift index cf5fcab780..b7ca2c3c28 100644 --- a/Bitkit/Utilities/PaymentNavigationHelper.swift +++ b/Bitkit/Utilities/PaymentNavigationHelper.swift @@ -50,7 +50,7 @@ struct PaymentNavigationHelper { sheetViewModel.showSheet(.send, data: SendConfig(view: route)) return } - if app.contactPaymentContext?.requiresAssetSelection == true { + if app.contactPaymentPicksSource { sheetViewModel.showSheet(.send, data: SendConfig(view: .amount)) return } @@ -117,7 +117,7 @@ struct PaymentNavigationHelper { spendStore: QuickPaySpendStore = .shared, coordinator: QuickPayPaymentCoordinator? = nil ) -> SendRoute? { - if app.contactPaymentContext?.requiresAssetSelection == true, app.paykitPaymentTerms == nil { + if app.contactPaymentPicksSource, app.paykitPaymentTerms == nil { return .amount } if let lnurlWithdrawData = app.lnurlWithdrawData { @@ -218,7 +218,7 @@ struct PaymentNavigationHelper { spendStore: QuickPaySpendStore = .shared, coordinator: QuickPayPaymentCoordinator? = nil ) -> SendRoute? { - if app.contactPaymentContext?.requiresAssetSelection == true { + if app.contactPaymentPicksSource { if app.paykitPaymentTerms == nil { return .amount } diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index c5b48e5370..6a1fae05a3 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -37,6 +37,12 @@ struct ContactPaymentContext: Equatable { incomingPaymentRequest.map { $0.amount.asset != .btc || $0.pricing.conversion != nil } == true } + /// An on-chain and a Lightning endpoint, between which the router picks, Spark's leg to the on-chain one included. + var hasMixedBitcoinEndpoints: Bool { + endpoints.contains { $0.methodId.onchainNetwork != nil } && + endpoints.contains { $0.methodId == .bitcoinLightningLnurl || $0.methodId == .bitcoinLightningBolt11 } + } + func initialUsdtSubscriptionPayment(at date: Date = Date()) -> PaykitRequestPricing.Payment? { guard isInitialSubscriptionPayment, let request = incomingPaymentRequest, request.billingPeriod != nil, Set(request.acceptedPaymentEndpointIdentifiers) == [PublicPaykitService.MethodId.usdtArbitrum.rawValue], @@ -117,6 +123,7 @@ struct ScanPaymentOperations { let state: () -> ScanPaymentState let canSendLightning: (_ amountSats: UInt64) -> Bool var decodeInvoice: (String) async throws -> BitkitCore.Scanner = { try await decode(invoice: $0) } + var canRouteThroughSpark: @MainActor () -> Bool = { PaykitRouteService.canRouteThroughSpark } @MainActor static func live(lightningService: LightningService) -> ScanPaymentOperations { @@ -171,6 +178,9 @@ class AppViewModel: ObservableObject { @Published var contactPaymentContext: ContactPaymentContext? private(set) var didRejectScannedPayment = false @Published var paykitUsesUsdt = false + @Published var paykitRoute: PaykitRouteUi? + /// Bumped by each routing request, so only the latest one's answer lands. + var paykitRoutingGeneration = 0 @Published var paykitReviewedAmount: PaykitAmount? @Published var paykitPaymentTerms: PaykitRequestPricing.Payment? @@ -763,9 +773,28 @@ extension AppViewModel { return paykitBitcoinMethod(for: selectedWalletToPayFrom) } + /// The method a send prices with. Spending with no Lightning payment to make funds the Spark leg to the on-chain + /// endpoint, so it takes that endpoint's price, the one the leg and its proof pay. + /// Amount picks the source and the asset: for a contact that lists USDT or is priced in another asset, and for a mixed + /// Bitcoin contact while Spark can carry a leg, so an amount no Lightning endpoint takes still reaches the router. + var contactPaymentPicksSource: Bool { + guard let context = contactPaymentContext else { return false } + return context.requiresAssetSelection || (context.hasMixedBitcoinEndpoints && paykitRoute?.offersSparkLeg == true) + } + func paykitBitcoinMethod(for wallet: WalletType) -> PublicPaykitService.MethodId { if wallet == .lightning { - return lnurlPayData != nil ? .bitcoinLightningLnurl : .bitcoinLightningBolt11 + // A routed Spark leg pays its on-chain endpoint, whatever Lightning endpoint the contact also has. + if let leg = paykitRoute?.serviceLeg, let method = PublicPaykitService.MethodId(rawValue: leg.endpoint.methodId) { + return method + } + if lnurlPayData != nil { + return .bitcoinLightningLnurl + } + if scannedLightningInvoice == nil, let address = scannedOnchainInvoice?.address { + return PublicPaykitService.onchainMethodId(for: address) + } + return .bitcoinLightningBolt11 } return PublicPaykitService.onchainMethodId(for: scannedOnchainInvoice?.address ?? "") } @@ -801,7 +830,9 @@ extension AppViewModel { } } - if let context = claimedContactPaymentContext, context.requiresAssetSelection, scope != .onchainPayments { + if let context = claimedContactPaymentContext, scope != .onchainPayments, + context.requiresAssetSelection || context.hasMixedBitcoinEndpoints && scanPaymentOperations.canRouteThroughSpark() + { resetSendState(preservingContactPaymentContext: true, ownerID: sendPresentationID) expectedGeneration = sendStateGeneration for endpoint in context.endpoints where endpoint.methodId != .usdtArbitrum { @@ -827,6 +858,20 @@ extension AppViewModel { isUsdtEnabled: SettingsViewModel.shared.isUsdtEnabled ) || context.incomingPaymentRequest.map { PaykitUsdtPaymentService.shared.hasBinding(for: $0.id) } == true selectedWalletToPayFrom = canUseLightning || (hasLightning && scannedOnchainInvoice == nil) ? .lightning : .onchain + // A Spark leg can pay the on-chain endpoint from Spending here too, whatever Lightning can pay now: an amount + // entered later can pass Lightning's limit, and the router still picks a direct payment that works. + if scannedOnchainInvoice != nil, + let route = PaykitRouteService.routeUi(for: context, canRouteThroughSpark: scanPaymentOperations.canRouteThroughSpark()), + route.offersSparkLeg + { + paykitRoute = route + // A request keeps its source here; its Confirm asks the router. + if !hasLightning, context.incomingPaymentRequest == nil, + max(state.spendableOnchainBalanceSats, alternativeOnchainBalanceSats) <= UInt64(Env.dustLimit) + { + selectedWalletToPayFrom = .lightning + } + } let canSelectUsdt = SettingsViewModel.shared.isUsdtEnabled && context.endpoints.contains { $0.methodId == .usdtArbitrum } if !paykitUsesUsdt, !canSelectUsdt, let request = context.incomingPaymentRequest { do { @@ -1041,6 +1086,20 @@ extension AppViewModel { // Fallback to on-chain if address is available guard !invoice.address.isEmpty, validateIncomingOnchainPaymentRequestAmount(requestedAmount ?? invoice.amountSatoshis) else { return } + // An on-chain contact payment opens with Spending as a source while Spark can carry it there, whether or + // not Savings covers it; Spending is the default when Savings holds no more than dust. + if let context = contactPaymentContext, scope != .onchainPayments, + let route = PaykitRouteService.routeUi(for: context, canRouteThroughSpark: scanPaymentOperations.canRouteThroughSpark()), + route.offersSparkLeg + { + handleScannedOnchainInvoice(invoice) + paykitRoute = route + if max(paymentState.spendableOnchainBalanceSats, alternativeOnchainBalanceSats) <= UInt64(Env.dustLimit) { + selectedWalletToPayFrom = .lightning + } + return + } + // If node is running, validate balance immediately if paymentState.isNodeRunning { let onchainBalance = max( @@ -1386,6 +1445,7 @@ extension AppViewModel { sendStateOwnerID = ownerID sendStateGeneration = UUID() paykitUsesUsdt = false + paykitRoute = nil paykitReviewedAmount = nil paykitPaymentTerms = nil scannedLightningInvoice = nil diff --git a/Bitkit/Views/Wallets/Activity/ActivityItemView.swift b/Bitkit/Views/Wallets/Activity/ActivityItemView.swift index ce4422c4dd..821dd7d425 100644 --- a/Bitkit/Views/Wallets/Activity/ActivityItemView.swift +++ b/Bitkit/Views/Wallets/Activity/ActivityItemView.swift @@ -19,6 +19,8 @@ struct ActivityItemView: View { @StateObject private var viewModel: ActivityItemViewModel @State private var boostTxDoesExist: [String: Bool] = [:] // Maps boostTxId -> doesExist @State private var isCpfpChild: Bool = false + /// Spark sent this transaction, so LDK holds no input of it to boost. + @State private var isSparkWithdrawal = false private var isPaykitUIActive: Bool { PaykitFeatureFlags.isUIAvailable && isPaykitUIEnabled @@ -148,7 +150,7 @@ struct ActivityItemView: View { case .lightning: return true case let .onchain(activity): - if isCpfpChild { + if isCpfpChild || isSparkWithdrawal { return true } if !activity.doesExist { @@ -257,6 +259,7 @@ struct ActivityItemView: View { // Check if this is a CPFP child transaction if case let .onchain(activity) = viewModel.activity { isCpfpChild = await CoreService.shared.activity.isCpfpChildTransaction(txId: activity.txId, walletId: activity.walletId) + isSparkWithdrawal = await SparkManager.shared.isSparkWithdrawal(txid: activity.txId, isSent: activity.txType == .sent) } // Load boostTxIds doesExist status to determine RBF vs CPFP diff --git a/Bitkit/Views/Wallets/Send/SendAmountView.swift b/Bitkit/Views/Wallets/Send/SendAmountView.swift index ee08955116..5bf522324d 100644 --- a/Bitkit/Views/Wallets/Send/SendAmountView.swift +++ b/Bitkit/Views/Wallets/Send/SendAmountView.swift @@ -1,3 +1,4 @@ +import BitkitCore import SwiftUI enum SendFundingSource: Equatable { @@ -44,7 +45,8 @@ struct SendAmountView: View { return [.usdt] } var sources: [SendFundingSource] = [] - if app.scannedLightningInvoice != nil || app.lnurlPayData != nil { + // A Spark leg can carry an on-chain contact payment from Spending. + if app.scannedLightningInvoice != nil || app.lnurlPayData != nil || app.paykitRoute?.offersSparkLeg == true { sources.append(.spending) } if app.scannedOnchainInvoice != nil { @@ -119,6 +121,9 @@ struct SendAmountView: View { } let minAmount = app.selectedWalletToPayFrom == .lightning ? 1 : Env.dustLimit + if !hwSend.isActive, app.selectedWalletToPayFrom == .lightning, let valid = sparkWithdrawalValidity { + return valid + } if app.selectedWalletToPayFrom == .lightning, let data = app.lnurlPayData, !data.accepts(amountSats: amountSats) { @@ -127,6 +132,26 @@ struct SendAmountView: View { return amountSats >= minAmount && amountSats <= availableAmount } + /// Spark's whole balance pays a withdrawal to the contact, so Lightning's limit never caps it. + private var sparkWithdrawalBalanceSats: UInt64 { + guard app.contactPaymentContext != nil, app.paykitRoute?.offersSparkLeg == true, SparkManager.shared.isReady else { return 0 } + return SparkManager.shared.balanceSats + } + + private var sparkWithdrawalValidity: Bool? { + PaykitRouteService.sparkWithdrawalValidity( + route: app.paykitRoute, + amountSats: amountSats, + sparkBalanceSats: sparkWithdrawalBalanceSats + ) + } + + /// The pad's cap: what Spending can send, or Spark's whole balance when a withdrawal can carry more. + private var inputCapSats: UInt64 { + guard !hwSend.isActive, app.selectedWalletToPayFrom == .lightning else { return availableAmount } + return max(availableAmount, sparkWithdrawalBalanceSats) + } + /// Determines if the current amount is a max amount send var isMaxAmountSend: Bool { guard app.selectedWalletToPayFrom == .onchain, app.contactPaymentContext?.incomingPaymentRequest == nil else { return false } @@ -337,7 +362,7 @@ struct SendAmountView: View { } } } - .onChange(of: availableAmount, initial: true) { updateInputCap() } + .onChange(of: inputCapSats, initial: true) { updateInputCap() } .onChange(of: amountViewModel.maxExceededCount) { showMaxExceededToast() } } @@ -389,6 +414,20 @@ struct SendAmountView: View { return } + if !app.paykitUsesUsdt, let context = app.contactPaymentContext, + let route = app.paykitRoute ?? PaykitRouteService.routeUi(for: context, canRouteThroughSpark: PaykitRouteService.canRouteThroughSpark) + { + switch await routePaykitPayment(route, request: context.incomingPaymentRequest) { + case .leg: + navigationPath.append(.confirm) + return + case .refused, .stale: + return + case .direct: + break + } + } + // Lightning payment if app.selectedWalletToPayFrom == .lightning { if UInt64(wallet.maxSendLightningSats) < amountSats { @@ -400,7 +439,9 @@ struct SendAmountView: View { return } - navigationPath.append(app.lnurlPayData != nil && app.scannedLightningInvoice == nil ? .lnurlPayConfirm : .confirm) + let paysLnurl = app.lnurlPayData != nil && app.scannedLightningInvoice == nil + guard !paysLnurl || app.validateRoutedLnurlAmount(amountSats: amountSats) else { return } + navigationPath.append(paysLnurl ? .lnurlPayConfirm : .confirm) return } @@ -448,9 +489,21 @@ struct SendAmountView: View { } } + private func routePaykitPayment(_ route: PaykitRouteUi, request: PaykitPaymentRequest?) async -> PaykitRouteOutcome { + let source: PaykitRouteService.Source = app.selectedWalletToPayFrom == .lightning ? .spending : .savings + return await app.routeContactPayment( + route, + amountSats: amountSats, + source: source, + lightningSpendableSats: source == .spending ? UInt64(max(0, wallet.maxSendLightningSats)) : 0, + onchainSpendableSats: source == .savings ? maxSendableAmount ?? UInt64(max(0, wallet.spendableOnchainBalanceSats)) : 0, + request: request + ) + } + private func updateInputCap() { // Don't cap when nothing is sendable, so the pad stays usable (Continue stays disabled instead). - amountViewModel.maxAmountOverride = availableAmount > 0 ? availableAmount : nil + amountViewModel.maxAmountOverride = inputCapSats > 0 ? inputCapSats : nil } private var fundingSourceMenu: some View { @@ -571,14 +624,8 @@ struct SendAmountView: View { conversionError = nil app.paykitUsesUsdt = source == .usdt switch source { - case .usdt: + case .usdt, .spending, .savings: hwSend.selectWallet(nil) - case .spending: - hwSend.selectWallet(nil) - app.selectedWalletToPayFrom = .lightning - case .savings: - hwSend.selectWallet(nil) - app.selectedWalletToPayFrom = .onchain case let .hardware(walletId): let balance = hwWalletManager.fundingBalance(walletId: walletId) let reserve = HwFundingSigner.feeReserve( @@ -590,11 +637,27 @@ struct SendAmountView: View { initialAvailableSats: balance > reserve ? balance - reserve : 0, showsLoading: true ) - app.selectedWalletToPayFrom = .onchain } + Self.selectWallet(of: source, app: app) updateFixedLightningAmount() } + /// Points the send at the wallet `source` pays from. A hardware wallet skips the router on Continue, so a Spark leg + /// routed for Spending is dropped here, as Confirm's own switch does. + static func selectWallet(of source: SendFundingSource, app: AppViewModel) { + switch source { + case .usdt: + break + case .spending: + app.selectedWalletToPayFrom = .lightning + case .savings: + app.selectedWalletToPayFrom = .onchain + case .hardware: + app.paykitRoute = SendConfirmationView.route(app.paykitRoute, afterSelecting: source) + app.selectedWalletToPayFrom = .onchain + } + } + private func updateFixedLightningAmount() { guard app.contactPaymentContext?.incomingPaymentRequest == nil, let amount = app.fixedLightningAmountSats else { return } amountViewModel.updateFromSats(amount, currency: currency) diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index e8dc697e4f..7e9f632d8a 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -28,6 +28,10 @@ struct SendConfirmationView: View { var isSetupPending = false @State private var showDetails = false + @State private var routedIncomingRequestId: PaykitPaymentRequest.ID? + /// Set when Confirm picks a request's source itself, so that switch isn't routed twice. + @State private var skipNextSourceReroute = false + @State private var refusedRouteSource: WalletType? @State private var hasShownAmountReview = false @State private var showingBiometricError = false @State private var biometricErrorMessage = "" @@ -128,18 +132,34 @@ struct SendConfirmationView: View { } private var fundingSources: [SendFundingSource] { + Self.fundingSources( + hasLightningInvoice: app.scannedLightningInvoice != nil, + hasOnchainInvoice: app.scannedOnchainInvoice != nil, + offersSparkLeg: app.paykitRoute?.offersSparkLeg == true, + hardwareWalletIds: hwWalletManager.wallets.compactMap { hardwareWallet in + guard hardwareWallet.fundingBalanceSats > 0 || hardwareWallet.walletId == hwSend.walletId else { + return nil + } + return hardwareWallet.walletId + } + ) + } + + /// The sources the amount screen offers: a Spark leg can carry an on-chain contact payment from Spending, whether or not + /// Savings covers it. + static func fundingSources( + hasLightningInvoice: Bool, + hasOnchainInvoice: Bool, + offersSparkLeg: Bool, + hardwareWalletIds: [String] + ) -> [SendFundingSource] { var sources: [SendFundingSource] = [] - if app.scannedLightningInvoice != nil { + if hasLightningInvoice || offersSparkLeg { sources.append(.spending) } - if app.scannedOnchainInvoice != nil { + if hasOnchainInvoice { sources.append(.savings) - sources.append(contentsOf: hwWalletManager.wallets.compactMap { hardwareWallet in - guard hardwareWallet.fundingBalanceSats > 0 || hardwareWallet.walletId == hwSend.walletId else { - return nil - } - return .hardware(walletId: hardwareWallet.walletId) - }) + sources.append(contentsOf: hardwareWalletIds.map { .hardware(walletId: $0) }) } return sources } @@ -181,7 +201,23 @@ struct SendConfirmationView: View { } private var canSwitchFundingSource: Bool { - retainedHardwareRetry == nil && fundingSources.count > 1 + Self.canSwitchFundingSource(hasRetainedHardwareRetry: retainedHardwareRetry != nil, fundingSources: fundingSources) + } + + static func canSwitchFundingSource(hasRetainedHardwareRetry: Bool, fundingSources: [SendFundingSource]) -> Bool { + !hasRetainedHardwareRetry && fundingSources.count > 1 + } + + /// What Confirm's FROM control shows and does. + struct FromControl: Equatable { + let titleKey: String + let isSwitchable: Bool + } + + /// A Spark leg pays from Spending, and the payer can still move a fixed request to Savings or a hardware wallet, + /// which reroutes it. + static func sparkRouteFromControl(canSwitchFundingSource: Bool) -> FromControl { + FromControl(titleKey: "wallet__spending__title", isSwitchable: canSwitchFundingSource) } var canSwitchWallet: Bool { @@ -345,6 +381,13 @@ struct SendConfirmationView: View { PaykitAmountText(amount: preparingRequest.amount, size: .display) .accessibilityIdentifier("ReviewAmount") } + } else if let deliveredSat = app.paykitRoute?.deliveredSat { + MoneyStack( + sats: Int(wallet.sendAmountSats ?? deliveredSat), + showSymbol: true, + testIdPrefix: "ReviewAmount", + onTap: navigateToAmount + ) } else if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice { MoneyStack( sats: Int(wallet.sendAmountSats ?? invoice.amountSatoshis), @@ -366,7 +409,9 @@ struct SendConfirmationView: View { .padding(.bottom, oneOffPaymentRequest == nil ? 44 : 24) if showDetails { - if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice { + if let route = app.paykitRoute, let totalFeeSat = route.totalFeeSat { + paykitRouteView(route, totalFeeSat: totalFeeSat, note: oneOffPaymentRequestNote) + } else if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice { onchainView(invoice) } else if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice { lightningView(invoice) @@ -455,6 +500,7 @@ struct SendConfirmationView: View { } guard preparingRequest == nil, !isRequestSetupPending, !returnToAmountReviewIfNeeded() else { return } ensureSendAmountFromScannedInvoicesIfNeeded() + await routeContactPaymentOnConfirm() if app.contactPaymentContext?.isInitialSubscriptionPayment == true, !shouldAutomaticallyPay { showManualConfirmation(reason: "not automatic when opened") } @@ -494,6 +540,11 @@ struct SendConfirmationView: View { !returnToAmountReviewIfNeeded(rebindMethod: !hwSend.isActive) else { return } ensureSendAmountFromScannedInvoicesIfNeeded() walletSwitchContext = sendContext + if skipNextSourceReroute { + skipNextSourceReroute = false + } else if Self.sourceSwitchNeedsReroute(route: app.paykitRoute, walletType: app.selectedWalletToPayFrom) { + Task { await routeContactPaymentOnConfirm(sourceChanged: true) } + } } .onChange(of: navigationPath) { previous, path in guard preparingRequest == nil, previous.last == .amount, path.isEmpty, requiresAmountReview, !amountIsRoot else { return } @@ -570,7 +621,8 @@ struct SendConfirmationView: View { shouldAutomaticallyPay: shouldAutomaticallyPay, hasStartedAutomaticPayment: hasStartedAutomaticPayment, isSetupPending: isSetupPending, - isPreparingWallet: walletSwitchContext != nil + isPreparingWallet: walletSwitchContext != nil, + isRouteRefused: refusedRouteSource == app.selectedWalletToPayFrom ) else { return } hasStartedAutomaticPayment = true do { @@ -717,6 +769,74 @@ struct SendConfirmationView: View { } } + func paykitRouteView(_ route: PaykitRouteUi, totalFeeSat: UInt64, note: String?) -> some View { + VStack(alignment: .leading, spacing: 16) { + HStack { + SendSectionView(t("wallet__send_from")) { + let control = Self.sparkRouteFromControl(canSwitchFundingSource: canSwitchFundingSource) + NumberPadActionButton( + text: t(control.titleKey), + imageName: control.isSwitchable ? "arrow-up-down" : nil, + color: .purpleAccent, + variant: control.isSwitchable ? .primary : .secondary, + disabled: !control.isSwitchable + ) { + selectNextFundingSource() + } + .accessibilityIdentifier("SendConfirmAssetButton") + } + + Spacer(minLength: 16) + + if let contact = contactPaymentContact { + SendSectionView(contactSectionTitle) { + contactRecipient(contact) + } + } + } + + HStack(alignment: .top, spacing: 16) { + SendSectionView(t("wallet__send_fee_and_speed")) { + HStack(spacing: 0) { + Image("bolt-hollow") + .foregroundColor(.purpleAccent) + .frame(width: 16, height: 16) + .padding(.trailing, 4) + BodySSBText("\(t("fee__instant__title")) (") + MoneyText(sats: Int(totalFeeSat), size: .bodySSB, symbol: true, symbolColor: .textPrimary) + BodySSBText(")") + } + } + + SendSectionView(t("wallet__send_swap_route")) { + BodySSBText(Self.routeName(route)) + .lineLimit(2) + .accessibilityIdentifier("ReviewSwapRoute") + } + } + + SendSectionView(t("wallet__tags")) { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 8) { + ForEach(tagManager.selectedTagsArray, id: \.self) { tag in + Tag(tag, icon: .close, onDelete: { tagManager.removeTagFromSelection(tag) }) + } + AddTagButton(onPress: { navigationPath.append(.tag) }) + .accessibilityIdentifier("TagsAddSend") + } + } + } + + if let note { + PaymentRequestInvoiceNote(note: note) + } + } + } + + private static func routeName(_ route: PaykitRouteUi) -> String { + route.serviceLeg?.service == SparkManager.routeService ? "Spark" : route.serviceLeg?.service ?? "" + } + func lightningView(_ invoice: LightningInvoice) -> some View { VStack(alignment: .leading, spacing: 16) { HStack { @@ -838,6 +958,14 @@ struct SendConfirmationView: View { } } + /// A hardware wallet signs the on-chain send itself and the router never runs for it, so picking one drops the Spark + /// leg; Savings and Spending ask the router again, which settles the leg. + static func route(_ route: PaykitRouteUi?, afterSelecting source: SendFundingSource) -> PaykitRouteUi? { + guard case .hardware = source, var route else { return route } + route.serviceLeg = nil + return route + } + private func selectNextFundingSource() { guard canSwitchFundingSource else { return } let currentIndex = fundingSources.firstIndex(of: selectedFundingSource) @@ -857,6 +985,7 @@ struct SendConfirmationView: View { hwSend.selectWallet(nil) app.selectedWalletToPayFrom = .onchain case let .hardware(walletId): + app.paykitRoute = Self.route(app.paykitRoute, afterSelecting: source) let balance = hwWalletManager.fundingBalance(walletId: walletId) let reserve = HwFundingSigner.feeReserve( balanceSats: balance, @@ -874,6 +1003,7 @@ struct SendConfirmationView: View { private func submitPayment(isAutomatic: Bool = false) async throws { guard !isSubmittingPayment else { return } guard !requiresAmountReview, preparingRequest == nil, !isRequestSetupPending, walletSwitchContext == nil, + refusedRouteSource != app.selectedWalletToPayFrom, isAutomatic || !prepareRequestCoinsIfNeeded() else { throw CancellationError() } // An automatic payment settles the fee itself below. if !isAutomatic, isPreparingOnchainSend { @@ -973,19 +1103,34 @@ struct SendConfirmationView: View { if hwSend.isActive { navigationPath.append(.hardwareSign) + } else if !app.paykitUsesUsdt, let leg = app.paykitRoute?.serviceLeg { + await performServiceRoutedPayment(leg) } else { try await performPayment(isAutomatic: isAutomatic) } } - /// The wallet switch chooses coins separately from send setup, so the automatic start waits for both. + /// A source switch on Confirm needs the router only when it moves a Spark leg's send to Savings, or any send to + /// Spending, where a Spark leg can carry it: a mixed contact paid from Savings keeps its decoded Lightning payment, + /// which can't pay past Lightning's limit. The app's own switch to a leg's source asks nothing. + static func sourceSwitchNeedsReroute(route: PaykitRouteUi?, walletType: WalletType) -> Bool { + guard let route else { return false } + if route.serviceLeg != nil { + return walletType != .lightning + } + return walletType == .lightning && route.offersSparkLeg + } + + /// The wallet switch chooses coins separately from send setup, so the automatic start waits for both. A source the + /// router refused has nothing to pay, so it never starts. static func canStartAutomaticPayment( shouldAutomaticallyPay: Bool, hasStartedAutomaticPayment: Bool, isSetupPending: Bool, - isPreparingWallet: Bool + isPreparingWallet: Bool, + isRouteRefused: Bool = false ) -> Bool { - shouldAutomaticallyPay && !hasStartedAutomaticPayment && !isSetupPending && !isPreparingWallet + shouldAutomaticallyPay && !hasStartedAutomaticPayment && !isSetupPending && !isPreparingWallet && !isRouteRefused } static func requiresManualConfirmation(isAutomatic: Bool, isHardwarePayment: Bool) -> Bool { @@ -1166,9 +1311,10 @@ struct SendConfirmationView: View { isSetupPending: Bool = false, isPreparingWallet: Bool = false, isAmountReviewRequired: Bool = false, - isPreparingOnchainSend: Bool = false + isPreparingOnchainSend: Bool = false, + isRouteRefused: Bool = false ) -> Bool { - isAmountReviewRequired || isPreparingRequest || isSetupPending || isPreparingWallet || isPreparingOnchainSend + isAmountReviewRequired || isPreparingRequest || isSetupPending || isPreparingWallet || isPreparingOnchainSend || isRouteRefused || isHardwareConfirmationUnavailable || isFeeRateMissing(walletType: walletType, isHardwarePayment: isHardwarePayment, feeRate: feeRate) } @@ -1191,7 +1337,8 @@ struct SendConfirmationView: View { isSetupPending: isRequestSetupPending, isPreparingWallet: walletSwitchContext != nil, isAmountReviewRequired: requiresAmountReview, - isPreparingOnchainSend: isPreparingOnchainSend + isPreparingOnchainSend: isPreparingOnchainSend, + isRouteRefused: refusedRouteSource == app.selectedWalletToPayFrom ) } @@ -1292,6 +1439,238 @@ struct SendConfirmationView: View { return note } + /// A request's Confirm opens with fixed terms and no amount screen, so the router is asked here: Direct switches the + /// send to the endpoint it picks, and a Spark leg pays an on-chain request from Spending. A source switch on Confirm + /// asks it again for any contact payment, so a leg never pays a send the payer moved to Savings. + private func routeContactPaymentOnConfirm(sourceChanged: Bool = false) async { + guard let context = app.contactPaymentContext, !app.paykitUsesUsdt, !hwSend.isActive, !isSubmittingPayment else { return } + let request = context.incomingPaymentRequest + if !sourceChanged { + guard let request, routedIncomingRequestId != request.id else { return } + } + guard let route = app.paykitRoute ?? PaykitRouteService.routeUi(for: context, canRouteThroughSpark: PaykitRouteService.canRouteThroughSpark) + else { return } + let amountSats: UInt64 + if let request { + let amount = app.paykitPaymentTerms?.amount ?? request.amount + guard amount.asset == .btc else { return } + amountSats = amount.atomic + } else { + amountSats = route.deliveredSat ?? wallet.sendAmountSats ?? 0 + } + guard amountSats > 0 else { return } + if let request { + routedIncomingRequestId = request.id + // A request has no amount screen to pick its source, so pick it as that screen would: Savings when it covers + // the amount and fee, otherwise Spending, where the Spark leg can carry it. + if !sourceChanged, app.selectedWalletToPayFrom == .onchain, app.scannedLightningInvoice == nil, app.lnurlPayData == nil, + await Self.requestStartsOnSpending( + savingsSendableSats: savingsSendableSats(), + amountSats: amountSats, + offersSparkLeg: route.offersSparkLeg + ) + { + skipNextSourceReroute = true + app.selectedWalletToPayFrom = .lightning + } + } + let walletType = app.selectedWalletToPayFrom + let source: PaykitRouteService.Source = walletType == .lightning ? .spending : .savings + let outcome = await app.routeContactPayment( + route, + amountSats: amountSats, + source: source, + lightningSpendableSats: source == .spending ? UInt64(max(0, wallet.maxSendLightningSats)) : 0, + onchainSpendableSats: source == .savings ? UInt64(max(0, wallet.spendableOnchainBalanceSats)) : 0, + request: request + ) + // The first call when Confirm opens keeps a refusal too, so a request with no route offers no swipe. + refusedRouteSource = Self.refusedRouteSource(after: outcome, on: walletType, previous: refusedRouteSource) + if Self.reroutePaysLnurl( + outcome: outcome, + walletType: app.selectedWalletToPayFrom, + hasInvoice: app.scannedLightningInvoice != nil, + hasLnurl: app.lnurlPayData != nil + ) { + navigationPath.append(.lnurlPayConfirm) + } + } + + /// Confirm has no LNURL send, so a Direct LNURL pick from Spending pays on the LNURL's own confirm, as one picked on + /// Continue does. + static func reroutePaysLnurl(outcome: PaykitRouteOutcome, walletType: WalletType, hasInvoice: Bool, hasLnurl: Bool) -> Bool { + outcome == .direct && walletType == .lightning && hasLnurl && !hasInvoice + } + + /// A source the router refused on Confirm keeps the swipe off while it's selected, so nothing consumes the contact's + /// private list for a send with nothing to pay; another source is still payable. A late outcome for a source never + /// clears another one's refusal. + static func refusedRouteSource(after outcome: PaykitRouteOutcome, on walletType: WalletType, previous: WalletType?) -> WalletType? { + if outcome == .refused { + return walletType + } + if outcome == .stale { + return previous + } + return previous == walletType ? nil : previous + } + + /// What Savings can send to the request's address after the on-chain fee; its balance while no fee rate is known. + private func savingsSendableSats() async -> UInt64 { + let balance = UInt64(max(0, wallet.spendableOnchainBalanceSats)) + guard let address = app.scannedOnchainInvoice?.address, let rate = wallet.selectedFeeRateSatsPerVByte else { return balance } + return await (try? wallet.calculateMaxSendableAmount(address: address, satsPerVByte: rate)) ?? balance + } + + static func requestStartsOnSpending(savingsSendableSats: UInt64, amountSats: UInt64, offersSparkLeg: Bool) -> Bool { + offersSparkLeg && savingsSendableSats < amountSats + } + + /// Where a failed leg goes: a leg Spark refused before sending paid nothing, so its failure offers Try Again; any + /// other failure may have sent it, so it stays pending until Spark's journal settles it. + static func serviceLegFailureRoute( + _ error: Error, + attempt: SparkWithdrawalAttempt, + routingCacheResetAttempted: Bool + ) -> SendRoute { + guard let refusal = error as? SparkWithdrawalNotSent else { + return .sparkWithdrawalPending(attempt) + } + return .failure(SendFailureContext( + error: refusal.underlying, + retryRoute: .confirm, + routingCacheResetAttempted: routingCacheResetAttempted, + paymentRequest: nil + )) + } + + /// Withdraws from Spark to the contact's on-chain address. A request it pays gets an on-chain proof with the + /// withdrawal's txid; the proof is started before the send, and Spark's journal settles it if the app stops mid-send. + private func performServiceRoutedPayment(_ leg: ServiceRouteLeg) async { + let paymentActivity = PaykitPaymentActivity.shared.begin() + defer { PaykitPaymentActivity.shared.end(paymentActivity) } + isSubmittingPayment = true + defer { isSubmittingPayment = false } + let context = app.contactPaymentContext + let request = context?.incomingPaymentRequest + var proofRequest: SparkContactWithdrawal.PaykitRequest? + var markProofStarted: (() async throws -> Void)? + do { + // The selected conversion quote's expiry bounds the send too, as on a direct send. + let paymentDeadline = try request?.submissionDeadline(quoteId: app.paykitPaymentTerms?.quoteId) + if let request { + guard let privateContext = context?.privatePaymentContext else { throw PaykitPaymentRequestError.requestUnavailable } + let identity = try await PaykitRouteService.startLegRequestProof( + prepareProof: { + try await PaykitPaymentProofService.shared.prepare( + request: request, + paymentAppId: privateContext.paymentAppId(for: leg.endpoint.methodId), + paymentEndpointIdentifier: leg.endpoint.methodId, + kind: .onchain, + paymentTerms: app.paykitPaymentTerms + ) + }, + prepareRequest: { try await prepareIncomingPaymentRequest() }, + paymentIdentity: { try await PaykitPaymentProofService.shared.onchainPaymentIdentity(requestId: request.id) }, + cancelProof: { await PaykitPaymentProofService.shared.cancelPreparation(request) }, + releasePaymentList: { await context?.resolvePrivatePaymentListConsumption(.definitePreBroadcastFailure) } + ) + // The proof and the journal keep the list version this send consumed, so dropping the withdrawal as + // unsent gives the list back, also after a kill before the proof started. + let previousVersion = await PrivatePaykitService.shared.consumedPaymentListVersion( + publicKey: request.counterparty, + attemptId: context?.id + ) + proofRequest = SparkContactWithdrawal.PaykitRequest( + id: request.id, + identity: identity, + paymentList: privateContext.paymentListVersion.map { + SparkContactWithdrawal.PaymentList(version: $0, previousVersion: previousVersion) + } + ) + // Spark's withdrawal runs this once its journal is written, so recovery owns the started proof. + markProofStarted = { + try await PaykitPaymentProofService.shared.markOnchainPaymentStarted( + request, + address: leg.endpoint.value, + paymentIdentity: identity, + privatePaymentListVersion: privateContext.paymentListVersion, + previousPrivatePaymentListVersion: previousVersion, + sparkWithdrawal: true + ) + } + } + let txid: String + do { + txid = try await PaykitRouteService.payReportingAllowance( + beginAllowance: { + guard let request else { return nil } + return try await PaykitAllowanceExecutor.shared.beginManualPayment( + request, + paymentEndpointIdentifier: leg.endpoint.methodId + ) + }, + authorize: { + if let request { + try await paykitPaymentRequestManager.ensurePaymentAllowed(request) + } + }, + markSending: { await PaykitAllowanceExecutor.shared.manualOnchainPaymentSending(attemptId: $0) }, + finishAllowance: { + await PaykitAllowanceExecutor.shared.finishManualPayment(attemptId: $0, outcome: $1, transactionId: $2) + } + ) { beforeSend in + try await withoutActuallyEscaping(beforeSend) { beforeSend in + try await PaykitRouteService.pay( + leg, + contact: context?.publicKey, + request: proofRequest, + tags: tagManager.selectedTagsArray, + paymentDeadline: paymentDeadline, + beforeSend: { + try await markProofStarted?() + try await beforeSend() + } + ) + } + } + } catch { + // Refused before Spark's send: nothing left, so this call's started proof goes. After it, the journal settles it. + let refusedBeforeSend = error is SparkWithdrawalNotSent + if let proofRequest, PaykitRouteService.legFailureReleasesProof( + error, + openJournalRequest: SparkManager.pendingContactWithdrawal?.request, + proofRequest: proofRequest + ) { + await PaykitPaymentProofService.shared.failSparkOnchainPayment(requestId: proofRequest.id, identity: proofRequest.identity) + } + if refusedBeforeSend, let request { + // A refusal before the proof was marked started leaves it prepared; started proofs stay as they are. + await PaykitPaymentProofService.shared.cancelPreparation(request) + } + await context?.resolvePrivatePaymentListConsumption(refusedBeforeSend ? .definitePreBroadcastFailure : .uncertain) + Logger.error("Service route payment failed: \(error)", context: "SendConfirmation") + navigationPath.append(Self.serviceLegFailureRoute( + error, + attempt: SparkWithdrawalAttempt(address: leg.endpoint.value, amountSats: leg.deliveredSat, requestId: request?.id), + routingCacheResetAttempted: routingCacheResetAttempted + )) + return + } + await context?.resolvePrivatePaymentListConsumption(.succeeded) + Logger.info("Paid Paykit contact through \(leg.service) in \(txid)", context: "SendConfirmation") + navigationPath.append(.success(paymentId: txid)) + } catch { + Logger.error("Service route payment failed: \(error)", context: "SendConfirmation") + navigationPath.append(.failure(SendFailureContext( + error: error, + retryRoute: .confirm, + routingCacheResetAttempted: routingCacheResetAttempted, + paymentRequest: nil + ))) + } + } + private func performPayment(isAutomatic: Bool) async throws { let paymentActivity = PaykitPaymentActivity.shared.begin() defer { PaykitPaymentActivity.shared.end(paymentActivity) } @@ -1722,7 +2101,11 @@ struct SendConfirmationView: View { private func validatePayment() async -> [WarningType] { var warnings: [WarningType] = [] - let amount: UInt64 = if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice { + // A Spark leg delivers its amount on-chain from Spending, so its amount and fee get the on-chain checks. + let leg = app.paykitRoute?.serviceLeg + let amount: UInt64 = if let leg { + leg.deliveredSat + } else if app.selectedWalletToPayFrom == .lightning, let invoice = app.scannedLightningInvoice { wallet.sendAmountSats ?? invoice.amountSatoshis } else if app.selectedWalletToPayFrom == .onchain, let invoice = app.scannedOnchainInvoice { wallet.sendAmountSats ?? invoice.amountSatoshis @@ -1749,13 +2132,14 @@ struct SendConfirmationView: View { } // Check if fee > $10 (only for onchain) - if app.selectedWalletToPayFrom == .onchain { - if let feeUsd = currency.convert(sats: UInt64(transactionFee), to: "USD"), feeUsd.value > 10.0 { + if leg != nil || app.selectedWalletToPayFrom == .onchain { + let fee = leg.map { $0.debitSat.saturatingSub($0.deliveredSat) } ?? UInt64(max(0, transactionFee)) + if let feeUsd = currency.convert(sats: fee, to: "USD"), feeUsd.value > 10.0 { warnings.append(.fee) } // Check if fee > 50% of send amount - if transactionFee > 0 && UInt64(transactionFee) > amount / 2 { + if fee > 0 && fee > amount / 2 { warnings.append(.feePercentage) } @@ -1876,7 +2260,8 @@ struct SendConfirmationView: View { } guard request.pricing.conversion != nil else { return false } let terms = try? request.payment(using: app.paykitPaymentMethod, quoteId: app.paykitPaymentTerms?.quoteId) - let minimumAmount = app.selectedWalletToPayFrom == .lightning ? (app.lnurlPayData?.minSendableSat ?? 1) : UInt64(Env.dustLimit) + let paysLightning = app.selectedWalletToPayFrom == .lightning && app.paykitRoute?.serviceLeg == nil + let minimumAmount = paysLightning ? (app.lnurlPayData?.minSendableSat ?? 1) : UInt64(Env.dustLimit) let meetsMinimum = terms.map { $0.amount.atomic >= minimumAmount } == true if rebindMethod, !app.paykitUsesUsdt, !isSubmittingPayment, let previous = app.paykitPaymentTerms, previous.amount.asset == .btc, app.paykitReviewedAmount == previous.amount, @@ -2253,3 +2638,44 @@ struct SendConfirmationView: View { } } } + +#Preview("Spark leg with a request note") { + let onchain = PaykitEndpoint(methodId: "btc-regtest-p2wpkh", value: "bcrt1q6rhpng9evdsfnn833a4f4vej0asu6dk5srld6x") + let leg = ServiceRouteLeg( + service: SparkManager.routeService, + endpoint: onchain, + deliveredSat: 20000, + debitSat: 22190, + atomicity: "trusted", + validUntilUnix: 0 + ) + ScrollView { + SendConfirmationView( + navigationPath: .constant([]), + isSubmittingPayment: .constant(false), + hwSend: HwSendCoordinator(walletId: nil), + requestPinCheck: { true }, + prepareIncomingPaymentRequest: {}, + routingCacheResetAttempted: false, + isAmountReviewRequired: .constant(false) + ) + .paykitRouteView( + PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true, serviceLeg: leg), + totalFeeSat: 2190, + note: "Dinner on Friday" + ) + .padding(16) + } + .background(Color.black) + .environmentObject(AppViewModel()) + .environmentObject(ActivityListViewModel()) + .environmentObject(ContactsManager()) + .environmentObject(CurrencyViewModel()) + .environmentObject(FeeEstimatesManager()) + .environmentObject(SettingsViewModel.shared) + .environmentObject(SheetViewModel()) + .environmentObject(WalletViewModel()) + .environmentObject(TagManager()) + .environment(HwWalletManager()) + .preferredColorScheme(.dark) +} diff --git a/Bitkit/Views/Wallets/Send/SendPendingScreen.swift b/Bitkit/Views/Wallets/Send/SendPendingScreen.swift index 68438cb3b2..957936962d 100644 --- a/Bitkit/Views/Wallets/Send/SendPendingScreen.swift +++ b/Bitkit/Views/Wallets/Send/SendPendingScreen.swift @@ -38,6 +38,8 @@ struct SendPendingScreen: View { var hardwareWalletId: String? var hardwareTransactionId: String? var hardwarePaymentIdentity: String? + /// The Spark withdrawal this screen waits on, whose journal settles it. + var sparkWithdrawal: SparkWithdrawalAttempt? var proofService: PaykitPaymentProofService = .shared var requestPinCheck: () async -> Bool = { false } @Binding var navigationPath: [SendRoute] @@ -107,7 +109,10 @@ struct SendPendingScreen: View { } private var pendingAmountSats: UInt64? { - pendingHardwareWalletId == nil ? onchainAttempt?.amountSats ?? pendingOnchainProof?.onchainAmountSats ?? wallet + if let sparkWithdrawal { + return sparkWithdrawal.amountSats + } + return pendingHardwareWalletId == nil ? onchainAttempt?.amountSats ?? pendingOnchainProof?.onchainAmountSats ?? wallet .sendAmountSats : pendingOnchainProof?.onchainAmountSats } @@ -279,7 +284,7 @@ struct SendPendingScreen: View { { applyOnchainPaymentResolution(resolution) } - } else if !onchainStateUnavailable { + } else if !onchainStateUnavailable, Self.readsNodeOnchainAttempts(sparkWithdrawal: sparkWithdrawal) { do { let loaded = try await Self.loadOrdinaryPending( using: attemptService, context: ordinaryPendingContext, @@ -316,7 +321,7 @@ struct SendPendingScreen: View { await searchForActivity() // Completion events are one-shot. Keep the visible original operation in sync // with its durable result even when an event preceded subscription or initialization. - while paymentHash == nil, paykitPaymentRequestId == nil, pendingHardwareWalletId == nil, + while paymentHash == nil, paykitPaymentRequestId == nil, pendingHardwareWalletId == nil, sparkWithdrawal == nil, !ordinarySendResolved, !Task.isCancelled { do { try await Task.sleep(for: .seconds(2)) } @@ -326,7 +331,9 @@ struct SendPendingScreen: View { } .task { // The request can end, or a failed check recover, while this screen stays open. - while paymentHash == nil, abandonableAttempt == nil, !Task.isCancelled { + while paymentHash == nil, abandonableAttempt == nil, Self.readsNodeOnchainAttempts(sparkWithdrawal: sparkWithdrawal), + !Task.isCancelled + { if pendingHardwareWalletId == nil { guard await loadAbandonableAttempt() else { return } } @@ -347,6 +354,43 @@ struct SendPendingScreen: View { .onReceive(PaykitPaymentProofService.onchainPaymentResolutionPublisher.receive(on: DispatchQueue.main)) { resolution in applyOnchainPaymentResolution(resolution) } + .onReceive(SparkManager.contactWithdrawalResolutionPublisher.receive(on: DispatchQueue.main)) { resolution in + applySparkWithdrawalResolution(resolution) + } + .task { + // The journal may have closed before this screen subscribed. + guard let attempt = sparkWithdrawal, SparkManager.pendingContactWithdrawal?.attempt != attempt, + let resolution = SparkManager.lastContactWithdrawalResolution + else { return } + applySparkWithdrawalResolution(resolution) + } + } + + private func applySparkWithdrawalResolution(_ resolution: SparkContactWithdrawalResolution) { + guard !ordinarySendResolved, let attempt = sparkWithdrawal, + let route = Self.sparkWithdrawalRoute(for: resolution, attempt: attempt) + else { return } + ordinarySendResolved = true + navigationPath.append(route) + } + + /// Whether the screen reads the node wallet's on-chain send attempts: never for a Spark withdrawal, which creates + /// none, so an unrelated unresolved send never shows as this one; its journal settles it instead. + static func readsNodeOnchainAttempts(sparkWithdrawal: SparkWithdrawalAttempt?) -> Bool { + sparkWithdrawal == nil + } + + /// Where the journal's close takes the screen waiting on `attempt`: a success once Spark sent it, a failure that can + /// be tried again once it never did, and nowhere for another withdrawal. + static func sparkWithdrawalRoute(for resolution: SparkContactWithdrawalResolution, attempt: SparkWithdrawalAttempt) -> SendRoute? { + guard resolution.attempt == attempt else { return nil } + if let txId = resolution.txId { + return .success(paymentId: txId) + } + return .failure(SendFailureContext( + error: AppError(message: "wallet__payment_failed_description", debugMessage: "Spark never sent the contact withdrawal"), + retryRoute: .confirm + )) } @MainActor @@ -542,6 +586,9 @@ struct SendPendingScreen: View { } private var onchainPendingMessage: String { + if sparkWithdrawal != nil { + return t("wallet__onchain_unknown_pending") + } if onchainStateUnavailable { return t("wallet__onchain_state_unavailable") } diff --git a/Bitkit/Views/Wallets/Send/SendSheet.swift b/Bitkit/Views/Wallets/Send/SendSheet.swift index fe64d37c0f..3dde24f4b1 100644 --- a/Bitkit/Views/Wallets/Send/SendSheet.swift +++ b/Bitkit/Views/Wallets/Send/SendSheet.swift @@ -69,6 +69,7 @@ enum SendRoute: Hashable { paykitPaymentRequestId: PaykitPaymentRequest.ID? = nil ) case onchainPending(OnchainSendPendingContext) + case sparkWithdrawalPending(SparkWithdrawalAttempt) case onchainOperationPending(OnchainSendPendingContext, requestId: PaykitPaymentRequest.ID?) case hardwarePending(requestId: PaykitPaymentRequest.ID, walletId: String, transactionId: String, paymentIdentity: String?) case success(paymentId: String, walletId: String = WalletScope.default) @@ -299,7 +300,7 @@ struct SendSheet: View { /// For onchain: only need node running. private var shouldShowSyncOverlay: Bool { if isPreparingRequest || hwSend.isActive || flow.isResumingAcceptedOrdinarySend || app.paykitUsesUsdt || - (app.contactPaymentContext?.requiresAssetSelection == true && currentRoot == .amount && flow.navigationPath.isEmpty) + (app.contactPaymentPicksSource && currentRoot == .amount && flow.navigationPath.isEmpty) { return false } @@ -764,7 +765,7 @@ struct SendSheet: View { return .ready } if app - .paykitUsesUsdt || (app.contactPaymentContext?.requiresAssetSelection == true && currentRoot == .amount && flow.navigationPath.isEmpty) + .paykitUsesUsdt || (app.contactPaymentPicksSource && currentRoot == .amount && flow.navigationPath.isEmpty) { flow.hasValidatedAfterSync = true return .ready @@ -776,7 +777,7 @@ struct SendSheet: View { return .failed } - if let lnurlPayData = app.lnurlPayData, let requestedAmount { + if let lnurlPayData = app.lnurlPayData, app.paykitRoute?.serviceLeg == nil, let requestedAmount { let minimumAmount = max(1, lnurlPayData.minSendableSat) guard requestedAmount >= minimumAmount else { showPaymentSetupFailure( @@ -881,8 +882,8 @@ struct SendSheet: View { } } - // Validate onchain payment balance (for pure onchain invoices) - if let onchainInvoice = app.scannedOnchainInvoice { + // Validate onchain payment balance (for pure onchain invoices); a Spark route can pay it from spending + if app.paykitRoute?.offersSparkLeg != true, let onchainInvoice = app.scannedOnchainInvoice { let onchainBalance = max( LightningService.shared.balances?.spendableOnchainBalanceSats ?? 0, hwWalletManager.maximumFundingBalanceSats @@ -937,6 +938,12 @@ struct SendSheet: View { } } + /// Whether a request Savings and the hardware wallets can't cover is rejected before Confirm. One Spark can carry + /// reaches Confirm, which routes it from Spending, as a pure on-chain payment's check does. + static func rejectsUnfundedOnchainRequest(route: PaykitRouteUi?) -> Bool { + route?.offersSparkLeg != true + } + private func selectHardwareFundingSourceIfNeeded( amountSats: UInt64, requestId: PaykitPaymentRequest.ID @@ -1048,7 +1055,7 @@ struct SendSheet: View { // A failed estimate is not proof of insufficient funds. Keep the sheet open so the normal // confirmation path can retry instead of rejecting a payable request. - guard !hasUnavailableSource else { return true } + guard !hasUnavailableSource, Self.rejectsUnfundedOnchainRequest(route: app.paykitRoute) else { return true } let maximumAvailable = max(savingsAvailable ?? 0, hardwareSources.map(\.available).max() ?? 0) _ = validateOnchainBalanceAndDismissIfInsufficient( invoiceAmount: amountSats, @@ -1180,6 +1187,12 @@ struct SendSheet: View { routingCacheResetAttempted: flow.routingCacheResetAttempted, navigationPath: $flow.navigationPath ) + case let .sparkWithdrawalPending(attempt): + SendPendingScreen( + paymentHash: nil, retryRoute: .confirm, paymentRequest: nil, paykitPaymentRequestId: attempt.requestId, + routingCacheResetAttempted: flow.routingCacheResetAttempted, sparkWithdrawal: attempt, + navigationPath: $flow.navigationPath + ) case let .onchainPending(context): SendPendingScreen( paymentHash: nil, retryRoute: .confirm, paymentRequest: nil, paykitPaymentRequestId: nil, diff --git a/BitkitTests/PaykitAllowanceExecutorTests.swift b/BitkitTests/PaykitAllowanceExecutorTests.swift index 1f30747a90..ca39c69d0a 100644 --- a/BitkitTests/PaykitAllowanceExecutorTests.swift +++ b/BitkitTests/PaykitAllowanceExecutorTests.swift @@ -1821,6 +1821,26 @@ final class PaykitAllowanceExecutorTests: XCTestCase { XCTAssertNil(blocked) } + func testALaterSettlementClosesTheOpenManualAttemptOfItsRequest() async throws { + let harness = AllowanceHarness() + await harness.executor.activate(identity: Fixtures.identityKey) + let request = try Fixtures.paymentRequest() + let attemptId = try await harness.executor.beginManualPayment(request, paymentEndpointIdentifier: Fixtures.onchainIdentifier) + let openAttempt = try XCTUnwrap(attemptId) + await harness.executor.finishManualPayment(attemptId: openAttempt, outcome: .unknown) + + await harness.executor.settleManualPayment(requestId: request.id, outcome: .failed) + await harness.executor.settleManualPayment(requestId: request.id, outcome: .succeeded) + + let outcomes = await harness.sdk.recordedOutcomes + XCTAssertEqual(outcomes, [ + Paykit.PaymentOutcomeReport(attemptId: openAttempt, outcome: .unknown), + Paykit.PaymentOutcomeReport(attemptId: openAttempt, outcome: .failed), + ], "Only the open attempt settles, once") + let journal = await harness.executor.localState(identity: Fixtures.identityKey).journal + XCTAssertEqual(journal.map(\.stage), [.failed]) + } + func testRecoverySettlesAManualLightningPaymentRestoredFromABackupTakenBeforeTheSend() async throws { let harness = AllowanceHarness() await harness.executor.activate(identity: Fixtures.identityKey) diff --git a/BitkitTests/PaykitPaymentProofServiceTests.swift b/BitkitTests/PaykitPaymentProofServiceTests.swift index c9db89075d..b261b51cb8 100644 --- a/BitkitTests/PaykitPaymentProofServiceTests.swift +++ b/BitkitTests/PaykitPaymentProofServiceTests.swift @@ -1879,6 +1879,211 @@ final class PaykitPaymentProofServiceTests: XCTestCase { XCTAssertTrue(remainingProofs.isEmpty) } + func testSparkWithdrawalSubmitsItsTransactionIdAsTheOnchainProof() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let proofRemoved = expectation(description: "On-chain proof removed after submission") + let store = PaymentProofMemoryStore { proofs in + if proofs.isEmpty { + proofRemoved.fulfill() + } + } + let sdk = PaymentProofSdkMock(identity: identity, records: [record]) + let service = paymentProofService(sdk: sdk, store: store) + let txid = String(repeating: "cd", count: 32) + + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted(request, address: onchainAddress, sparkWithdrawal: true) + let completed = await service.completeSparkOnchainPayment(requestId: request.id, identity: identity, txid: txid) + await sdk.waitForSubmissionStart() + await fulfillment(of: [proofRemoved], timeout: 1) + + XCTAssertTrue(completed, "Spark's withdrawal is no node send attempt, yet its txid completes the proof") + let retried = await service.completeSparkOnchainPayment(requestId: request.id, identity: identity, txid: txid) + XCTAssertTrue(retried, "A journal retry after the proof was saved must not keep the withdrawal open forever") + let lastSubmission = await sdk.lastSubmission() + let submission = try XCTUnwrap(lastSubmission) + XCTAssertEqual(submission.paymentEndpointIdentifier, endpoint) + XCTAssertEqual( + try proofValues(submission.proof.exportText()), + ["data": txid, "type": PaykitPaymentProofKind.onchain.rawValue] + ) + } + + func testSparkWithdrawalThatNeverWentOutDropsItsStartedProof() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) + + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted(request, address: onchainAddress, sparkWithdrawal: true) + await service.failSparkOnchainPayment(requestId: request.id, identity: identity) + + let remaining = await store.snapshot() + XCTAssertTrue(remaining.isEmpty) + } + + func testAnUnsentSparkWithdrawalKeepsItsProofUntilItsAllowanceAttemptIsSettled() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted(request, address: onchainAddress, sparkWithdrawal: true) + + let unsettled = await service.failSparkOnchainPayment(requestId: request.id, identity: identity, settleAllowance: { false }) + XCTAssertEqual(unsettled, .failed, "A failed allowance write keeps the journal open for a retry") + let kept = await store.snapshot() + XCTAssertEqual(kept.count, 1, "The proof stays until its allowance attempt is settled, so a restart still settles it") + + var proofsWhileSettling: Int? + let released = await service.failSparkOnchainPayment(requestId: request.id, identity: identity, settleAllowance: { + proofsWhileSettling = await store.snapshot().count + return true + }) + XCTAssertEqual(released, .released) + XCTAssertEqual(proofsWhileSettling, 1, "The allowance attempt is settled before its proof is removed") + let remaining = await store.snapshot() + XCTAssertTrue(remaining.isEmpty) + } + + func testAnUnstartedSparkWithdrawalSettlesNoAllowanceAttempt() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: PaymentProofMemoryStore()) + var settled = false + + let release = await service.failSparkOnchainPayment(requestId: request.id, identity: identity, settleAllowance: { + settled = true + return true + }) + + XCTAssertEqual(release, .nothingStarted) + XCTAssertFalse(settled, "Only a started Spark proof has an allowance attempt to settle") + } + + func testClosingASparkJournalLeavesADirectOnchainProofForTheSameRequest() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) + + // A kill left the Spark journal open with only a prepared proof, and the request was then paid directly. + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted(request, address: onchainAddress) + await service.failSparkOnchainPayment(requestId: request.id, identity: identity) + + let remaining = await store.snapshot() + XCTAssertEqual(remaining.count, 1, "The direct send's proof is not the Spark withdrawal's to drop") + } + + func testAnUnsentSparkWithdrawalProofThatCantBeDroppedSaysSo() async throws { + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) + + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted(request, address: onchainAddress, sparkWithdrawal: true) + await store.failNextSave() + let failed = await service.failSparkOnchainPayment(requestId: request.id, identity: identity) + + XCTAssertEqual(failed, .failed, "The journal stays open only when the caller learns the proof is still there") + let remaining = await store.snapshot() + XCTAssertEqual(remaining.count, 1) + let retried = await service.failSparkOnchainPayment(requestId: request.id, identity: identity) + XCTAssertEqual(retried, .released) + let afterRetry = await store.snapshot() + XCTAssertTrue(afterRetry.isEmpty) + } + + func testAnUnsentSparkWithdrawalGivesBackItsPrivateListAfterARelaunch() async throws { + snapshotAppDefaultsDomain() + UserDefaults.standard.removeObject(forKey: PrivatePaykitService.cacheStateKey) + let privatePaykit = PrivatePaykitService() + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let sdk = PaymentProofSdkMock(identity: identity, records: [record]) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: sdk, store: store) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 6), attemptId: UUID()) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 7), attemptId: UUID()) + + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted( + request, address: onchainAddress, privatePaymentListVersion: 7, previousPrivatePaymentListVersion: 6, sparkWithdrawal: true + ) + // Spark's journal closes the withdrawal as never sent after the app restarted. + let relaunched = paymentProofService(sdk: sdk, store: store) + await relaunched.failSparkOnchainPayment(requestId: request.id, identity: identity, privatePaykitService: privatePaykit) + + let remaining = await store.snapshot() + XCTAssertTrue(remaining.isEmpty) + let released = await privatePaykit.consumedPaymentListVersion(publicKey: request.counterparty) + XCTAssertEqual(released, 6) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 7), attemptId: UUID()) + } + + func testAKillBeforeTheSparkProofStartsGivesBackTheListAfterARelaunch() async throws { + snapshotAppDefaultsDomain() + UserDefaults.standard.removeObject(forKey: PrivatePaykitService.cacheStateKey) + let privatePaykit = PrivatePaykitService() + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let sdk = PaymentProofSdkMock(identity: identity, records: [record]) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: sdk, store: store) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 6), attemptId: UUID()) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 7), attemptId: UUID()) + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + + // Killed after the journal was written, before the proof was marked started: only the journal knows the list. + let relaunched = paymentProofService(sdk: sdk, store: store) + let release = await relaunched.failSparkOnchainPayment( + requestId: request.id, + identity: identity, + unstartedPaymentList: SparkContactWithdrawal.PaymentList(version: 7, previousVersion: 6), + privatePaykitService: privatePaykit + ) + + XCTAssertEqual(release, .nothingStarted) + let released = await privatePaykit.consumedPaymentListVersion(publicKey: request.counterparty) + XCTAssertEqual(released, 6, "The unsent request can be paid from its private list again") + } + + func testAnUnsentSparkWithdrawalLeavesAListAnotherPaymentConsumedSince() async throws { + snapshotAppDefaultsDomain() + UserDefaults.standard.removeObject(forKey: PrivatePaykitService.cacheStateKey) + let privatePaykit = PrivatePaykitService() + let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue + let record = try paymentRequestRecord(endpoints: [endpoint]) + let request = try XCTUnwrap(PaykitPaymentRequest(record: record, now: Date())) + let store = PaymentProofMemoryStore() + let service = paymentProofService(sdk: PaymentProofSdkMock(identity: identity, records: [record]), store: store) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 7), attemptId: UUID()) + + try await service.prepare(request: request, paymentAppId: "paykit-server", paymentEndpointIdentifier: endpoint, kind: .onchain) + try await service.markOnchainPaymentStarted( + request, address: onchainAddress, privatePaymentListVersion: 7, previousPrivatePaymentListVersion: nil, sparkWithdrawal: true + ) + try await privatePaykit.consumePrivatePaymentList(publicKey: request.counterparty, context: listContext(version: 8), attemptId: UUID()) + await service.failSparkOnchainPayment(requestId: request.id, identity: identity, privatePaykitService: privatePaykit) + + let remaining = await store.snapshot() + XCTAssertTrue(remaining.isEmpty) + let consumed = await privatePaykit.consumedPaymentListVersion(publicKey: request.counterparty) + XCTAssertEqual(consumed, 8) + } + func testOnchainCompletionDoesNotWaitForProofDelivery() async throws { let endpoint = PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue let record = try paymentRequestRecord(endpoints: [endpoint]) @@ -3395,6 +3600,10 @@ final class PaykitPaymentProofServiceTests: XCTestCase { return (format(start), format(end)) } + private func listContext(version: UInt64) -> PrivatePaykitPaymentContext { + PrivatePaykitPaymentContext(paymentAppsByEndpoint: [:], paymentListVersion: version) + } + private func paymentProofService( sdk: PaymentProofSdkMock, store: PaymentProofMemoryStore, diff --git a/BitkitTests/PaykitPaymentRequestServiceTests.swift b/BitkitTests/PaykitPaymentRequestServiceTests.swift index c1c7f06618..818a020b03 100644 --- a/BitkitTests/PaykitPaymentRequestServiceTests.swift +++ b/BitkitTests/PaykitPaymentRequestServiceTests.swift @@ -7110,6 +7110,24 @@ final class PaykitPaymentRequestServiceTests: XCTestCase { XCTAssertFalse(manager.isApprovedForPayment(request)) } + func testDismissedRequestIsNotPresentedAgainWhenTheSdkListsItAsProposedAgain() async throws { + let sdk = try PaymentRequestSdkMock(records: [paymentRequestRecord()]) + let manager = paymentRequestManager(sdk: sdk) + await manager.refresh() + let request = try XCTUnwrap(manager.requestsForPresentation().first) + XCTAssertTrue(manager.markPresentedIfPending(request)) + + try await manager.dismiss(request) + try await sdk.setRecords([paymentRequestRecord(state: .rejected)]) + await manager.refresh() + XCTAssertTrue(manager.pendingRequests.isEmpty) + + try await sdk.setRecords([paymentRequestRecord()]) + await manager.refresh() + XCTAssertEqual(manager.pendingRequests.map(\.id), [request.id]) + XCTAssertTrue(manager.requestsForPresentation().isEmpty) + } + func testFailedRejectionDropsRequestRemovedFromAuthoritativeQueue() async throws { let sdk = try PaymentRequestSdkMock(records: [paymentRequestRecord()]) let manager = paymentRequestManager(sdk: sdk) diff --git a/BitkitTests/PaykitRouteSettlingTests.swift b/BitkitTests/PaykitRouteSettlingTests.swift new file mode 100644 index 0000000000..b6c6dc4e3f --- /dev/null +++ b/BitkitTests/PaykitRouteSettlingTests.swift @@ -0,0 +1,87 @@ +@testable import Bitkit +import BitkitCore +import Paykit +import XCTest + +final class PaykitRouteSettlingTests: XCTestCase { + private let onchain = PaykitEndpoint(methodId: "btc-regtest-p2wpkh", value: "bcrt1q6rhpng9evdsfnn833a4f4vej0asu6dk5srld6x") + + @MainActor + func testASparkLegIsRefusedWhileAnEarlierContactWithdrawalSettles() async { + snapshotAppDefaultsDomain() + SparkManager.pendingContactWithdrawal = SparkContactWithdrawal( + address: "bcrt1qearlier", + amountSats: 5000, + contact: "earlier", + startedAt: 1 + ) + let app = AppViewModel() + defer { ToastWindowManager.shared.hideToast() } + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.selectedWalletToPayFrom = .lightning + let onchain = onchain + var quoted = false + + let outcome = await app.routeContactPayment( + PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true), + amountSats: 9000, + source: .spending, + lightningSpendableSats: 10000, + onchainSpendableSats: 0, + request: nil + ) { route, amountSats, source, lightningSats, onchainSats in + try await PaykitRouteService.route( + route, amountSats: amountSats, source: source, lightningSpendableSats: lightningSats, onchainSpendableSats: onchainSats + ) { _, amountSats in + quoted = true + return [ServiceRouteLeg( + service: SparkManager.routeService, + endpoint: onchain, + deliveredSat: amountSats, + debitSat: amountSats + 300, + atomicity: "trusted", + validUntilUnix: 0 + )] + } + } + + XCTAssertEqual(outcome, .refused, "Spark takes one contact withdrawal at a time, so Confirm must not offer a second") + XCTAssertFalse(quoted, "No Spark leg is quoted while the earlier withdrawal's journal is open") + XCTAssertEqual(ToastWindowManager.shared.currentToast?.accessibilityIdentifier, "PaykitRouteSettlingToast") + } + + @MainActor + func testAShortBalanceNamesItselfBeforeASettlingWithdrawal() async { + snapshotAppDefaultsDomain() + SparkManager.pendingContactWithdrawal = SparkContactWithdrawal( + address: "bcrt1qearlier", + amountSats: 5000, + contact: "earlier", + startedAt: 1 + ) + let app = AppViewModel() + defer { ToastWindowManager.shared.hideToast() } + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.selectedWalletToPayFrom = .lightning + + let outcome = await app.routeContactPayment( + PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true), + amountSats: 20000, + source: .spending, + lightningSpendableSats: 10000, + onchainSpendableSats: 0, + request: nil + ) { route, amountSats, source, lightningSats, onchainSats in + try await PaykitRouteService.route( + route, amountSats: amountSats, source: source, lightningSpendableSats: lightningSats, onchainSpendableSats: onchainSats + ) { _, _ in [] } + } + + XCTAssertEqual(outcome, .refused) + XCTAssertEqual( + ToastWindowManager.shared.currentToast?.accessibilityIdentifier, + "PaykitRouteBalanceToast", + "No balance covers 20,000, whatever an earlier withdrawal does, as on Android" + ) + } +} diff --git a/BitkitTests/PaykitRouteTests.swift b/BitkitTests/PaykitRouteTests.swift new file mode 100644 index 0000000000..39d557b917 --- /dev/null +++ b/BitkitTests/PaykitRouteTests.swift @@ -0,0 +1,1431 @@ +@testable import Bitkit +import BitkitCore +import BreezSdkSpark +import Paykit +import XCTest + +final class PaykitRouteTests: XCTestCase { + private let onchain = PaykitEndpoint(methodId: "btc-regtest-p2wpkh", value: "bcrt1q6rhpng9evdsfnn833a4f4vej0asu6dk5srld6x") + private let lightning = PaykitEndpoint( + methodId: "btc-lightning-lnurl", + value: "lnurl1dp68gurn8ghj7um9wfmxjcm99e3k7mf0v9cxj0m385ekvcenxc6r2c35xvukxefcv5mkvv34x5ekzd3ev56nyd3hxqurzepexejxxepnxscrvwfnv9nxzcn9xq6xyefhvgcxxcmyxymnserxfq5fns" + ) + + private func sparkLeg(amountSats: UInt64, feeSats: UInt64) -> ServiceRouteLeg { + ServiceRouteLeg( + service: SparkManager.routeService, + endpoint: onchain, + deliveredSat: amountSats, + debitSat: amountSats + feeSats, + atomicity: "trusted", + validUntilUnix: UInt64(Date().timeIntervalSince1970) + 600 + ) + } + + // MARK: - Request + + func testSpendingOffersEveryEndpointAndSavingsOnlyTheOnchainOnes() { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true) + let leg = sparkLeg(amountSats: 20000, feeSats: 300) + + let spending = PaykitRouteService.request( + route: route, amountSats: 20000, source: .spending, lightningSpendableSats: 50000, onchainSpendableSats: 90000, + serviceLegs: [leg] + ) + let savings = PaykitRouteService.request( + route: route, amountSats: 20000, source: .savings, lightningSpendableSats: 50000, onchainSpendableSats: 90000, + serviceLegs: [leg] + ) + + XCTAssertEqual(spending.contactEndpoints, [lightning, onchain]) + XCTAssertEqual(spending.lightningSpendableSat, 50000) + XCTAssertEqual(spending.onchainSpendableSat, 0) + XCTAssertEqual(spending.serviceLegs, [leg]) + XCTAssertEqual(savings.contactEndpoints, [onchain]) + XCTAssertEqual(savings.lightningSpendableSat, 0) + XCTAssertEqual(savings.onchainSpendableSat, 90000) + XCTAssertTrue(savings.serviceLegs.isEmpty) + } + + // MARK: - Router outcomes + + func testRouterPaysTheLnurlEndpointItPicksFromSpending() throws { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: false) + + let picked = try paykitRoutePayment( + request: PaykitRouteService.request( + route: route, amountSats: 20, source: .spending, lightningSpendableSats: 5000, onchainSpendableSats: 0, + serviceLegs: [] + ), + network: .regtest + ) + + XCTAssertEqual(picked, .direct(endpoint: lightning)) + } + + func testRouterPaysTheOnchainEndpointItPicksFromSavings() throws { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: false) + + let picked = try paykitRoutePayment( + request: PaykitRouteService.request( + route: route, amountSats: 20000, source: .savings, lightningSpendableSats: 0, onchainSpendableSats: 90000, + serviceLegs: [] + ), + network: .regtest + ) + + XCTAssertEqual(picked, .direct(endpoint: onchain)) + } + + func testRouterTakesTheSparkLegToAnOnchainOnlyContactFromSpending() throws { + let route = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + let leg = sparkLeg(amountSats: 20000, feeSats: 300) + + let picked = try paykitRoutePayment( + request: PaykitRouteService.request( + route: route, amountSats: 20000, source: .spending, lightningSpendableSats: 50000, onchainSpendableSats: 0, + serviceLegs: [leg] + ), + network: .regtest + ) + + XCTAssertEqual(picked, .service(leg: leg)) + var routed = route + routed.serviceLeg = leg + XCTAssertEqual(routed.totalFeeSat, 300) + XCTAssertEqual(routed.deliveredSat, 20000) + } + + func testRouterFindsNoneWithoutABalanceThatReachesTheContact() throws { + let route = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: false) + + let picked = try paykitRoutePayment( + request: PaykitRouteService.request( + route: route, amountSats: 20000, source: .savings, lightningSpendableSats: 0, onchainSpendableSats: 5000, + serviceLegs: [] + ), + network: .regtest + ) + + guard case .none = picked else { return XCTFail("Expected no route, got \(picked)") } + XCTAssertTrue(PaykitRouteService.isBalanceShort(amountSats: 20000, lightningSpendableSats: 0, onchainSpendableSats: 5000)) + XCTAssertFalse(PaykitRouteService.isBalanceShort(amountSats: 20000, lightningSpendableSats: 0, onchainSpendableSats: 90000)) + } + + // MARK: - Spark leg offer + + func testSparkLegIsOfferedForAnOnchainContactWhileSparkCanRoute() { + let onchainOnly = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [Self.endpoint(.regtestOnchainP2wpkh, onchain.value)] + ) + + XCTAssertEqual( + PaykitRouteService.routeUi(for: onchainOnly, canRouteThroughSpark: true)?.offersSparkLeg, + true + ) + XCTAssertEqual( + PaykitRouteService.routeUi(for: onchainOnly, canRouteThroughSpark: false)?.offersSparkLeg, + false + ) + let usdtOnly = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: [ + Self.endpoint(.usdtArbitrum, "0x0000000000000000000000000000000000000001"), + ]) + XCTAssertNil(PaykitRouteService.routeUi(for: usdtOnly, canRouteThroughSpark: true)) + } + + func testASparkWithdrawalIsWeighedAgainstSparksBalanceNotTheLightningLimit() { + let route = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + var quoted = route + quoted.serviceLeg = sparkLeg(amountSats: 999_000, feeSats: 500) + + // Lightning's limit of 997,506 sats never caps a withdrawal from Spark's 1,000,000. + XCTAssertEqual( + PaykitRouteService.sparkWithdrawalValidity(route: route, amountSats: 999_000, sparkBalanceSats: 1_000_000), + true, + "continue asks spark for a quote" + ) + XCTAssertEqual( + PaykitRouteService.sparkWithdrawalValidity(route: quoted, amountSats: 999_000, sparkBalanceSats: 1_000_000), + true, + "the quoted debit fits spark's balance" + ) + XCTAssertEqual( + PaykitRouteService.sparkWithdrawalValidity(route: quoted, amountSats: 999_000, sparkBalanceSats: 999_499), + false, + "a debit past spark's balance can't be sent" + ) + XCTAssertNil( + PaykitRouteService.sparkWithdrawalValidity(route: route, amountSats: 1_000_001, sparkBalanceSats: 1_000_000), + "past spark's balance, lightning's limit decides" + ) + XCTAssertNil( + PaykitRouteService.sparkWithdrawalValidity( + route: PaykitRouteUi(endpoints: [onchain], offersSparkLeg: false), + amountSats: 999_000, + sparkBalanceSats: 1_000_000 + ), + "without a spark leg, lightning's limit decides" + ) + } + + // MARK: - Contact withdrawal journal + + func testJournaledWithdrawalMatchesOnlyItsOwnAttempt() { + let other = Self.withdrawal(id: "other", to: "bcrt1qother", amountSats: 20000, timestamp: 1001) + let earlier = Self.withdrawal(id: "earlier", to: onchain.value, amountSats: 20000, timestamp: 2000) + let sent = Self.withdrawal(id: "sent", to: onchain.value, amountSats: 20000, timestamp: 1001) + var pending = SparkContactWithdrawal( + address: onchain.value, + amountSats: 20000, + contact: "contact", + startedAt: 1000, + earlierPaymentIds: SparkManager.withdrawalIds(to: onchain.value, amountSats: 20000, in: [other, earlier]) + ) + + XCTAssertEqual(pending.earlierPaymentIds, ["earlier"]) + XCTAssertEqual(SparkManager.matchingWithdrawal(pending, in: [other, earlier, sent])?.id, "sent") + XCTAssertNil( + SparkManager.matchingWithdrawal(pending, in: [other, earlier]), + "An earlier withdrawal to the same address is never this attempt" + ) + + pending.paymentId = "sent" + XCTAssertNil(SparkManager.matchingWithdrawal(pending, in: [other, earlier]), "Once Spark returned the attempt, only that payment settles it") + XCTAssertEqual(SparkManager.matchingWithdrawal(pending, in: [earlier, sent])?.id, "sent") + } + + func testUnlistedWithdrawalIsDroppedOnlyAfterTheExpiry() { + var pending = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000) + let expiry = SparkManager.contactWithdrawalExpirySecs + + XCTAssertFalse( + SparkManager.canCloseUnlisted(pending, now: 1001), + "A sync right after the send may not list the withdrawal yet" + ) + XCTAssertTrue(SparkManager.canCloseUnlisted(pending, now: 1000 + expiry)) + + pending.paymentId = "sent" + XCTAssertFalse( + SparkManager.canCloseUnlisted(pending, now: 1000 + expiry * 10), + "A withdrawal Spark returned went out and is never dropped as unsent" + ) + } + + func testAWithdrawalSparkListsWithoutDetailsIsMatchedByItsKeyAndKeptOpen() { + let pending = SparkContactWithdrawal( + address: onchain.value, + amountSats: 20000, + contact: "contact", + startedAt: 1000, + idempotencyKey: "key" + ) + var listed = Self.withdrawal(id: "key", to: onchain.value, amountSats: 20000, timestamp: 1001) + listed.status = .pending + listed.details = nil + let past = 1000 + SparkManager.contactWithdrawalExpirySecs * 10 + + let matched = SparkManager.matchingWithdrawal(pending, in: [listed]) + XCTAssertEqual(matched?.id, "key", "Spark keeps the send's idempotency key as the payment's id") + XCTAssertFalse( + SparkManager.canCloseUnlisted(pending, listed: matched, now: past), + "A withdrawal Spark lists without its details may still pay out, so its journal stays open" + ) + + listed.status = .failed + XCTAssertTrue( + SparkManager.canCloseUnlisted(pending, listed: SparkManager.matchingWithdrawal(pending, in: [listed]), now: past), + "One Spark failed before it had withdrawal details never pays out" + ) + } + + func testAFailedWithdrawalStaysOpenAfterASyncThatNeverReachedSpark() async { + var allowedClears: [Bool] = [] + // The sync call returns, but Spark keeps its failed sync in `lastSyncError`, so it never synced after the failure. + await SparkManager.settleAfterFailedWithdrawal( + failedAt: 1000, + syncWallet: {}, + hasSynced: { _ in false }, + settle: { allowedClears.append($0) } + ) + XCTAssertEqual(allowedClears, [false], "A sync that never reached Spark can't show the withdrawal was never sent") + + var syncedAfter: UInt64? + await SparkManager.settleAfterFailedWithdrawal( + failedAt: 1000, + syncWallet: {}, + hasSynced: { syncedAfter = $0; return true }, + settle: { allowedClears.append($0) } + ) + XCTAssertEqual(syncedAfter, 1000) + XCTAssertEqual(allowedClears, [false, true]) + + // Spark's `.synced` event also follows a sync that never reached it. + await SparkManager.settleAfterSync(since: 900, hasSynced: { syncedAfter = $0; return false }, settle: { allowedClears.append($0) }) + XCTAssertEqual(syncedAfter, 900) + XCTAssertEqual(allowedClears, [false, true, false], "A synced event alone can't show the withdrawal was never sent") + } + + func testJournalStaysOpenUntilEveryLocalRecordIsSaved() async { + let saved = await SparkManager.recordWithdrawalLocally(saveProof: { true }, saveActivity: { true }, saveTags: { true }) + XCTAssertTrue(saved) + + var tagsTried = false + let activityFailed = await SparkManager.recordWithdrawalLocally( + saveProof: { true }, + saveActivity: { false }, + saveTags: { tagsTried = true; return true } + ) + XCTAssertFalse(activityFailed, "A failed activity write keeps the journal for a retry") + XCTAssertFalse(tagsTried, "Tags wait for the activity they belong to") + + var activityTried = false + let proofFailed = await SparkManager.recordWithdrawalLocally( + saveProof: { false }, + saveActivity: { activityTried = true; return true }, + saveTags: { true } + ) + XCTAssertFalse(proofFailed, "A proof that wasn't saved keeps the journal for a retry") + XCTAssertTrue(activityTried, "The activity is still written when the proof save fails") + + let tagsFailed = await SparkManager.recordWithdrawalLocally(saveProof: { true }, saveActivity: { true }, saveTags: { false }) + XCTAssertFalse(tagsFailed) + } + + func testUnsentWithdrawalKeepsItsJournalUntilTheProofIsReleased() async { + snapshotAppDefaultsDomain() + let request = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee"), + identity: "payer" + ) + let pending = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000, request: request) + SparkManager.pendingContactWithdrawal = pending + + var failedAllowances: [SparkContactWithdrawal.PaykitRequest] = [] + await SparkManager.closeUnsentWithdrawal( + pending, + releaseProof: { _, _ in .failed }, + failAllowance: { failedAllowances.append($0); return true } + ) + XCTAssertEqual(SparkManager.pendingContactWithdrawal, pending, "A proof that wasn't released keeps the journal, so the next sync retries it") + XCTAssertEqual(failedAllowances, [], "The attempt stays unknown while the journal is still open") + + var released: SparkContactWithdrawal.PaykitRequest? + await SparkManager.closeUnsentWithdrawal( + pending, + releaseProof: { request, failAllowance in + released = request + return await failAllowance() ? .released : .failed + }, + failAllowance: { failedAllowances.append($0); return true } + ) + XCTAssertEqual(released, request) + XCTAssertEqual(failedAllowances, [request], "An unsent withdrawal fails its allowance attempt, so the ledger lets the request be paid again") + XCTAssertNil(SparkManager.pendingContactWithdrawal) + + // A kill before the proof started leaves no Spark attempt, so a direct send's attempt for the request stays. + SparkManager.pendingContactWithdrawal = pending + failedAllowances = [] + await SparkManager.closeUnsentWithdrawal( + pending, + releaseProof: { _, _ in .nothingStarted }, + failAllowance: { failedAllowances.append($0); return true } + ) + XCTAssertEqual(failedAllowances, [], "Only the Spark withdrawal's own allowance attempt fails") + XCTAssertNil(SparkManager.pendingContactWithdrawal) + } + + func testLegReportsItsAllowanceAttemptWithTheSendsOutcome() async { + struct Refused: Error {} + struct Lost: Error {} + var events: [String] = [] + func pay( + authorize: @escaping () async throws -> Void = {}, + send: @escaping (() async throws -> Void) async throws -> String + ) async -> String? { + try? await PaykitRouteService.payReportingAllowance( + beginAllowance: { events.append("begin"); return "attempt" }, + authorize: { events.append("authorize"); try await authorize() }, + markSending: { events.append("sending \($0)") }, + finishAllowance: { events.append("finish \($0) \($1) \($2 ?? "-")") }, + pay: send + ) + } + + let txid = await pay { beforeSend in try await beforeSend(); return "txid" } + XCTAssertEqual(txid, "txid") + XCTAssertEqual(events, ["begin", "authorize", "sending attempt", "finish attempt succeeded txid"]) + + events = [] + _ = await pay(authorize: { throw Refused() }) { beforeSend in + do { try await beforeSend() } catch { throw SparkWithdrawalNotSent(underlying: error) } + return "txid" + } + XCTAssertEqual(events, ["begin", "authorize", "finish attempt failed -"], "A send Spark refused paid nothing") + + events = [] + _ = await pay { beforeSend in + try await beforeSend() + throw SparkWithdrawalNotSent(underlying: Refused()) + } + XCTAssertEqual( + events, + ["begin", "authorize", "sending attempt", "finish attempt failed -"], + "A withdrawal Spark returned as failed paid nothing either" + ) + + events = [] + _ = await pay { beforeSend in try await beforeSend(); throw Lost() } + XCTAssertEqual( + events, + ["begin", "authorize", "sending attempt", "finish attempt unknown -"], + "A send that may have gone out stays unknown until recovery settles it" + ) + } + + func testAWithdrawalSparkReturnsAsFailedEndsAsARefusal() throws { + let sent = Self.withdrawal(id: "sent", to: onchain.value, amountSats: 20000, timestamp: 1001) + XCTAssertEqual(try SparkManager.sentWithdrawalId(sent), "tx-sent") + + var failed = sent + failed.status = .failed + XCTAssertThrowsError(try SparkManager.sentWithdrawalId(failed), "A failed withdrawal paid nothing, so it never shows success") { + XCTAssertTrue($0 is SparkWithdrawalNotSent, "A refusal releases the request's proof, private list and allowance attempt") + } + } + + @MainActor + func testAClosedJournalTellsThePendingScreenHowItsWithdrawalEnded() async { + snapshotAppDefaultsDomain() + let request = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee"), + identity: "payer" + ) + let pending = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000, request: request) + SparkManager.pendingContactWithdrawal = pending + var resolutions: [SparkContactWithdrawalResolution] = [] + let subscription = SparkManager.contactWithdrawalResolutionPublisher.sink { resolutions.append($0) } + defer { subscription.cancel() } + + await SparkManager.closeUnsentWithdrawal(pending, releaseProof: { _, _ in .released }, failAllowance: { _ in true }) + + let unsent = SparkContactWithdrawalResolution(attempt: pending.attempt, txId: nil) + XCTAssertEqual(resolutions, [unsent]) + XCTAssertEqual(SparkManager.lastContactWithdrawalResolution, unsent, "A screen that opens later still learns it") + guard case .failure = SendPendingScreen.sparkWithdrawalRoute(for: unsent, attempt: pending.attempt) else { + return XCTFail("A withdrawal that never went out can be tried again") + } + XCTAssertEqual( + SendPendingScreen.sparkWithdrawalRoute( + for: SparkContactWithdrawalResolution(attempt: pending.attempt, txId: "txid"), + attempt: pending.attempt + ), + .success(paymentId: "txid") + ) + let other = SparkWithdrawalAttempt(address: onchain.value, amountSats: 30000, requestId: request.id) + XCTAssertNil(SendPendingScreen.sparkWithdrawalRoute(for: unsent, attempt: other), "Another withdrawal's close leaves the screen") + } + + @MainActor + func testAWithdrawalsJournalIsWrittenBeforeItsProofStarts() async { + struct Refused: Error {} + var steps: [String] = [] + + try? await SparkManager.startJournaledWithdrawal( + writeJournal: { steps.append("journal") }, + beforeSend: { steps.append("proof started") }, + closeUnsent: { steps.append("closed") } + ) + XCTAssertEqual(steps, ["journal", "proof started"], "A kill after the proof starts leaves a journal that releases it") + + steps = [] + do { + try await SparkManager.startJournaledWithdrawal( + writeJournal: { steps.append("journal") }, + beforeSend: { steps.append("proof started"); throw Refused() }, + closeUnsent: { steps.append("closed") } + ) + XCTFail("A refusal before the send must reach the caller") + } catch { + XCTAssertTrue(error is SparkWithdrawalNotSent) + } + XCTAssertEqual(steps, ["journal", "proof started", "closed"], "A refusal closes the journal, releasing what it started") + } + + @MainActor + func testAWithdrawalWhoseQuoteExpiresBeforeItSendsNeverLeaves() async { + var now = Date(timeIntervalSince1970: 1_800_000_000) + var steps: [String] = [] + do { + try await SparkManager.startJournaledWithdrawal( + writeJournal: { steps.append("journal") }, + beforeSend: { + // The quote expires while the allowance and the request are checked. + now = now.addingTimeInterval(120) + steps.append("proof started") + }, + closeUnsent: { steps.append("closed") }, + paymentDeadline: PaykitPreciseInstant(date: now.addingTimeInterval(60)), + now: { now } + ) + XCTFail("An expired quote must stop the send") + } catch let error as SparkWithdrawalNotSent { + XCTAssertEqual(error.underlying as? PaykitPaymentRequestError, .requestExpired) + } catch { + XCTFail("Unexpected error \(error)") + } + XCTAssertEqual(steps, ["journal", "proof started", "closed"], "The refusal closes the journal, releasing the started proof") + } + + func testAPendingWithdrawalStaysOpenUntilSparkAcceptsItsPayout() { + XCTAssertEqual( + SparkManager.settlement(of: .pending), + .wait, + "Spark keeps a withdrawal pending until the provider accepts its payout, and it can still fail" + ) + XCTAssertEqual(SparkManager.settlement(of: .completed), .record) + XCTAssertEqual(SparkManager.settlement(of: .failed), .closeUnsent) + } + + @MainActor + func testADefiniteSparkRefusalClosesTheWithdrawalAtOnce() async { + var steps: [String] = [] + let refused = await SparkManager.withdrawalSendFailure( + SdkError.InsufficientFunds(tokenIdentifier: nil), + closeUnsent: { steps.append("closed") }, + settleLater: { steps.append("settle later") } + ) + XCTAssertTrue(refused is SparkWithdrawalNotSent, "Spark picks leaves before anything reaches the operators") + XCTAssertEqual(steps, ["closed"], "A refusal releases the journal at once instead of after the expiry") + + steps = [] + let feeRose = await SparkManager.withdrawalSendFailure( + SdkError.InvalidInput( + "The onchain fee rose to 900 sats at the slowest speed, above the 500 sats quoted for this payment. Please re-prepare the payment." + ), + closeUnsent: { steps.append("closed") }, + settleLater: { steps.append("settle later") } + ) + XCTAssertTrue(feeRose is SparkWithdrawalNotSent, "Spark checks a refreshed quote's fee before it withdraws") + XCTAssertEqual(steps, ["closed"]) + + steps = [] + let unknown = await SparkManager.withdrawalSendFailure( + SdkError.SparkError("operators"), + closeUnsent: { steps.append("closed") }, + settleLater: { steps.append("settle later") } + ) + XCTAssertFalse(unknown is SparkWithdrawalNotSent) + XCTAssertEqual(steps, ["settle later"], "An outcome that may have sent it settles from the sync after it") + } + + @MainActor + func testASecondContactWithdrawalIsRefusedWhileTheFirstPrepares() throws { + snapshotAppDefaultsDomain() + SparkManager.pendingContactWithdrawal = nil + let spark = SparkManager.shared + try spark.claimContactWithdrawal() + defer { spark.releaseContactWithdrawalClaim() } + + XCTAssertThrowsError(try spark.claimContactWithdrawal(), "A second send must never overwrite the first one's journal") + spark.releaseContactWithdrawalClaim() + XCTAssertNoThrow(try spark.claimContactWithdrawal()) + } + + func testAnUnfundedRequestReachesConfirmWhileSparkCanCarryIt() throws { + let context = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [Self.endpoint(.regtestOnchainP2wpkh, onchain.value)] + ) + let offered = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true)) + let direct = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: false)) + + XCTAssertFalse(SendSheet.rejectsUnfundedOnchainRequest(route: offered), "Confirm routes it from Spending through Spark") + XCTAssertTrue(SendSheet.rejectsUnfundedOnchainRequest(route: direct)) + XCTAssertTrue(SendSheet.rejectsUnfundedOnchainRequest(route: nil)) + } + + @MainActor + func testAHardwareWalletPickOnAmountDropsTheSparkLeg() { + snapshotAppDefaultsDomain() + let app = AppViewModel() + var routed = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + routed.serviceLeg = sparkLeg(amountSats: 20000, feeSats: 2190) + app.paykitRoute = routed + app.selectedWalletToPayFrom = .lightning + + SendAmountView.selectWallet(of: .hardware(walletId: "trezor"), app: app) + + XCTAssertEqual(app.selectedWalletToPayFrom, .onchain) + XCTAssertNil(app.paykitRoute?.serviceLeg, "Confirm must never describe the Spark leg for a hardware wallet's send") + XCTAssertEqual(app.paykitRoute?.endpoints, routed.endpoints) + + app.paykitRoute = routed + SendAmountView.selectWallet(of: .savings, app: app) + XCTAssertEqual(app.paykitRoute, routed, "Savings asks the router again on Continue") + } + + func testAnLnurlOutsideItsLimitsLeavesTheSparkLegToTheRouter() { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true, lnurl: lnurlData(minSendableMsats: 5_000_000)) + let leg = sparkLeg(amountSats: 1000, feeSats: 2190) + + let below = PaykitRouteService.request( + route: route, + amountSats: 1000, + source: .spending, + lightningSpendableSats: 4000, + onchainSpendableSats: 0, + serviceLegs: [leg] + ) + XCTAssertEqual(below.contactEndpoints, [onchain], "An LNURL that refuses the amount must never win over the Spark leg") + + let within = PaykitRouteService.request( + route: route, + amountSats: 6000, + source: .spending, + lightningSpendableSats: 10000, + onchainSpendableSats: 0, + serviceLegs: [] + ) + XCTAssertEqual(within.contactEndpoints, [lightning, onchain]) + } + + /// A route built after the scan, once Spark became ready, holds a contact's LNURL that was never decoded; the router + /// can still pick it, so the pick decodes it. + @MainActor + func testAnLnurlTheRouterPicksWithoutDecodedDataIsDecoded() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true) + let decoded = lnurlData(minSendableMsats: 1000) + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.selectedWalletToPayFrom = .lightning + let lightning = lightning + var decodedValues: [String] = [] + + let outcome = await app.routeContactPayment( + route, + amountSats: 2000, + source: .spending, + lightningSpendableSats: 10000, + onchainSpendableSats: 0, + request: nil, + router: { _, _, _, _, _ in .direct(endpoint: lightning) }, + decodeEndpoint: { value in + decodedValues.append(value) + return .lnurlPay(data: decoded) + } + ) + + XCTAssertEqual(outcome, .direct) + XCTAssertEqual(decodedValues, [lightning.value]) + XCTAssertEqual(app.lnurlPayData, decoded) + XCTAssertEqual(app.paykitRoute?.lnurl, decoded, "a later pick reuses the decoded LNURL") + } + + @MainActor + func testTheRouterIsAskedWithTheLnurlItsLimitsComeFrom() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true) + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.lnurlPayData = lnurlData(minSendableMsats: 5_000_000) + app.selectedWalletToPayFrom = .lightning + var asked: PaykitRouteUi? + + _ = await app.routeContactPayment( + route, + amountSats: 1000, + source: .spending, + lightningSpendableSats: 4000, + onchainSpendableSats: 0, + request: nil + ) { route, _, _, _, _ in + asked = route + return .service(leg: self.sparkLeg(amountSats: 1000, feeSats: 2190)) + } + + XCTAssertEqual(asked?.lnurl, app.lnurlPayData, "The router must see the LNURL's limits") + } + + @MainActor + func testAContactWhoseLnurlMinimumLightningPaysStillOffersSparkPastTheLightningLimit() async throws { + snapshotAppDefaultsDomain() + let lnurl = LnurlPayData( + uri: lightning.value, + callback: "https://example.com/pay", + minSendable: 1_000_000, + maxSendable: 2_000_000_000, + metadataStr: "[]", + commentAllowed: nil, + allowsNostr: false, + nostrPubkey: nil + ) + let address = onchain.value + let app = AppViewModel( + sheetViewModel: SheetViewModel(), + navigationViewModel: NavigationViewModel(), + scanPaymentOperations: ScanPaymentOperations( + state: { + ScanPaymentState( + isNodeRunning: true, + spendableOnchainBalanceSats: 0, + totalLightningBalanceSats: 997_506, + hasChannels: false, + hasUsableChannels: false + ) + }, + canSendLightning: { $0 <= 997_506 }, + decodeInvoice: { value in + value == address + ? .onChain(invoice: OnChainInvoice(address: address, amountSatoshis: 0, label: nil, message: nil, params: nil)) + : .lnurlPay(data: lnurl) + }, + canRouteThroughSpark: { true } + ) + ) + let context = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [ + Self.endpoint(.bitcoinLightningLnurl, lightning.value), + Self.endpoint(.regtestOnchainP2wpkh, address), + Self.endpoint(.usdtArbitrum, "0x1111111111111111111111111111111111111111"), + ] + ) + XCTAssertTrue(app.claimContactPaymentContext(context)) + + try await app.handleScannedData(lightning.value, claimedContactPaymentContext: context) + + XCTAssertEqual(app.lnurlPayData, lnurl) + XCTAssertEqual( + app.paykitRoute?.offersSparkLeg, + true, + "Lightning pays the LNURL's minimum, but a 999,000-sat payment past its 997,506 limit still needs Spark" + ) + } + + func testALightningPayableContactRoutesDirectWithoutASparkQuote() async throws { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true) + var quotes = 0 + + let direct = try await PaykitRouteService.route( + route, amountSats: 2000, source: .spending, lightningSpendableSats: 50000, onchainSpendableSats: 0 + ) { _, _ in quotes += 1; return [] } + XCTAssertEqual(direct, .direct(endpoint: lightning)) + XCTAssertEqual(quotes, 0, "Spark's quote is never fetched for a payment Lightning makes") + + let leg = sparkLeg(amountSats: 60000, feeSats: 300) + let routed = try await PaykitRouteService.route( + route, amountSats: 60000, source: .spending, lightningSpendableSats: 50000, onchainSpendableSats: 0 + ) { endpoints, amountSats in + quotes += 1 + XCTAssertEqual(endpoints, [self.onchain]) + XCTAssertEqual(amountSats, 60000) + return [leg] + } + XCTAssertEqual(routed, .service(leg: leg), "An amount past Lightning's limit still takes the quoted Spark leg") + XCTAssertEqual(quotes, 1) + } + + @MainActor + func testANoneRouteNamesTheLnurlLimitTheAmountMissed() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + defer { ToastWindowManager.shared.hideToast() } + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.lnurlPayData = lnurlData(minSendableMsats: 1_000_000) + app.selectedWalletToPayFrom = .lightning + + let outcome = await app.routeContactPayment( + PaykitRouteUi(endpoints: [lightning], offersSparkLeg: false), + amountSats: 500, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) + + XCTAssertEqual(outcome, .refused) + XCTAssertEqual( + ToastWindowManager.shared.currentToast?.accessibilityIdentifier, + "LnurlPayAmountTooLowToast", + "A contact with a working LNURL is payable, only not at this amount" + ) + } + + @MainActor + func testASparkLegItsFeeTakesPastTheBalanceShowsTheBalanceCopy() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + defer { ToastWindowManager.shared.hideToast() } + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.selectedWalletToPayFrom = .lightning + let fee = SendOnchainSpeedFeeQuote(userFeeSat: 750, l1BroadcastFeeSat: 1440) + + let outcome = await app.routeContactPayment( + PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true), + amountSats: 9000, + source: .spending, + lightningSpendableSats: 10000, + onchainSpendableSats: 0, + request: nil + ) { route, amountSats, source, lightningSats, onchainSats in + try await PaykitRouteService.route( + route, amountSats: amountSats, source: source, lightningSpendableSats: lightningSats, onchainSpendableSats: onchainSats + ) { endpoints, amountSats in + try await PaykitRouteService.sparkLegs(to: endpoints, amountSats: amountSats) { endpoint, amountSats in + try SparkManager.withdrawalRouteLeg( + endpoint: endpoint, amountSats: amountSats, fee: fee, validUntilUnix: 0, balanceSats: 10000 + ) + } + } + } + + XCTAssertEqual(outcome, .refused) + XCTAssertEqual( + ToastWindowManager.shared.currentToast?.accessibilityIdentifier, + "PaykitRouteBalanceToast", + "Spark holds 10,000 but the 9,000 withdrawal takes 11,190 with its fee, so the balance is what falls short" + ) + } + + @MainActor + func testAPendingWithdrawalSendIsHeldUntilItsJournalSettles() { + var pending = Self.withdrawal(id: "sent", to: onchain.value, amountSats: 20000, timestamp: 1001) + pending.status = .pending + + XCTAssertThrowsError(try SparkManager.sentWithdrawalId(pending), "A pending withdrawal can still fail, so it never shows success") { + XCTAssertFalse($0 is SparkWithdrawalNotSent, "It may still pay, so its proof and allowance attempt stay") + XCTAssertEqual( + SendConfirmationView.serviceLegFailureRoute( + $0, + attempt: SparkWithdrawalAttempt(address: self.onchain.value, amountSats: 20000, requestId: nil), + routingCacheResetAttempted: false + ), + .sparkWithdrawalPending(SparkWithdrawalAttempt(address: self.onchain.value, amountSats: 20000, requestId: nil)) + ) + } + } + + @MainActor + func testAMixedBitcoinContactWithoutUsdtOpensOnAmountWithTheSparkLeg() async throws { + snapshotAppDefaultsDomain() + let lnurl = lnurlData(minSendableMsats: 5_000_000) + let address = onchain.value + let sheets = SheetViewModel() + let app = AppViewModel( + sheetViewModel: sheets, + navigationViewModel: NavigationViewModel(), + scanPaymentOperations: ScanPaymentOperations( + state: { + ScanPaymentState( + isNodeRunning: true, + spendableOnchainBalanceSats: 0, + totalLightningBalanceSats: 10000, + hasChannels: false, + hasUsableChannels: false + ) + }, + canSendLightning: { $0 <= 10000 }, + decodeInvoice: { value in + value == address + ? .onChain(invoice: OnChainInvoice(address: address, amountSatoshis: 0, label: nil, message: nil, params: nil)) + : .lnurlPay(data: lnurl) + }, + canRouteThroughSpark: { true } + ) + ) + let context = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [Self.endpoint(.bitcoinLightningLnurl, lightning.value), Self.endpoint(.regtestOnchainP2wpkh, address)] + ) + XCTAssertFalse(context.requiresAssetSelection) + XCTAssertTrue(app.claimContactPaymentContext(context)) + + try await app.handleScannedData(lightning.value, claimedContactPaymentContext: context) + PaymentNavigationHelper.openPaymentSheet( + app: app, + currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, + sheetViewModel: sheets + ) + + XCTAssertEqual(app.paykitRoute?.offersSparkLeg, true, "2,000 sats below the LNURL's 5,000 minimum can still go through Spark") + XCTAssertEqual(app.scannedOnchainInvoice?.address, address) + XCTAssertEqual(sheets.sendSheetItem?.initialRoute, .amount, "Amount picks the source, so the amount reaches the router") + } + + private func lnurlData(minSendableMsats: UInt64) -> LnurlPayData { + LnurlPayData( + uri: lightning.value, + callback: "https://example.com/pay", + minSendable: minSendableMsats, + maxSendable: 100_000_000, + metadataStr: "[]", + commentAllowed: nil, + allowsNostr: false, + nostrPubkey: nil + ) + } + + @MainActor + func testARouteThatReturnsAfterItsPaymentChangedNeverLandsOnTheNextOne() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let contactA = ContactPaymentContext(publicKey: "contacta", privatePaymentContext: nil, endpoints: []) + let contactB = ContactPaymentContext(publicKey: "contactb", privatePaymentContext: nil, endpoints: []) + let routeA = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + let routeB = PaykitRouteUi(endpoints: [lightning], offersSparkLeg: false) + app.contactPaymentContext = contactA + app.paykitRoute = routeA + + let outcome = await app.routeContactPayment( + routeA, + amountSats: 20000, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) { _, _, _, _, _ in + // Contact A's sheet is dismissed and contact B's opens while Spark quotes A's leg. + app.contactPaymentContext = contactB + app.paykitRoute = routeB + return .service(leg: self.sparkLeg(amountSats: 20000, feeSats: 300)) + } + + XCTAssertEqual(outcome, .stale) + XCTAssertEqual(app.paykitRoute, routeB, "contact A's leg must never pay contact B") + } + + @MainActor + func testARouteThatReturnsAfterTheSourceChangedNeverRestoresIt() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let route = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.paykitRoute = route + app.selectedWalletToPayFrom = .lightning + + let outcome = await app.routeContactPayment( + route, + amountSats: 20000, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) { _, _, _, _, _ in + // The user goes back to Savings while Spark quotes the Spending leg. + app.selectedWalletToPayFrom = .onchain + return .service(leg: self.sparkLeg(amountSats: 20000, feeSats: 300)) + } + + XCTAssertEqual(outcome, .stale) + XCTAssertEqual(app.selectedWalletToPayFrom, .onchain, "a superseded Spending quote must not take the source back") + XCTAssertNil(app.paykitRoute?.serviceLeg) + } + + @MainActor + func testARouteSupersededByANewerOneIsDropped() async { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let route = PaykitRouteUi(endpoints: [onchain], offersSparkLeg: true) + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.paykitRoute = route + app.selectedWalletToPayFrom = .lightning + var newer: PaykitRouteOutcome? + + let older = await app.routeContactPayment( + route, + amountSats: 20000, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) { _, _, _, _, _ in + // A new amount asks the router again before the first quote returns. + newer = await app.routeContactPayment( + route, + amountSats: 30000, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) { _, _, _, _, _ in .service(leg: self.sparkLeg(amountSats: 30000, feeSats: 300)) } + return .service(leg: self.sparkLeg(amountSats: 20000, feeSats: 300)) + } + + XCTAssertEqual(newer, .leg) + XCTAssertEqual(older, .stale) + XCTAssertEqual(app.paykitRoute?.serviceLeg?.deliveredSat, 30000, "the older amount's leg must not replace the newer one") + } + + @MainActor + func testADirectRerouteFromBolt11BackToLnurlPaysTheLnurl() async { + let (app, route, bolt11, lnurl) = openLightningContact() + + let first = await routeDirectly(app, route, to: bolt11) + XCTAssertEqual(first, .direct) + XCTAssertNil(app.lnurlPayData) + + let second = await routeDirectly(app, app.paykitRoute ?? route, to: lnurl) + XCTAssertEqual(second, .direct) + XCTAssertEqual(app.lnurlPayData?.uri, lnurl.value, "the LNURL pick must pay the LNURL, not the skipped invoice") + XCTAssertNil(app.scannedLightningInvoice) + } + + @MainActor + func testADirectRerouteFromLnurlBackToBolt11PaysTheInvoice() async { + let (app, route, bolt11, lnurl) = openLightningContact() + + let first = await routeDirectly(app, route, to: lnurl) + XCTAssertEqual(first, .direct) + XCTAssertNil(app.scannedLightningInvoice, "the LNURL pick must not leave the invoice to pay") + + let second = await routeDirectly(app, app.paykitRoute ?? route, to: bolt11) + XCTAssertEqual(second, .direct) + XCTAssertEqual(app.scannedLightningInvoice?.bolt11, bolt11.value) + XCTAssertNil(app.lnurlPayData) + } + + @MainActor + func testARerouteFromBolt11ToLnurlBelowItsMinimumShowsTheMinimumToast() async { + let (app, route, bolt11, lnurl) = openLightningContact(lnurlMinSendableMsats: 1_000_000) + defer { ToastWindowManager.shared.hideToast() } + + let first = await routeDirectly(app, route, to: bolt11) + XCTAssertEqual(first, .direct) + XCTAssertNil(app.lnurlPayData) + + let second = await routeDirectly(app, app.paykitRoute ?? route, to: lnurl, amountSats: 500) + XCTAssertEqual(second, .direct) + XCTAssertEqual(app.lnurlPayData?.uri, lnurl.value) + XCTAssertFalse(app.validateRoutedLnurlAmount(amountSats: 500), "the restored LNURL's minimum must stop Confirm") + let toast = ToastWindowManager.shared.currentToast + XCTAssertEqual(toast?.accessibilityIdentifier, "LnurlPayAmountTooLowToast") + XCTAssertEqual(toast?.title, t("wallet__lnurl_pay__error_min__title")) + XCTAssertEqual(toast?.description, t( + "wallet__lnurl_pay__error_min__description", + variables: ["amount": CurrencyFormatter.formatSats(1000)] + )) + } + + @MainActor + func testARerouteFromBolt11ToLnurlAboveItsMaximumShowsTheMaximumToast() async { + let (app, route, bolt11, lnurl) = openLightningContact(lnurlMaxSendableMsats: 3_000_000) + defer { ToastWindowManager.shared.hideToast() } + + let first = await routeDirectly(app, route, to: bolt11) + XCTAssertEqual(first, .direct) + XCTAssertNil(app.lnurlPayData) + + let second = await routeDirectly(app, app.paykitRoute ?? route, to: lnurl, amountSats: 4000) + XCTAssertEqual(second, .direct) + XCTAssertEqual(app.lnurlPayData?.uri, lnurl.value) + XCTAssertFalse(app.validateRoutedLnurlAmount(amountSats: 4000), "the restored LNURL's maximum must stop Confirm") + let toast = ToastWindowManager.shared.currentToast + XCTAssertEqual(toast?.accessibilityIdentifier, "LnurlPayAmountTooHighToast") + XCTAssertEqual(toast?.title, t("wallet__lnurl_pay__error_max__title")) + XCTAssertEqual(toast?.description, t("wallet__lnurl_pay__error_max__description")) + } + + @MainActor + private func openLightningContact( + lnurlMinSendableMsats: UInt64 = 1000, + lnurlMaxSendableMsats: UInt64 = 100_000_000 + ) -> (AppViewModel, PaykitRouteUi, PaykitEndpoint, PaykitEndpoint) { + snapshotAppDefaultsDomain() + let app = AppViewModel() + let bolt11 = PaykitEndpoint( + methodId: PublicPaykitService.MethodId.bitcoinLightningBolt11.rawValue, + value: "lnbcrt1contactreroute" + ) + app.contactPaymentContext = ContactPaymentContext(publicKey: "contact", privatePaymentContext: nil, endpoints: []) + app.scannedLightningInvoice = LightningInvoice( + bolt11: bolt11.value, + paymentHash: Data(), + amountSatoshis: 0, + timestampSeconds: 1, + expirySeconds: 3600, + isExpired: false, + description: nil, + networkType: .regtest, + payeeNodeId: nil + ) + app.lnurlPayData = LnurlPayData( + uri: lightning.value, + callback: "https://example.com/pay", + minSendable: lnurlMinSendableMsats, + maxSendable: lnurlMaxSendableMsats, + metadataStr: "[]", + commentAllowed: nil, + allowsNostr: false, + nostrPubkey: nil + ) + app.selectedWalletToPayFrom = .lightning + return (app, PaykitRouteUi(endpoints: [bolt11, lightning], offersSparkLeg: false), bolt11, lightning) + } + + @MainActor + private func routeDirectly( + _ app: AppViewModel, + _ route: PaykitRouteUi, + to endpoint: PaykitEndpoint, + amountSats: UInt64 = 2000 + ) async -> PaykitRouteOutcome { + await app.routeContactPayment( + route, + amountSats: amountSats, + source: .spending, + lightningSpendableSats: 50000, + onchainSpendableSats: 0, + request: nil + ) { _, _, _, _, _ in .direct(endpoint: endpoint) } + } + + @MainActor + func testAStaleRecoveryNeverClearsANewerWithdrawalsJournal() async { + snapshotAppDefaultsDomain() + let older = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000) + let newer = SparkContactWithdrawal(address: onchain.value, amountSats: 30000, contact: "contact", startedAt: 2000) + // A recovery captured the older withdrawal; another one closed it and the newer withdrawal wrote its journal. + SparkManager.pendingContactWithdrawal = newer + + await SparkManager.closeUnsentWithdrawal(older, releaseProof: { _, _ in .nothingStarted }, failAllowance: { _ in true }) + + XCTAssertEqual(SparkManager.pendingContactWithdrawal, newer, "Losing the newer journal could pay it twice") + } + + @MainActor + func testAStaleCloseNeverTellsTheNewerWithdrawalsScreenItEnded() async { + snapshotAppDefaultsDomain() + let request = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee"), + identity: "payer" + ) + // A retry of the same request: same address, amount and request, so both share one attempt. + let older = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000, request: request) + let newer = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 2000, request: request) + XCTAssertEqual(older.attempt, newer.attempt) + SparkManager.pendingContactWithdrawal = newer + var resolutions: [SparkContactWithdrawalResolution] = [] + let subscription = SparkManager.contactWithdrawalResolutionPublisher.sink { resolutions.append($0) } + defer { subscription.cancel() } + + await SparkManager.closeUnsentWithdrawal(older, releaseProof: { _, _ in .nothingStarted }, failAllowance: { _ in true }) + + XCTAssertEqual(SparkManager.pendingContactWithdrawal, newer) + XCTAssertEqual(resolutions, [], "An unsent resolution for the newer send's attempt would offer Try Again while it is in flight") + } + + @MainActor + func testAStaleCloseDuringARetryKeepsTheNewerProofAndAllowanceAttempt() async { + snapshotAppDefaultsDomain() + let request = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee"), + identity: "payer" + ) + let older = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1000, request: request) + let newer = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 2000, request: request) + SparkManager.pendingContactWithdrawal = newer + var released: [SparkContactWithdrawal.PaykitRequest] = [] + var failedAllowances: [SparkContactWithdrawal.PaykitRequest] = [] + + await SparkManager.closeUnsentWithdrawal( + older, + releaseProof: { request, failAllowance in + released.append(request) + return await failAllowance() ? .released : .failed + }, + failAllowance: { failedAllowances.append($0); return true } + ) + + XCTAssertEqual(released, [], "The proof matches by request, so a stale close would release the retry's started proof") + XCTAssertEqual(failedAllowances, [], "The retry's allowance attempt stays open while it is in flight") + XCTAssertEqual(SparkManager.pendingContactWithdrawal, newer) + } + + @MainActor + func testAPendingSparkSendNeverAdoptsTheNodesOnchainAttempt() { + let attempt = SparkWithdrawalAttempt(address: onchain.value, amountSats: 20000, requestId: nil) + + XCTAssertFalse( + SendPendingScreen.readsNodeOnchainAttempts(sparkWithdrawal: attempt), + "A Spark withdrawal never creates a node on-chain attempt, so an unrelated one must not show as this send" + ) + XCTAssertTrue(SendPendingScreen.readsNodeOnchainAttempts(sparkWithdrawal: nil)) + } + + func testLegPreparesTheRequestBeforeItsProofIsStarted() async throws { + var steps: [String] = [] + let identity = try await PaykitRouteService.startLegRequestProof( + prepareProof: { steps.append("proof") }, + prepareRequest: { steps.append("request") }, + paymentIdentity: { steps.append("identity"); return "payer" }, + cancelProof: { steps.append("cancel") }, + releasePaymentList: { steps.append("release") } + ) + + XCTAssertEqual(identity, "payer") + XCTAssertEqual(steps, ["proof", "request", "identity"], "The request is approved before Spark's payment check") + } + + func testLegThatFailsBeforeSendingFreesTheRequest() async { + struct Refused: Error {} + for failing in ["proof", "request"] { + var steps: [String] = [] + do { + _ = try await PaykitRouteService.startLegRequestProof( + prepareProof: { + if failing == "proof" { + throw Refused() + } + }, + prepareRequest: { + if failing == "request" { + throw Refused() + } + }, + paymentIdentity: { "payer" }, + cancelProof: { steps.append("cancel") }, + releasePaymentList: { steps.append("release") } + ) + XCTFail("\(failing) must fail the leg") + } catch {} + + XCTAssertEqual(steps, failing == "proof" ? ["release"] : ["cancel", "release"], failing) + } + } + + func testSourceSwitchOnConfirmReroutesOnlyWhenTheLegNoLongerFits() throws { + let context = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [Self.endpoint(.regtestOnchainP2wpkh, onchain.value)] + ) + let offered = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true)) + var routed = offered + routed.serviceLeg = sparkLeg(amountSats: 20000, feeSats: 2190) + + XCTAssertTrue(SendConfirmationView.sourceSwitchNeedsReroute(route: routed, walletType: .onchain)) + XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: routed, walletType: .lightning)) + XCTAssertTrue(SendConfirmationView.sourceSwitchNeedsReroute(route: offered, walletType: .lightning)) + XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: offered, walletType: .onchain)) + XCTAssertFalse(SendConfirmationView.sourceSwitchNeedsReroute(route: nil, walletType: .onchain)) + } + + func testADirectLnurlPickOnConfirmPaysOnTheLnurlConfirm() { + XCTAssertTrue(SendConfirmationView.reroutePaysLnurl(outcome: .direct, walletType: .lightning, hasInvoice: false, hasLnurl: true)) + XCTAssertFalse(SendConfirmationView.reroutePaysLnurl(outcome: .direct, walletType: .lightning, hasInvoice: true, hasLnurl: true)) + XCTAssertFalse(SendConfirmationView.reroutePaysLnurl(outcome: .leg, walletType: .lightning, hasInvoice: false, hasLnurl: true)) + XCTAssertFalse(SendConfirmationView.reroutePaysLnurl(outcome: .direct, walletType: .onchain, hasInvoice: false, hasLnurl: true)) + } + + /// A mixed contact paid directly from Savings keeps its decoded Lightning payment, so a switch to Spending must still + /// ask the router: over Lightning's limit only a Spark withdrawal pays it. + func testSourceSwitchToSpendingReroutesAMixedContactRoutedDirectFromSavings() { + let route = PaykitRouteUi(endpoints: [lightning, onchain], offersSparkLeg: true) + + XCTAssertTrue(SendConfirmationView.sourceSwitchNeedsReroute(route: route, walletType: .lightning)) + } + + func testASparkRoutedConfirmCanMoveToAnotherSource() throws { + let context = ContactPaymentContext( + publicKey: "contact", + privatePaymentContext: nil, + endpoints: [Self.endpoint(.regtestOnchainP2wpkh, onchain.value)] + ) + var routed = try XCTUnwrap(PaykitRouteService.routeUi(for: context, canRouteThroughSpark: true)) + routed.serviceLeg = sparkLeg(amountSats: 20000, feeSats: 2190) + + XCTAssertEqual( + SendConfirmationView.fundingSources(hasLightningInvoice: false, hasOnchainInvoice: true, offersSparkLeg: true, hardwareWalletIds: ["hw"]), + [.spending, .savings, .hardware(walletId: "hw")], + "Confirm on a Spark leg still offers Savings and the hardware wallet" + ) + // The router never runs for a hardware wallet, so its pick drops the leg for the on-chain send it signs. + XCTAssertNil(SendConfirmationView.route(routed, afterSelecting: .hardware(walletId: "hw"))?.serviceLeg) + XCTAssertEqual(SendConfirmationView.route(routed, afterSelecting: .hardware(walletId: "hw"))?.endpoints, routed.endpoints) + // Savings and Spending ask the router again, which settles the leg. + XCTAssertEqual(SendConfirmationView.route(routed, afterSelecting: .savings), routed) + XCTAssertEqual(SendConfirmationView.route(routed, afterSelecting: .spending), routed) + XCTAssertNil(SendConfirmationView.route(nil, afterSelecting: .hardware(walletId: "hw"))) + } + + func testTheFromControlStaysSwitchableOnASparkRoute() { + let sources = SendConfirmationView.fundingSources( + hasLightningInvoice: false, + hasOnchainInvoice: true, + offersSparkLeg: true, + hardwareWalletIds: [] + ) + let canSwitch = SendConfirmationView.canSwitchFundingSource(hasRetainedHardwareRetry: false, fundingSources: sources) + + let control = SendConfirmationView.sparkRouteFromControl(canSwitchFundingSource: canSwitch) + + XCTAssertTrue(control.isSwitchable, "After picking Spark, FROM still moves a fixed request to Savings") + XCTAssertEqual(control.titleKey, "wallet__spending__title") + // A retained hardware retry pins the source, on a Spark route too. + let pinned = SendConfirmationView.canSwitchFundingSource(hasRetainedHardwareRetry: true, fundingSources: sources) + XCTAssertFalse(SendConfirmationView.sparkRouteFromControl(canSwitchFundingSource: pinned).isSwitchable) + } + + func testARefusedRerouteOnConfirmKeepsTheSwipeOffUntilAnotherSourceIsPicked() { + let refused = SendConfirmationView.refusedRouteSource(after: .refused, on: .lightning, previous: nil) + + XCTAssertEqual(refused, .lightning) + XCTAssertTrue(SendConfirmationView.isSwipeDisabled( + walletType: .lightning, + isHardwarePayment: false, + isHardwareConfirmationUnavailable: false, + feeRate: 5, + isRouteRefused: refused == .lightning + ), "a refused route must keep the swipe off, so no private list is consumed for it") + XCTAssertFalse(SendConfirmationView.isSwipeDisabled( + walletType: .onchain, + isHardwarePayment: false, + isHardwareConfirmationUnavailable: false, + feeRate: 5, + isRouteRefused: refused == .onchain + ), "switching back to Savings pays the contact again") + XCTAssertNil(SendConfirmationView.refusedRouteSource(after: .leg, on: .lightning, previous: refused)) + } + + func testALateRerouteOutcomeKeepsAnotherSourcesRefusal() { + XCTAssertEqual(SendConfirmationView.refusedRouteSource(after: .direct, on: .onchain, previous: .lightning), .lightning) + XCTAssertEqual(SendConfirmationView.refusedRouteSource(after: .refused, on: .onchain, previous: .lightning), .onchain) + } + + func testOnchainRequestStartsOnSpendingWhenSavingsCantCoverIt() { + // Savings 5,000 can't cover a 20,000 request, so Spending (Spark 50,000) pays it through the leg. + XCTAssertTrue(SendConfirmationView.requestStartsOnSpending(savingsSendableSats: 5000, amountSats: 20000, offersSparkLeg: true)) + XCTAssertFalse(SendConfirmationView.requestStartsOnSpending(savingsSendableSats: 48000, amountSats: 20000, offersSparkLeg: true)) + XCTAssertFalse( + SendConfirmationView.requestStartsOnSpending(savingsSendableSats: 5000, amountSats: 20000, offersSparkLeg: false), + "Without a Spark leg the request stays on Savings" + ) + } + + func testConfirmOffersSpendingWhileASparkLegCanCarryAnOnchainRequest() { + // Savings covers the request, so its Confirm opens on Savings; Spending through Spark is still a source. + XCTAssertEqual( + SendConfirmationView.fundingSources(hasLightningInvoice: false, hasOnchainInvoice: true, offersSparkLeg: true, hardwareWalletIds: []), + [.spending, .savings] + ) + // Savings is short, so the request opens on Spending, which must be in the list to switch back to. + XCTAssertEqual( + SendConfirmationView.fundingSources(hasLightningInvoice: false, hasOnchainInvoice: true, offersSparkLeg: true, hardwareWalletIds: ["hw"]), + [.spending, .savings, .hardware(walletId: "hw")] + ) + XCTAssertEqual( + SendConfirmationView.fundingSources(hasLightningInvoice: false, hasOnchainInvoice: true, offersSparkLeg: false, hardwareWalletIds: []), + [.savings], + "Without a Spark leg an on-chain request has no Spending source" + ) + XCTAssertEqual( + SendConfirmationView.fundingSources(hasLightningInvoice: true, hasOnchainInvoice: true, offersSparkLeg: true, hardwareWalletIds: []), + [.spending, .savings] + ) + } + + func testRefusalWhileAnOlderJournalIsOpenReleasesThisCallsProof() { + struct Refused: Error {} + let older = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "older", counterparty: "payee"), + identity: "payer" + ) + let this = SparkContactWithdrawal.PaykitRequest( + id: PaykitPaymentRequest.ID(paymentRequestId: "this", counterparty: "payee"), + identity: "payer" + ) + let notSent = SparkWithdrawalNotSent(underlying: Refused()) + + XCTAssertTrue( + PaykitRouteService.legFailureReleasesProof(notSent, openJournalRequest: older, proofRequest: this), + "An older journal still open must not keep a refused send's proof started" + ) + XCTAssertTrue(PaykitRouteService.legFailureReleasesProof(notSent, openJournalRequest: nil, proofRequest: this)) + XCTAssertFalse( + PaykitRouteService.legFailureReleasesProof(notSent, openJournalRequest: this, proofRequest: this), + "An earlier attempt of the same request still owns its proof" + ) + XCTAssertFalse( + PaykitRouteService.legFailureReleasesProof(Refused(), openJournalRequest: this, proofRequest: this), + "A failure once Spark's send started is settled by the journal" + ) + } + + func testSparkLegDebitsTheL1BroadcastFeeToo() { + let fee = SendOnchainSpeedFeeQuote(userFeeSat: 750, l1BroadcastFeeSat: 1440) + + XCTAssertEqual(SparkManager.withdrawalDebitSats(amountSats: 2000, fee: fee), 4190, "Confirm and the fee check use 2,190, not 750") + XCTAssertThrowsError(try SparkManager.checkWithdrawalFee(2190, shownFeeSats: 750)) + } + + func testContactWithdrawalStaysASendNotATransfer() { + let toContact = Self.withdrawal(id: "contact", to: onchain.value, amountSats: 20000, timestamp: 1) + let toSavings = Self.withdrawal(id: "savings", to: "bcrt1qsavings", amountSats: 5000, timestamp: 1) + + let transfers = SparkManager.savingsTransferTxIds(unclaimed: [], payments: [toContact, toSavings], contactWithdrawals: ["tx-contact"]) + + XCTAssertEqual(transfers, ["tx-savings"]) + } + + func testSparkScreenWithdrawalsLeaveOutContactPayments() { + let saved = SparkManager.contactWithdrawalTxIds + defer { SparkManager.contactWithdrawalTxIds = saved } + SparkManager.contactWithdrawalTxIds = ["tx-contact"] + let toContact = Self.withdrawal(id: "contact", to: onchain.value, amountSats: 20000, timestamp: 1) + let toSavings = Self.withdrawal(id: "savings", to: "bcrt1qsavings", amountSats: 5000, timestamp: 1) + + XCTAssertEqual( + SparkManager.withdrawals([toContact, toSavings]).map(\.txid), + ["tx-savings"], + "A contact payment is not a transfer to savings" + ) + } + + func testSparkScreenWithdrawalsLeaveOutAPendingContactPayment() { + snapshotAppDefaultsDomain() + SparkManager.contactWithdrawalTxIds = [] + var toContact = Self.withdrawal(id: "contact", to: onchain.value, amountSats: 20000, timestamp: 1) + toContact.status = .pending + let toSavings = Self.withdrawal(id: "savings", to: "bcrt1qsavings", amountSats: 5000, timestamp: 1) + var journal = SparkContactWithdrawal(address: onchain.value, amountSats: 20000, contact: "contact", startedAt: 1) + SparkManager.pendingContactWithdrawal = journal + + XCTAssertEqual( + SparkManager.withdrawals([toContact, toSavings]).map(\.txid), + ["tx-savings"], + "Before Spark returns it, the open journal's address and amount tell the contact payment apart" + ) + journal.paymentId = "contact" + SparkManager.pendingContactWithdrawal = journal + XCTAssertEqual( + SparkManager.withdrawals([toContact, toSavings]).map(\.txid), + ["tx-savings"], + "A contact payment Spark keeps pending is not a transfer to savings" + ) + } + + private static func endpoint(_ methodId: PublicPaykitService.MethodId, _ value: String) -> PublicPaykitService.Endpoint { + PublicPaykitService.Endpoint(methodId: methodId, value: value, min: nil, max: nil, rawPayload: value) + } + + private static func withdrawal(id: String, to address: String, amountSats: UInt64, timestamp: UInt64) -> Payment { + Payment( + id: id, + paymentType: .send, + status: .completed, + amount: U128(amountSats), + fees: 300, + timestamp: timestamp, + method: .withdraw, + details: .withdraw(txId: "tx-\(id)", vout: 0, destinationAddress: address), + conversionDetails: nil + ) + } +} diff --git a/BitkitTests/SendConfirmationLifecycleTests.swift b/BitkitTests/SendConfirmationLifecycleTests.swift index a6d960d902..bf736eeca6 100644 --- a/BitkitTests/SendConfirmationLifecycleTests.swift +++ b/BitkitTests/SendConfirmationLifecycleTests.swift @@ -29,6 +29,50 @@ final class SendConfirmationLifecycleTests: XCTestCase { XCTAssertEqual(wallet.sendAmountSats, 10000) } + func testASparkFundedOnchainRequestKeepsItsOnchainPriceOnSpending() throws { + snapshotAppDefaultsDomain() + let request = try onchainRequest(rates: [ + ConversionRate(asset: "btc", value: "0.000002188"), + ConversionRate(asset: "btc-lightning", value: "0.00002"), + ]) + let app = AppViewModel() + app.scannedOnchainInvoice = invoice + let onchainTerms = try request.payment(using: app.paykitPaymentMethod) + + // Spending funds the Spark leg, which still pays the request's on-chain endpoint. + app.selectedWalletToPayFrom = .lightning + + XCTAssertEqual(try request.payment(using: app.paykitPaymentMethod), onchainTerms) + } + + func testASparkLegIgnoresTheUnselectedLnurlsPrice() throws { + snapshotAppDefaultsDomain() + let request = try onchainRequest(acceptsLightning: true, rates: [ + ConversionRate(asset: "btc", value: "0.000002188"), + ConversionRate(asset: "btc-lightning", value: "0.00002"), + ]) + let app = AppViewModel() + app.scannedOnchainInvoice = invoice + let onchainTerms = try request.payment(using: app.paykitPaymentMethod) + let endpoint = PaykitEndpoint(methodId: PublicPaykitService.MethodId.regtestOnchainP2wpkh.rawValue, value: invoice.address) + app.lnurlPayData = LnurlPayData( + uri: "lnurl1contact", callback: "https://example.com/callback", minSendable: 5_000_000, maxSendable: 100_000_000, + metadataStr: "[]", commentAllowed: nil, allowsNostr: false, nostrPubkey: nil + ) + app.paykitRoute = PaykitRouteUi( + endpoints: [endpoint], + offersSparkLeg: true, + serviceLeg: ServiceRouteLeg( + service: SparkManager.routeService, endpoint: endpoint, deliveredSat: 5000, debitSat: 5300, + atomicity: "trusted", validUntilUnix: 0 + ) + ) + + app.selectedWalletToPayFrom = .lightning + + XCTAssertEqual(try request.payment(using: app.paykitPaymentMethod), onchainTerms, "The leg pays the on-chain endpoint") + } + func testQuotedWalletSwitchRebindsAmountOnConfirmation() async throws { snapshotAppDefaultsDomain() snapshotAppGroupDefaults("home_screen_display_currency_code_v1", "home_screen_display_currency_symbol_v1") diff --git a/BitkitTests/SendConfirmationViewTests.swift b/BitkitTests/SendConfirmationViewTests.swift index 9ee79a26be..a1aefad92c 100644 --- a/BitkitTests/SendConfirmationViewTests.swift +++ b/BitkitTests/SendConfirmationViewTests.swift @@ -68,6 +68,26 @@ final class SendConfirmationViewTests: XCTestCase { )) } + func testARouteRefusedWhenConfirmOpensKeepsTheSwipeAndTheAutomaticPaymentOff() { + // Confirm's first routing call keeps a refusal the way a source switch does. + let refused = SendConfirmationView.refusedRouteSource(after: .refused, on: .lightning, previous: nil) + + XCTAssertFalse(SendConfirmationView.canStartAutomaticPayment( + shouldAutomaticallyPay: true, + hasStartedAutomaticPayment: false, + isSetupPending: false, + isPreparingWallet: false, + isRouteRefused: refused == .lightning + ), "an automatic attempt must not pay a source the router refused") + XCTAssertTrue(SendConfirmationView.isSwipeDisabled( + walletType: .lightning, + isHardwarePayment: false, + isHardwareConfirmationUnavailable: false, + feeRate: 5, + isRouteRefused: refused == .lightning + )) + } + func testAutomaticPaymentAwaitsFeeRateOnlyWhileItIsLoading() { XCTAssertTrue(SendConfirmationView.automaticPaymentAwaitsFeeRate(isFeeRateMissing: true, feeRateLoadFailed: false)) XCTAssertFalse(SendConfirmationView.automaticPaymentAwaitsFeeRate(isFeeRateMissing: true, feeRateLoadFailed: true)) @@ -189,4 +209,28 @@ final class SendConfirmationViewTests: XCTestCase { .uncertain ) } + + func testASparkLegThatMayHaveSentStaysPendingInsteadOfOfferingTryAgain() { + struct Refused: Error {} + struct Lost: Error {} + let attempt = SparkWithdrawalAttempt( + address: "bcrt1qcontact", + amountSats: 20000, + requestId: PaykitPaymentRequest.ID(paymentRequestId: "request", counterparty: "payee") + ) + + let unresolved = SendConfirmationView.serviceLegFailureRoute(Lost(), attempt: attempt, routingCacheResetAttempted: false) + XCTAssertEqual( + unresolved, + .sparkWithdrawalPending(attempt), + "Spark may have sent it, so the screen follows its journal until it settles" + ) + + let refused = SendConfirmationView.serviceLegFailureRoute( + SparkWithdrawalNotSent(underlying: Refused()), + attempt: attempt, + routingCacheResetAttempted: false + ) + guard case .failure = refused else { return XCTFail("A leg Spark refused before sending can be tried again") } + } } diff --git a/BitkitTests/SparkWithdrawalTests.swift b/BitkitTests/SparkWithdrawalTests.swift index 36f076e527..05594c3520 100644 --- a/BitkitTests/SparkWithdrawalTests.swift +++ b/BitkitTests/SparkWithdrawalTests.swift @@ -1,4 +1,5 @@ @testable import Bitkit +import BitkitCore import BreezSdkSpark import XCTest @@ -330,6 +331,108 @@ final class SparkWithdrawalTests: XCTestCase { XCTAssertFalse(SparkManager.isWithdrawal(txid: "payment", sent: ["sent"], withdrawals: listed)) } + func testASparkWithdrawalIsNeverBoosted() { + let pending = Payment( + id: "pending", + paymentType: .send, + status: .pending, + amount: 20000, + fees: 300, + timestamp: 1, + method: .withdraw, + details: .withdraw(txId: "listed", vout: 0, destinationAddress: "bcrt1qcontact"), + conversionDetails: nil + ) + + XCTAssertTrue(SparkManager.isSparkWithdrawal(txid: "contact", isSent: true, known: ["contact"], payments: [])) + XCTAssertTrue( + SparkManager.isSparkWithdrawal(txid: "listed", isSent: true, known: [], payments: [pending]), + "a pending withdrawal Spark lists can't be boosted" + ) + XCTAssertFalse(SparkManager.isSparkWithdrawal(txid: "savings", isSent: true, known: ["contact"], payments: [pending])) + } + + func testASparkWithdrawalsSavingsReceiptCanStillBeBoosted() { + XCTAssertFalse( + SparkManager.isSparkWithdrawal(txid: "transfer", isSent: false, known: ["transfer"], payments: []), + "Savings owns the output a Spark withdrawal pays it, so its receipt keeps CPFP" + ) + } + + // MARK: - Payout confirmation + + /// Spark lists a withdrawal completed once its provider took the payout on, before it is mined, so only a payout + /// output the chain lists in a block confirms its activity. + func testACompletedContactWithdrawalIsConfirmedOnlyOnceThePayoutIsMined() async { + let payouts = SparkManager.completedContactPayouts( + [ + withdrawal(txId: "mined", status: .completed), + withdrawal(txId: "mempool", status: .completed), + withdrawal(txId: "unlisted", status: .completed), + withdrawal(txId: "pending", status: .pending), + withdrawal(txId: "savings", status: .completed), + ], + contactWithdrawals: ["mined", "mempool", "unlisted", "pending"] + ) + let marked = TxIds() + + await SparkManager.confirmMinedPayouts( + payouts, + needsConfirmation: { _ in true }, + unspentOutputs: { _ in [Self.output(txId: "mined", confirmations: 1), Self.output(txId: "mempool", confirmations: 0)] }, + markConfirmed: { await marked.insert($0) } + ) + + let confirmed = await marked.ids + XCTAssertEqual(confirmed, ["mined"], "a payout still in the mempool or not yet broadcast stays unconfirmed") + } + + func testAConfirmedContactWithdrawalIsNotLookedUpAgain() async { + let lookups = TxIds() + + await SparkManager.confirmMinedPayouts( + [SparkManager.ContactPayout(txId: "mined", vout: 0, address: "bcrt1qcontact")], + needsConfirmation: { _ in false }, + unspentOutputs: { address in + await lookups.insert(address) + return [] + }, + markConfirmed: { _ in } + ) + + let looked = await lookups.ids + XCTAssertTrue(looked.isEmpty) + } + + private func withdrawal(txId: String, status: BreezSdkSpark.PaymentStatus) -> BreezSdkSpark.Payment { + Payment( + id: txId, + paymentType: .send, + status: status, + amount: 20000, + fees: 300, + timestamp: 1, + method: .withdraw, + details: .withdraw(txId: txId, vout: 1, destinationAddress: "bcrt1qcontact"), + conversionDetails: nil + ) + } + + private static func output(txId: String, confirmations: UInt32) -> AccountUtxo { + AccountUtxo( + txid: txId, + vout: 1, + amount: 20000, + blockHeight: confirmations > 0 ? 100 : 0, + address: "bcrt1qcontact", + path: "", + confirmations: confirmations, + coinbase: false, + own: false, + required: nil + ) + } + @MainActor private func waitUntilPriced(_ transfer: TransferViewModel) async { for _ in 0 ..< 100 where transfer.isPricingSparkWithdrawal { @@ -366,3 +469,11 @@ private actor PriceGate { private final class WithdrawnFee { var feeSats: UInt64? } + +private actor TxIds { + private(set) var ids: [String] = [] + + func insert(_ id: String) { + ids.append(id) + } +} diff --git a/changelog.d/next/1191.added.md b/changelog.d/next/1191.added.md new file mode 100644 index 0000000000..c908dc605f --- /dev/null +++ b/changelog.d/next/1191.added.md @@ -0,0 +1 @@ +Paykit contacts who only accept on-chain bitcoin can be paid from Spark. diff --git a/journeys/README.md b/journeys/README.md index a6dec62f88..7d652dd108 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -191,6 +191,7 @@ Known naming differences: | Pubky Ring choice row lookup spinner | `PubkyChoiceIdentityLookup` (the same tag on every row) | `PubkyChoiceRingLookup_` (bare z32 key) | | Contact import overview profile and friend count | — *(no tag; read the "Import" title and the "N friends" text)* | `ContactImportOverviewProfile`, `ContactImportOverviewSummary` | | Lightning Connections add connection | `add_connection_button` | `NavigationAction` | +| Send contact row | `SendContact_` | `SendContact-` | `SubscriptionRow-` matches Android exactly. `PaymentRequestRow` keeps that prefix but appends the billing period (`-one-time` for a one-off), because every recurring payment of one diff --git a/journeys/paykit-spark-route.xml b/journeys/paykit-spark-route.xml new file mode 100644 index 0000000000..2ed0eaa9a7 --- /dev/null +++ b/journeys/paykit-spark-route.xml @@ -0,0 +1,27 @@ + + + Proves that paying a Paykit contact whose only endpoint is on-chain, from a wallet whose spending balance is held + on Spark, routes through a Spark withdrawal straight to the contact's address, without the user picking a route, + and that the contact receives the exact amount on chain. + + Preconditions: a Debug build with SWIFT_ACTIVE_COMPILATION_CONDITIONS including E2E_BUILD, E2E_BACKEND=local, + E2E_NETWORK=regtest and E2E_HOMESERVER_PUBKY set to the local marketplace homeserver; bitkit-docker's default stack with the marketplace and payment-requests + profiles. The simulator reaches the host's loopback directly, so it needs no port forwarding. + The wallet has no channels and an empty savings balance, a Spark balance of at least 25 000 sats from Lightspark's + regtest faucet sent to the deposit address on the Spark screen, a Pubky profile on the local homeserver, and the + fixture-issuer's pubky saved as a contact. The contact is bitkit-docker's fixture-issuer, which publishes only a + btc-regtest-p2wpkh endpoint; Spark pays it on Lightspark's regtest chain. + + + Verify the savings balance (tag "ActivitySavings") shows 0 and the spending balance (tag "ActivitySpending") is above 25 000 + Tap Send (tag "Send"), then Contact (tag "RecipientContact") + Tap the fixture-issuer (tag "SendContact-" followed by its pubky) + Verify the amount screen (tag "SendAmount") offers SPENDING as the source + Enter 20000 and tap Continue (tag "ContinueAmount") + Verify the Confirm screen (tag "SendConfirm") is visible, then tap Show Details (tag "SendConfirmToggleDetails") + Verify FROM is SPENDING, TO is the contact, and ROUTE (tag "ReviewSwapRoute") reads "Spark" + Swipe to pay (tag "GRAB") + Verify the Bitcoin Sent screen (tag "SendSuccess") shows 20 000 + Verify Lightspark's regtest mempool shows the withdrawal transaction paying exactly 20 000 sats to the fixture-issuer's address + +