Skip to content

Commit

Permalink
UI: React to onchain snapshot update
Browse files Browse the repository at this point in the history
  • Loading branch information
dennisreimann committed Dec 10, 2024
1 parent 5fb4b6e commit 188b995
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 18 deletions.
7 changes: 2 additions & 5 deletions BTCPayApp.Core/Wallet/LightningNodeService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using BTCPayApp.Core.Auth;
using BTCPayApp.Core.BTCPayServer;
using BTCPayApp.Core.Data;
using BTCPayApp.Core.Helpers;
Expand All @@ -19,13 +18,12 @@ public class LightningNodeManager : BaseHostedService
private readonly BTCPayConnectionManager _btcPayConnectionManager;
private readonly IServiceScopeFactory _serviceScopeFactory;


private IServiceScope? _nodeScope;
public LDKNode? Node => _nodeScope?.ServiceProvider.GetService<LDKNode>();
private LightningNodeState _state = LightningNodeState.Init;
public bool IsHubConnected => _btcPayConnectionManager.ConnectionState is BTCPayConnectionState.ConnectedAsMaster;
private async Task<bool> IsOnchainLightningDerivationConfigured() => (await _onChainWalletManager.GetConfig())?.Derivations.ContainsKey(WalletDerivation.LightningScripts) is true;
public async Task<bool> CanConfigureLightningNode () => IsHubConnected && await _onChainWalletManager.IsConfigured() && !await IsOnchainLightningDerivationConfigured() && State == LightningNodeState.NotConfigured;
public async Task<bool> CanConfigureLightningNode () => IsHubConnected && await _onChainWalletManager.IsConfigured() && !await IsOnchainLightningDerivationConfigured() && State == LightningNodeState.NotConfigured;
// public string? ConnectionString => IsOnchainLightningDerivationConfigured && _accountManager.GetUserInfo() is {} acc
// ? $"type=app;user={acc.UserId}": null;

Expand Down Expand Up @@ -68,7 +66,6 @@ public async Task StartNode()
return;
}


_logger.LogInformation("Starting lightning node");
await _controlSemaphore.WaitAsync();
try
Expand Down Expand Up @@ -122,7 +119,7 @@ public async Task StopNode(bool setAsStopped = true)
_nodeScope = null;
_controlSemaphore.Release();
if (setAsStopped)
State = LightningNodeState.Stopped;
State = LightningNodeState.Stopped;
}
}

Expand Down
7 changes: 4 additions & 3 deletions BTCPayApp.Core/Wallet/OnChainWalletManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ private set
}

public event AsyncEventHandler<(OnChainWalletState Old, OnChainWalletState New)>? StateChanged;
public event AsyncEventHandler<CoinSnapshot>? SnapshotUpdated;

public OnChainWalletManager(
ConfigProvider configProvider,
Expand Down Expand Up @@ -352,9 +353,9 @@ private async Task UpdateSnapshot()
var bb = await GetBestBlock();
var identifiers = config.Derivations.Values.Select(derivation => derivation.Identifier).ToArray();
var utxos = await HubProxy.GetUTXOs(identifiers);
config.CoinSnapshot = new CoinSnapshot()
config.CoinSnapshot = new CoinSnapshot
{
BlockSnapshot = new BlockSnapshot()
BlockSnapshot = new BlockSnapshot
{
BlockHash = uint256.Parse(bb.BlockHash),
BlockHeight = (uint) bb.BlockHeight
Expand All @@ -367,6 +368,7 @@ private async Task UpdateSnapshot()
}).ToArray())
};
await _configProvider.Set(WalletConfig.Key, config, true);
SnapshotUpdated?.Invoke(this, config.CoinSnapshot);
}
finally
{
Expand Down Expand Up @@ -495,7 +497,6 @@ public interface ISignableCoin : ICoin
}, pair => pair.Value.OrderByDescending(tx => tx.Timestamp).ToArray());
}


