@@ -184,31 +184,38 @@ struct SpendingConfirm: View {
184184 let balance = UInt64 ( wallet. spendableOnchainBalanceSats)
185185 let allUtxos = try await lightningService. listSpendableOutputs ( )
186186
187- // Fee for normal send (recipient + change) - used to check if change would be dust
188- let utxos = try await lightningService. selectUtxosWithAlgorithm (
189- targetAmountSats: currentOrder. feeSat,
190- satsPerVbyte: fastFeeRate,
191- coinSelectionAlgorythm: . largestFirst,
192- utxos: nil
193- )
194- let normalFee = try await wallet. calculateTotalFee (
195- address: address,
196- amountSats: currentOrder. feeSat,
197- satsPerVByte: fastFeeRate,
198- utxosToSpend: utxos
199- )
200- let maxSendable = balance >= normalFee ? balance - normalFee : 0
201-
202- // Check if change would be dust (use sendAll in that case)
203- // This also covers the "max" case where expectedChange = 0
204- let useSendAll = DustChangeHelper . shouldUseSendAllToAvoidDust (
205- totalInput: balance,
206- amountSats: currentOrder. feeSat,
207- normalFee: normalFee
208- )
187+ // Try normal coin selection first; if it fails (e.g. insufficient funds
188+ // to cover amount + fee when sending near-max), fall through to sendAll.
189+ var useSendAll = false
190+ var normalFee : UInt64 = 0
191+ var normalUtxos : [ SpendableUtxo ] ?
192+
193+ do {
194+ let utxos = try await lightningService. selectUtxosWithAlgorithm (
195+ targetAmountSats: currentOrder. feeSat,
196+ satsPerVbyte: fastFeeRate,
197+ coinSelectionAlgorythm: . largestFirst,
198+ utxos: nil
199+ )
200+ normalFee = try await wallet. calculateTotalFee (
201+ address: address,
202+ amountSats: currentOrder. feeSat,
203+ satsPerVByte: fastFeeRate,
204+ utxosToSpend: utxos
205+ )
206+ normalUtxos = utxos
207+
208+ useSendAll = DustChangeHelper . shouldUseSendAllToAvoidDust (
209+ totalInput: balance,
210+ amountSats: currentOrder. feeSat,
211+ normalFee: normalFee
212+ )
213+ } catch {
214+ Logger . info ( " Normal coin selection failed, using sendAll: \( error) " )
215+ useSendAll = true
216+ }
209217
210218 if useSendAll {
211- // Use sendAll: change would be dust or zero (max case)
212219 let sendAllFee = try await wallet. calculateTotalFee (
213220 address: address,
214221 amountSats: balance,
@@ -223,10 +230,9 @@ struct SpendingConfirm: View {
223230 shouldUseSendAll = true
224231 }
225232 } else {
226- // Normal send with change output
227233 await MainActor . run {
228234 transactionFee = normalFee
229- selectedUtxos = utxos
235+ selectedUtxos = normalUtxos
230236 satsPerVbyte = fastFeeRate
231237 shouldUseSendAll = false
232238 }
0 commit comments