From 56bfb93bc812d0fa1692b3c3b5457ec74839a124 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jos=C3=A9=20A=2EP?=
<53834183+Jossec101@users.noreply.github.com>
Date: Wed, 25 Nov 2026 13:07:51 +0100
Subject: [PATCH 1/2] Warn before opening a channel whose outbound the
automatic swap-out would take
Opening a channel from a node with automatic liquidity management adds its capacity to the node's local balance. When
that leaves the balance over the swap-out threshold by at least a weighted provider's min swap, the next run swaps the
new outbound back out, paying swap fees. The channel request form now asks for confirmation in that case only; a hot
wallet's existing confirmation carries the same warning. The forecast shares the weighted-provider rule with
AutoLiquidityManagementJob.
---
src/Jobs/AutoLiquidityManagementJob.cs | 14 +-
src/Pages/ChannelRequests.razor | 141 +++++++++++++----
src/Services/SwapOutForecast.cs | 61 ++++++++
src/Services/SwapProviderLimits.cs | 16 ++
.../Services/SwapOutForecastTests.cs | 142 ++++++++++++++++++
5 files changed, 331 insertions(+), 43 deletions(-)
create mode 100644 src/Services/SwapOutForecast.cs
create mode 100644 test/NodeGuard.Tests/Services/SwapOutForecastTests.cs
diff --git a/src/Jobs/AutoLiquidityManagementJob.cs b/src/Jobs/AutoLiquidityManagementJob.cs
index d02c63c30..53ee7286e 100644
--- a/src/Jobs/AutoLiquidityManagementJob.cs
+++ b/src/Jobs/AutoLiquidityManagementJob.cs
@@ -121,22 +121,14 @@ public async Task Execute(IJobExecutionContext context)
}
/// The providers with a weight; all weights at 0 means Loop, as before.
- private List<(SwapProvider Provider, int Weight)> WeightedProviders(Node node)
+ private IReadOnlyList<(SwapProvider Provider, int Weight)> WeightedProviders(Node node)
{
- var weights = new List<(SwapProvider Provider, int Weight)>
- {
- (SwapProvider.Loop, node.LoopSwapWeight),
- (SwapProvider.FortySwap, node.FortySwapWeight),
- (SwapProvider.Spark, node.SparkSwapWeight)
- };
-
- if (weights.All(w => w.Weight <= 0))
+ if (node is { LoopSwapWeight: <= 0, FortySwapWeight: <= 0, SparkSwapWeight: <= 0 })
{
_logger.LogWarning("Node {NodeName} has total weight of 0, defaulting to Loop", node.Name);
- return [(SwapProvider.Loop, 1)];
}
- return weights.Where(w => w.Weight > 0).ToList();
+ return SwapProviderLimits.Weighted(node);
}
///
diff --git a/src/Pages/ChannelRequests.razor b/src/Pages/ChannelRequests.razor
index 1781942d5..c3c75c29e 100644
--- a/src/Pages/ChannelRequests.razor
+++ b/src/Pages/ChannelRequests.razor
@@ -9,6 +9,8 @@
@using Google.Protobuf
@using NBXplorer.Models
@using NodeGuard.Helpers;
+@using NodeGuard.Services.Spark
+@using System.Net
@attribute [Authorize(Roles = "FinanceManager, Superadmin, NodeManager")]
Channel Requests
@@ -565,11 +567,20 @@
{_swapOutWarning}")}")"
OkLabel="Yes, I am sure"
OnCancel="@ApproveOperationCloseConfirmationModal"
OnSubmit="@ApproveOperationSubmitConfirmationModal"/>
+
+
? _channelRequests;
@@ -637,6 +649,9 @@
private bool _createInFlight;
private ConfirmationModal _approveOperationConfirmationModal;
private ConfirmationModal _markRequestAsFailedConfirmationModal;
+ private ConfirmationModal _swapOutConfirmationModal;
+ // Why the open request being created would be swapped right back out, or null when it would not.
+ private string? _swapOutWarning;
private UTXOSelectorModal _utxoSelectorModalRef;
private List _selectedUTXOs = new();
private MempoolRecommendedFeesType _selectedMempoolRecommendedFeesType;
@@ -901,45 +916,25 @@
};
var selectedWallet = await WalletRepository.GetById(_selectedWalletId.Value);
+ _swapOutWarning = await SwapOutWarningAsync(request);
-
- if (selectedWallet.IsHotWallet)
+ if (selectedWallet.IsHotWallet || _swapOutWarning != null)
{
_selectedRequest = request;
await datagridRef.Edit(null);
- await _approveOperationConfirmationModal.ShowModal();
+ if (selectedWallet.IsHotWallet)
+ {
+ await _approveOperationConfirmationModal.ShowModal();
+ }
+ else
+ {
+ await _swapOutConfirmationModal.ShowModal();
+ }
await ResetChannelRequestRejectModal();
return;
}
- var createChannelResult = await ChannelOperationRequestRepository.AddAsync(request);
-
- if (createChannelResult.Item1)
- {
- ToastService.ShowSuccess("Open channel request created!");
- await AuditService.LogAsync(
- AuditActionType.Create,
- AuditEventType.Success,
- AuditObjectType.ChannelOperationRequest,
- request.Id.ToString(),
- new { Amount = amount, SourceNodeId = _selectedSourceNodeId, DestNodeId = _selectedDestNode?.Id, Description = $"Channel open request created. Amount: {amount} BTC, SourceNodeId: {_selectedSourceNodeId}, DestNodeId: {_selectedDestNode?.Id}" });
-
- if (_selectedUTXOs.Count > 0)
- {
- await CoinSelectionService.LockUTXOs(_selectedUTXOs, request, BitcoinRequestType.ChannelOperation);
- }
- }
- else
- {
- ToastService.ShowError(createChannelResult.Item2);
- await AuditService.LogAsync(
- AuditActionType.Create,
- AuditEventType.Failure,
- AuditObjectType.ChannelOperationRequest,
- null,
- new { Error = createChannelResult.Item2, Description = $"Failed to create channel open request. Error: {createChannelResult.Item2}" });
- }
- _utxoSelectorModalRef.ClearModal();
+ await CreateOpenRequestAsync(request);
}
else
{
@@ -952,6 +947,88 @@
await ReloadAllRequestsGrid();
}
+ ///
+ /// Creates a cold-wallet open request and locks its selected UTXOs.
+ ///
+ private async Task CreateOpenRequestAsync(ChannelOperationRequest request)
+ {
+ var amount = new Money(request.SatsAmount).ToUnit(MoneyUnit.BTC);
+ var createChannelResult = await ChannelOperationRequestRepository.AddAsync(request);
+
+ if (createChannelResult.Item1)
+ {
+ ToastService.ShowSuccess("Open channel request created!");
+ await AuditService.LogAsync(
+ AuditActionType.Create,
+ AuditEventType.Success,
+ AuditObjectType.ChannelOperationRequest,
+ request.Id.ToString(),
+ new { Amount = amount, SourceNodeId = request.SourceNodeId, DestNodeId = request.DestNodeId, Description = $"Channel open request created. Amount: {amount} BTC, SourceNodeId: {request.SourceNodeId}, DestNodeId: {request.DestNodeId}" });
+
+ if (_selectedUTXOs.Count > 0)
+ {
+ await CoinSelectionService.LockUTXOs(_selectedUTXOs, request, BitcoinRequestType.ChannelOperation);
+ }
+ }
+ else
+ {
+ ToastService.ShowError(createChannelResult.Item2);
+ await AuditService.LogAsync(
+ AuditActionType.Create,
+ AuditEventType.Failure,
+ AuditObjectType.ChannelOperationRequest,
+ null,
+ new { Error = createChannelResult.Item2, Description = $"Failed to create channel open request. Error: {createChannelResult.Item2}" });
+ }
+ _utxoSelectorModalRef.ClearModal();
+ }
+
+ ///
+ /// The warning to show when the automatic swap-out would take the outbound of the channel
+ /// opens from its source node, or null when it would not or the node's balance can't be read.
+ ///
+ private async Task SwapOutWarningAsync(ChannelOperationRequest request)
+ {
+ var node = await NodeRepository.GetById(request.SourceNodeId, false);
+ if (node == null || !SwapOutForecast.SwapsOutAutomatically(node)) return null;
+
+ var balance = await LightningService.ChannelBalanceAsync(node);
+ if (balance == null) return null;
+
+ var localBalanceSats = (long)(balance.LocalBalance?.Sat ?? 0) + (long)(balance.PendingOpenLocalBalance?.Sat ?? 0);
+ if (SwapOutForecast.SatsSwappedAfterOpen(node, localBalanceSats, request.SatsAmount, SparkSettings) is not { } swappedSats) return null;
+
+ var balanceAfterBtc = new Money(localBalanceSats + request.SatsAmount).ToUnit(MoneyUnit.BTC);
+ var thresholdBtc = new Money(node.MinimumBalanceThresholdSats).ToUnit(MoneyUnit.BTC);
+ var swappedBtc = new Money(swappedSats).ToUnit(MoneyUnit.BTC);
+ return $"Opening this channel takes {WebUtility.HtmlEncode(node.Name)}'s local balance to {balanceAfterBtc:f8} BTC, above its {thresholdBtc:f8} BTC swap-out threshold. " +
+ $"Automatic liquidity management would swap out up to {swappedBtc:f8} BTC of this channel's outbound liquidity: you would pay swap fees and lose that outbound. Open it anyway?";
+ }
+
+ private async Task SwapOutCloseConfirmationModal()
+ {
+ await _swapOutConfirmationModal.CloseModal();
+ }
+
+ private async Task SwapOutSubmitConfirmationModal()
+ {
+ if (_selectedRequest == null || _createInFlight) return;
+ _createInFlight = true;
+
+ try
+ {
+ await CreateOpenRequestAsync(_selectedRequest);
+ await _swapOutConfirmationModal.CloseModal();
+ await LoadData();
+ await FetchRequests();
+ await ReloadAllRequestsGrid();
+ }
+ finally
+ {
+ _createInFlight = false;
+ }
+ }
+
#endregion
private static bool RequestPendingFilter(ChannelOperationRequest req)
diff --git a/src/Services/SwapOutForecast.cs b/src/Services/SwapOutForecast.cs
new file mode 100644
index 000000000..1b78589c4
--- /dev/null
+++ b/src/Services/SwapOutForecast.cs
@@ -0,0 +1,61 @@
+/*
+ * NodeGuard
+ * Copyright (C) 2023 Elenpay
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see http://www.gnu.org/licenses/.
+ *
+ */
+
+using NodeGuard.Data.Models;
+using NodeGuard.Services.Spark;
+
+namespace NodeGuard.Services;
+
+///
+/// What the automatic swap-out (AutoLiquidityManagementJob) would take from a node's new outbound after a channel
+/// open, by the same rule it swaps by.
+///
+public static class SwapOutForecast
+{
+ ///
+ /// The sats of a channel opened from that the automatic
+ /// swap-out would take, or null when it would not swap. It swaps when the node has automatic liquidity management on
+ /// and a funds destination wallet, and its local balance after the open (, before
+ /// the open, plus the channel) is above its threshold by at least the smallest min swap of its weighted providers.
+ /// Swap fee budget, swaps in flight and Spark wallet room are left out: they delay a swap, not prevent it.
+ ///
+ public static long? SatsSwappedAfterOpen(Node node, long localBalanceSats, long channelSats, SparkSettings spark)
+ {
+ if (!SwapsOutAutomatically(node))
+ {
+ return null;
+ }
+
+ var excess = localBalanceSats + channelSats - node.MinimumBalanceThresholdSats;
+ var minSwap = SwapProviderLimits.Weighted(node).Min(w => SwapProviderLimits.For(node, w.Provider, spark).MinSats);
+ if (excess <= 0 || excess < minSwap)
+ {
+ return null;
+ }
+
+ return Math.Min(channelSats, excess);
+ }
+
+ ///
+ /// Whether the automatic swap-out runs for : enabled, with automatic liquidity management on
+ /// and a funds destination wallet (as INodeRepository.GetAllWithAutoLiquidityEnabled picks them).
+ ///
+ public static bool SwapsOutAutomatically(Node node) =>
+ !node.IsNodeDisabled && node.AutoLiquidityManagementEnabled && node.FundsDestinationWalletId.HasValue;
+}
diff --git a/src/Services/SwapProviderLimits.cs b/src/Services/SwapProviderLimits.cs
index 775551c93..41c652f31 100644
--- a/src/Services/SwapProviderLimits.cs
+++ b/src/Services/SwapProviderLimits.cs
@@ -43,6 +43,22 @@ public readonly record struct SwapProviderLimits(long MinSats, long MaxSats, int
_ => throw new ArgumentOutOfRangeException(nameof(provider), provider, "Unknown swap provider")
};
+ ///
+ /// The providers swaps out through, with their weights: those with a weight above 0, or Loop
+ /// alone when none has one.
+ ///
+ public static IReadOnlyList<(SwapProvider Provider, int Weight)> Weighted(Node node)
+ {
+ var weighted = new List<(SwapProvider Provider, int Weight)>
+ {
+ (SwapProvider.Loop, node.LoopSwapWeight),
+ (SwapProvider.FortySwap, node.FortySwapWeight),
+ (SwapProvider.Spark, node.SparkSwapWeight)
+ }.Where(w => w.Weight > 0).ToList();
+
+ return weighted.Count > 0 ? weighted : [(SwapProvider.Loop, 1)];
+ }
+
/// 's max routing fee ratio for 's swaps.
public static decimal MaxRoutingFeeRatioFor(Node node, SwapProvider provider) => provider switch
{
diff --git a/test/NodeGuard.Tests/Services/SwapOutForecastTests.cs b/test/NodeGuard.Tests/Services/SwapOutForecastTests.cs
new file mode 100644
index 000000000..fa16d1aba
--- /dev/null
+++ b/test/NodeGuard.Tests/Services/SwapOutForecastTests.cs
@@ -0,0 +1,142 @@
+/*
+ * NodeGuard
+ * Copyright (C) 2023 Elenpay
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see http://www.gnu.org/licenses/.
+ *
+ */
+
+using FluentAssertions;
+using NodeGuard.Data.Models;
+using NodeGuard.Services.Spark;
+
+namespace NodeGuard.Services;
+
+public class SwapOutForecastTests
+{
+ private static readonly SparkSettings Spark = new() { Enabled = true, SwapMinSats = 50_000 };
+
+ /// A node the automatic swap-out runs for: 1M sats threshold, Loop only with a 100k sats min swap.
+ private static Node SwappingNode() => new()
+ {
+ Name = "alice",
+ AutoLiquidityManagementEnabled = true,
+ FundsDestinationWalletId = 1,
+ MinimumBalanceThresholdSats = 1_000_000,
+ LoopSwapWeight = 100,
+ LoopSwapMinAmountSats = 100_000,
+ LoopSwapMaxAmountSats = 10_000_000,
+ FortySwapWeight = 0,
+ FortySwapMinAmountSats = 200_000,
+ SparkSwapWeight = 0
+ };
+
+ [Fact]
+ public void AnOpenThatTakesTheBalanceOverTheThresholdByAMinSwap_IsSwappedOut()
+ {
+ // 950k + 500k = 1.45M, 450k over the threshold: that much of the channel would be swapped
+ SwapOutForecast.SatsSwappedAfterOpen(SwappingNode(), 950_000, 500_000, Spark).Should().Be(450_000);
+ }
+
+ [Fact]
+ public void ANodeAlreadyOverItsThreshold_LosesTheWholeChannel()
+ {
+ SwapOutForecast.SatsSwappedAfterOpen(SwappingNode(), 2_000_000, 500_000, Spark).Should().Be(500_000);
+ }
+
+ [Theory]
+ [InlineData(400_000, 600_000)] // lands on the threshold
+ [InlineData(100_000, 500_000)] // stays under it
+ [InlineData(1_000_000, 99_999)] // over it by less than the min swap
+ public void AnOpenThatLeavesLessThanAMinSwapOverTheThreshold_IsNotSwappedOut(long localBalanceSats, long channelSats)
+ {
+ SwapOutForecast.SatsSwappedAfterOpen(SwappingNode(), localBalanceSats, channelSats, Spark).Should().BeNull();
+ }
+
+ [Fact]
+ public void AnOpenOverTheThresholdByExactlyAMinSwap_IsSwappedOut()
+ {
+ SwapOutForecast.SatsSwappedAfterOpen(SwappingNode(), 1_000_000, 100_000, Spark).Should().Be(100_000);
+ }
+
+ [Fact]
+ public void ANodeWithoutAutomaticLiquidityManagement_IsNotSwappedOut()
+ {
+ var node = SwappingNode();
+ node.AutoLiquidityManagementEnabled = false;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 2_000_000, 500_000, Spark).Should().BeNull();
+ }
+
+ [Fact]
+ public void ADisabledNode_IsNotSwappedOut()
+ {
+ var node = SwappingNode();
+ node.IsNodeDisabled = true;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 2_000_000, 500_000, Spark).Should().BeNull();
+ }
+
+ [Fact]
+ public void ANodeWithoutAFundsDestinationWallet_IsNotSwappedOut()
+ {
+ var node = SwappingNode();
+ node.FundsDestinationWalletId = null;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 2_000_000, 500_000, Spark).Should().BeNull();
+ }
+
+ [Fact]
+ public void WithEveryWeightAtZero_LoopsMinSwapApplies()
+ {
+ var node = SwappingNode();
+ node.LoopSwapWeight = 0;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 99_999, Spark).Should().BeNull();
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 100_000, Spark).Should().Be(100_000);
+ }
+
+ [Fact]
+ public void TheSmallestMinSwapAmongTheWeightedProviders_Applies()
+ {
+ var node = SwappingNode();
+ node.SparkSwapWeight = 50;
+ node.SparkSwapMinAmountSats = 20_000;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 20_000, Spark).Should().Be(20_000);
+ }
+
+ [Fact]
+ public void AnUnweightedProvidersMinSwap_IsLeftOut()
+ {
+ var node = SwappingNode();
+ node.LoopSwapWeight = 0;
+ node.FortySwapWeight = 100;
+
+ // 40swap's 200k min applies, not Loop's 100k
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 150_000, Spark).Should().BeNull();
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 200_000, Spark).Should().Be(200_000);
+ }
+
+ [Fact]
+ public void ASparkWeightedNodeWithoutItsOwnMinSwap_UsesTheSparkSettings()
+ {
+ var node = SwappingNode();
+ node.LoopSwapWeight = 0;
+ node.SparkSwapWeight = 100;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 49_999, Spark).Should().BeNull();
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 50_000, Spark).Should().Be(50_000);
+ }
+}
From 326095db7fd8950cecf877db016dec34a6c331ec Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jos=C3=A9=20A=2EP?=
<53834183+Jossec101@users.noreply.github.com>
Date: Wed, 25 Nov 2026 14:52:32 +0100
Subject: [PATCH 2/2] Warn only for swaps the job can make, and bound the
balance read
The forecast now leaves out providers AutoLiquidityManagementJob can never pick: no swaps in flight allowed, a max swap
below the min swap, or Spark without a Spark wallet (Spark disabled included). A node with a swap budget of 0 gets no
warning, as every run stops at an exhausted budget. Reading the source node's balance on Save waits at most 5 seconds,
so an unreachable LND doesn't hold the button; on timeout there is no warning.
---
src/Pages/ChannelRequests.razor | 15 +++-
src/Services/SwapOutForecast.cs | 32 +++++--
.../Services/SwapOutForecastTests.cs | 85 ++++++++++++++++++-
3 files changed, 119 insertions(+), 13 deletions(-)
diff --git a/src/Pages/ChannelRequests.razor b/src/Pages/ChannelRequests.razor
index c3c75c29e..76b17b67c 100644
--- a/src/Pages/ChannelRequests.razor
+++ b/src/Pages/ChannelRequests.razor
@@ -652,6 +652,7 @@
private ConfirmationModal _swapOutConfirmationModal;
// Why the open request being created would be swapped right back out, or null when it would not.
private string? _swapOutWarning;
+ private static readonly TimeSpan SwapOutBalanceTimeout = TimeSpan.FromSeconds(5);
private UTXOSelectorModal _utxoSelectorModalRef;
private List _selectedUTXOs = new();
private MempoolRecommendedFeesType _selectedMempoolRecommendedFeesType;
@@ -985,14 +986,24 @@
///
/// The warning to show when the automatic swap-out would take the outbound of the channel
- /// opens from its source node, or null when it would not or the node's balance can't be read.
+ /// opens from its source node, or null when it would not or the node's balance can't be read within
+ /// .
///
private async Task SwapOutWarningAsync(ChannelOperationRequest request)
{
var node = await NodeRepository.GetById(request.SourceNodeId, false);
if (node == null || !SwapOutForecast.SwapsOutAutomatically(node)) return null;
- var balance = await LightningService.ChannelBalanceAsync(node);
+ // The node's LND gets no deadline of its own: an unreachable one must not hold the Save button
+ Lnrpc.ChannelBalanceResponse? balance;
+ try
+ {
+ balance = await LightningService.ChannelBalanceAsync(node).WaitAsync(SwapOutBalanceTimeout);
+ }
+ catch (TimeoutException)
+ {
+ return null;
+ }
if (balance == null) return null;
var localBalanceSats = (long)(balance.LocalBalance?.Sat ?? 0) + (long)(balance.PendingOpenLocalBalance?.Sat ?? 0);
diff --git a/src/Services/SwapOutForecast.cs b/src/Services/SwapOutForecast.cs
index 1b78589c4..e9a364ecc 100644
--- a/src/Services/SwapOutForecast.cs
+++ b/src/Services/SwapOutForecast.cs
@@ -30,10 +30,10 @@ public static class SwapOutForecast
{
///
/// The sats of a channel opened from that the automatic
- /// swap-out would take, or null when it would not swap. It swaps when the node has automatic liquidity management on
- /// and a funds destination wallet, and its local balance after the open (, before
- /// the open, plus the channel) is above its threshold by at least the smallest min swap of its weighted providers.
- /// Swap fee budget, swaps in flight and Spark wallet room are left out: they delay a swap, not prevent it.
+ /// swap-out would take, or null when it would not swap. It swaps when and the
+ /// excess, the node's local balance after the open (, before the open, plus the
+ /// channel) over its threshold, fits a weighted provider the job can pick (see ).
+ /// What only delays a swap is left out: swaps in flight, the budget spent this period, a busy or full Spark wallet.
///
public static long? SatsSwappedAfterOpen(Node node, long localBalanceSats, long channelSats, SparkSettings spark)
{
@@ -43,8 +43,7 @@ public static class SwapOutForecast
}
var excess = localBalanceSats + channelSats - node.MinimumBalanceThresholdSats;
- var minSwap = SwapProviderLimits.Weighted(node).Min(w => SwapProviderLimits.For(node, w.Provider, spark).MinSats);
- if (excess <= 0 || excess < minSwap)
+ if (excess <= 0 || !SwapProviderLimits.Weighted(node).Any(w => CanSwap(node, w.Provider, excess, spark)))
{
return null;
}
@@ -53,9 +52,24 @@ public static class SwapOutForecast
}
///
- /// Whether the automatic swap-out runs for : enabled, with automatic liquidity management on
- /// and a funds destination wallet (as INodeRepository.GetAllWithAutoLiquidityEnabled picks them).
+ /// Whether the automatic swap-out can swap anything for : enabled, with automatic liquidity
+ /// management on, a funds destination wallet (as INodeRepository.GetAllWithAutoLiquidityEnabled picks them)
+ /// and a swap budget above 0 (with none, every run stops at an exhausted budget).
///
public static bool SwapsOutAutomatically(Node node) =>
- !node.IsNodeDisabled && node.AutoLiquidityManagementEnabled && node.FundsDestinationWalletId.HasValue;
+ !node.IsNodeDisabled && node.AutoLiquidityManagementEnabled && node.FundsDestinationWalletId.HasValue
+ && node.SwapBudgetSats > 0;
+
+ ///
+ /// Whether AutoLiquidityManagementJob can swap sats through
+ /// : it runs swaps (max swaps in flight above 0), the most it may take of the excess
+ /// (its max swap) reaches its min swap and, for Spark, the node has a Spark wallet.
+ ///
+ private static bool CanSwap(Node node, SwapProvider provider, long excess, SparkSettings spark)
+ {
+ var limits = SwapProviderLimits.For(node, provider, spark);
+ return limits.MaxInFlight > 0
+ && Math.Min(excess, limits.MaxSats) >= limits.MinSats
+ && (provider != SwapProvider.Spark || spark.WalletFor(node) is not null);
+ }
}
diff --git a/test/NodeGuard.Tests/Services/SwapOutForecastTests.cs b/test/NodeGuard.Tests/Services/SwapOutForecastTests.cs
index fa16d1aba..d3691f1a0 100644
--- a/test/NodeGuard.Tests/Services/SwapOutForecastTests.cs
+++ b/test/NodeGuard.Tests/Services/SwapOutForecastTests.cs
@@ -27,19 +27,28 @@ public class SwapOutForecastTests
{
private static readonly SparkSettings Spark = new() { Enabled = true, SwapMinSats = 50_000 };
- /// A node the automatic swap-out runs for: 1M sats threshold, Loop only with a 100k sats min swap.
+ ///
+ /// A node the automatic swap-out runs for: 1M sats threshold, a swap budget, Loop only with a 100k sats min swap.
+ /// 40swap (200k min) and Spark (its wallet set) are ready but unweighted.
+ ///
private static Node SwappingNode() => new()
{
Name = "alice",
AutoLiquidityManagementEnabled = true,
FundsDestinationWalletId = 1,
MinimumBalanceThresholdSats = 1_000_000,
+ SwapBudgetSats = 100_000,
LoopSwapWeight = 100,
LoopSwapMinAmountSats = 100_000,
LoopSwapMaxAmountSats = 10_000_000,
+ LoopMaxSwapsInFlight = 1,
FortySwapWeight = 0,
FortySwapMinAmountSats = 200_000,
- SparkSwapWeight = 0
+ FortySwapMaxAmountSats = 10_000_000,
+ FortySwapMaxSwapsInFlight = 1,
+ SparkSwapWeight = 0,
+ SparkMaxSwapsInFlight = 1,
+ SparkWalletId = 7
};
[Fact]
@@ -139,4 +148,76 @@ public void ASparkWeightedNodeWithoutItsOwnMinSwap_UsesTheSparkSettings()
SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 49_999, Spark).Should().BeNull();
SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 50_000, Spark).Should().Be(50_000);
}
+
+ [Fact]
+ public void ANodeWithoutASwapBudget_IsNotSwappedOut()
+ {
+ var node = SwappingNode();
+ node.SwapBudgetSats = 0;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 2_000_000, 500_000, Spark).Should().BeNull();
+ }
+
+ [Fact]
+ public void ANodeWhoseProvidersRunNoSwaps_IsNotSwappedOut()
+ {
+ var node = SwappingNode();
+ node.LoopMaxSwapsInFlight = 0;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 2_000_000, 500_000, Spark).Should().BeNull();
+ }
+
+ [Fact]
+ public void AProviderThatRunsNoSwaps_IsLeftOut()
+ {
+ var node = SwappingNode();
+ node.SparkSwapWeight = 50;
+ node.SparkSwapMinAmountSats = 20_000;
+ node.SparkMaxSwapsInFlight = 0;
+
+ // Spark's 20k min doesn't apply, Loop's 100k does
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 70_000, Spark).Should().BeNull();
+ }
+
+ [Fact]
+ public void AProviderWhoseMaxSwapIsBelowItsMin_IsLeftOut()
+ {
+ var node = SwappingNode();
+ node.SparkSwapWeight = 50;
+ node.SparkSwapMinAmountSats = 20_000;
+ node.SparkSwapMaxAmountSats = 10_000;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 70_000, Spark).Should().BeNull();
+ }
+
+ [Fact]
+ public void SparkForANodeWithoutASparkWallet_IsLeftOut()
+ {
+ var node = SwappingNode();
+ node.SparkSwapWeight = 50;
+ node.SparkSwapMinAmountSats = 20_000;
+ node.SparkWalletId = null;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 70_000, Spark).Should().BeNull();
+ }
+
+ [Fact]
+ public void SparkWithSparkDisabled_IsLeftOut()
+ {
+ var node = SwappingNode();
+ node.SparkSwapWeight = 50;
+ node.SparkSwapMinAmountSats = 20_000;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 70_000, SparkSettings.Disabled).Should().BeNull();
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 70_000, Spark).Should().Be(70_000);
+ }
+
+ [Fact]
+ public void AnExcessOverTheMaxSwap_IsStillSwappedOut()
+ {
+ var node = SwappingNode();
+ node.LoopSwapMaxAmountSats = 200_000;
+
+ SwapOutForecast.SatsSwappedAfterOpen(node, 1_000_000, 500_000, Spark).Should().Be(500_000);
+ }
}