diff --git a/src/Jobs/AutoLiquidityManagementJob.cs b/src/Jobs/AutoLiquidityManagementJob.cs
index d02c63c3..53ee7286 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 1781942d..76b17b67 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,10 @@
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 static readonly TimeSpan SwapOutBalanceTimeout = TimeSpan.FromSeconds(5);
private UTXOSelectorModal _utxoSelectorModalRef;
private List _selectedUTXOs = new();
private MempoolRecommendedFeesType _selectedMempoolRecommendedFeesType;
@@ -901,45 +917,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 +948,98 @@
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 within
+ /// .
+ ///
+ private async Task SwapOutWarningAsync(ChannelOperationRequest request)
+ {
+ var node = await NodeRepository.GetById(request.SourceNodeId, false);
+ if (node == null || !SwapOutForecast.SwapsOutAutomatically(node)) return null;
+
+ // 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);
+ 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 00000000..e9a364ec
--- /dev/null
+++ b/src/Services/SwapOutForecast.cs
@@ -0,0 +1,75 @@
+/*
+ * 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 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)
+ {
+ if (!SwapsOutAutomatically(node))
+ {
+ return null;
+ }
+
+ var excess = localBalanceSats + channelSats - node.MinimumBalanceThresholdSats;
+ if (excess <= 0 || !SwapProviderLimits.Weighted(node).Any(w => CanSwap(node, w.Provider, excess, spark)))
+ {
+ return null;
+ }
+
+ return Math.Min(channelSats, excess);
+ }
+
+ ///
+ /// 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.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/src/Services/SwapProviderLimits.cs b/src/Services/SwapProviderLimits.cs
index 775551c9..41c652f3 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 00000000..d3691f1a
--- /dev/null
+++ b/test/NodeGuard.Tests/Services/SwapOutForecastTests.cs
@@ -0,0 +1,223 @@
+/*
+ * 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, 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,
+ FortySwapMaxAmountSats = 10_000_000,
+ FortySwapMaxSwapsInFlight = 1,
+ SparkSwapWeight = 0,
+ SparkMaxSwapsInFlight = 1,
+ SparkWalletId = 7
+ };
+
+ [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);
+ }
+
+ [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);
+ }
+}