public async Task<IEnumerable<ICoin>> GetUTXOS()
{
var config = await GetConfig();
Expand Down
42 changes: 32 additions & 10 deletions BTCPayApp.UI/Pages/SendPage.razor
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,13 @@
</SectionContent>
<section class="container">
<AuthorizeView Policy="@Policies.CanModifyStoreSettings" Resource="StoreId">
<h2>Send from @(StoreInfo?.Name ?? "Store") Funds</h2>
<header class="d-flex align-items-center justify-content-between gap-3 mb-3">
<h2 class="mb-0">Send from @(StoreInfo?.Name ?? "Store") Funds</h2>
@if (BalanceLoading)
{
<LoadingIndicator/>
}
</header>
@if (TotalBalance > 0 && (LightningOffchainLocalBalance is > 0 || OnchainConfirmedBalance is > 0) &&
(OnchainState == SourceState.Supported && OnChainWalletManager.IsActive ||
LightningState == SourceState.Supported && LightningNodeManager.IsActive))
Expand Down Expand Up @@ -163,12 +169,6 @@
</ValidationEditContext>
<QrScanModal OnScan="@OnQrCodeScan"/>
}
else if (BalanceLoading)
{
<div class="p-3 text-center">
<LoadingIndicator/>
</div>
}
else if (!string.IsNullOrEmpty(BalanceError))
{
<Alert Type="danger">@BalanceError</Alert>
Expand Down Expand Up @@ -297,8 +297,14 @@

@if (Transactions?.Any() is true)
{
<h2 class="mb-3">Recent Payments</h2>
<TransactionsList Transactions="Transactions" Unit="@BitcoinUnit" Loading="@TransactionsLoading" Error="@TransactionsError" OnToggleDisplayCurrency="ToggleDisplayCurrency"/>
<header class="d-flex align-items-center justify-content-between gap-3 mb-3">
<h2 class="mb-0">Recent Payments</h2>
@if (TransactionsLoading)
{
<LoadingIndicator/>
}
</header>
<TransactionsList Transactions="Transactions" Unit="@BitcoinUnit" Error="@TransactionsError" OnToggleDisplayCurrency="ToggleDisplayCurrency"/>
}
}
</AuthorizeView>
Expand Down Expand Up @@ -407,9 +413,25 @@
? await LightningNodeManager.IsLightningOurs(lightning) ? SourceState.Supported : SourceState.NotSupported
: SourceState.NotConfigured;

OnChainWalletManager.SnapshotUpdated += OnSnapshotUpdated;

_ = LoadTransactions();
}

protected override ValueTask DisposeAsyncCore(bool disposing)
{
base.DisposeAsyncCore(disposing);

OnChainWalletManager.SnapshotUpdated -= OnSnapshotUpdated;

return ValueTask.CompletedTask;
}

private async Task OnSnapshotUpdated(object? sender, CoinSnapshot _)
{
await LoadTransactions();
}

private async Task OnBackClick()
{
if (Model.Transaction == null)
Expand All @@ -422,6 +444,7 @@
{
TransactionsError = null;
TransactionsLoading = true;
await InvokeAsync(StateHasChanged);
try
{
// load
Expand Down Expand Up @@ -594,7 +617,6 @@
await OnChainWalletManager.BroadcastTransaction(transaction);
Dispatcher.Dispatch(new StoreState.FetchBalances(StoreId!));
Model = new SendModel();
_ = LoadTransactions();
return new FormResult(true, $"Transaction {transaction.GetHash()} broadcasted");
}
catch (Exception ex)
Expand Down
8 changes: 8 additions & 0 deletions BTCPayApp.UI/StateMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,14 @@ private async Task ListenIn(IDispatcher dispatcher)
}
};

onChainWalletManager.SnapshotUpdated += async (sender, args) =>
{
if (accountManager.GetCurrentStore() is { } store)
{
dispatcher.Dispatch(new StoreState.FetchBalances(store.Id));
}
};

lightningNodeService.StateChanged += async (sender, args) =>
{
dispatcher.Dispatch(new RootState.LightningNodeStateUpdatedAction(lightningNodeService.State));
Expand Down

0 comments on commit 188b995

Please sign in to comment.