Skip to content

Commit

Permalink
Increase channel view performance when loading (#246)
Browse files Browse the repository at this point in the history
* refactor(NodeChannelSubscribeJob.cs): remove check for empty close address to allow for channels without a close address
style(Channels.razor): add space after typecast for consistency and readability
refactor(Channels.razor): simplify balance calculation logic by removing unnecessary null check and conversion
feat(Channels.razor): add _channelsBalance dictionary to store channel balances for efficiency
feat(Channels.razor): add balance update every 60 seconds to keep channel balances up-to-date
fix(Channels.razor): change return type of GetPercentageBalance to int and handle exceptions more gracefully
style(Channels.razor): adjust indentation for better code readability
style(Channels.razor): add space after typecast for consistency and readability
style(Channels.razor): adjust line breaks for better code readability

refactor(LightningService.cs): improve code readability by breaking down long lines of code
feat(LightningService.cs): modify GetChannelBalance method to return a dictionary of balances for all channels
fix(LightningService.cs): improve error handling and logging for better debugging and error tracking

style(LightningService.cs): improve code readability by breaking long lines into multiple lines

This commit breaks down long lines of code into multiple lines to improve readability and maintainability. This includes error messages, function calls, and conditional statements. No functional changes were made.

style(LightningService.cs): improve code readability by breaking long lines into multiple lines

This commit breaks down long lines of code into multiple lines to improve readability and maintainability. This is particularly useful for developers who use tools or editors with limited horizontal space. It also makes it easier to understand the structure and flow of the code at a glance.

refactor(LightningService.cs): change GetChannelBalance method to GetChannelsBalance to fetch balances for all channels
feat(LightningService.cs): add logic to calculate local and remote balances for each channel in GetChannelsBalance method to provide more detailed balance information

* Update src/Pages/Channels.razor

Co-authored-by: Marcos <[email protected]>

---------

Co-authored-by: Marcos <[email protected]>
  • Loading branch information
Jossec101 and markettes authored Jul 25, 2023
1 parent 0b6c8ca commit 08732a6
Show file tree
Hide file tree
Showing 3 changed files with 239 additions and 133 deletions.
5 changes: 0 additions & 5 deletions src/Jobs/NodeChannelSubscribeJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,6 @@ public async Task NodeUpdateManagement(ChannelEventUpdate channelEventUpdate, No
switch (channelEventUpdate.Type)
{
case ChannelEventUpdate.Types.UpdateType.OpenChannel:
if (String.IsNullOrEmpty(channelEventUpdate.OpenChannel.CloseAddress))
{
_logger.LogError("Close address is empty");
throw new Exception("Close address is empty");
}

var channelOpened = channelEventUpdate.OpenChannel;
var fundingTxAndIndex = channelOpened.ChannelPoint.Split(":");
Expand Down
67 changes: 40 additions & 27 deletions src/Pages/Channels.razor
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@
Wallet wallet = null;
if (context.OpenedWithId != null)
{
wallet = Task.Run(() => WalletRepository.GetById((int)context.OpenedWithId)).Result;
wallet = Task.Run(() => WalletRepository.GetById((int) context.OpenedWithId)).Result;
}
@(wallet == null ? "Unknown" : wallet.Name)
}
Expand Down Expand Up @@ -148,16 +148,11 @@
<DisplayTemplate>
@{
var balance = Task.Run(() => GetPercentageBalance(context)).Result;
var percentageBalance = 0;
if (balance != null)
{
percentageBalance = Convert.ToInt32(balance);
}


}
@if (balance != null)
@if (balance >= 0)
{
<Progress Color="Color.Primary" Value="@percentageBalance"/>
<Progress Color="Color.Primary" Value="@balance"/>
<Text>
@{
@($"{balance}%")
Expand Down Expand Up @@ -365,6 +360,9 @@
private ColumnLayout<ChannelsColumnName> ChannelsColumnLayout;
private Dictionary<string, bool> ChannelsColumns = new();
private bool columnsLoaded;
// This dictionary is used to store the balance of each channel, key is the channel id, value is a tuple with the node id as local in the pair, local balance, remote balance
private Dictionary<ulong, (int,long, long)> _channelsBalance = new();
private DateTimeOffset _lastBalanceUpdate = DateTimeOffset.Now;

public abstract class ChannelsColumnName
{
Expand Down Expand Up @@ -406,14 +404,14 @@
_nodes = await NodeRepository.GetAll();
_wallets = await WalletRepository.GetAll();
_channelsDataGridRef.FilterData();
_channelsBalance = await LightningService.GetChannelsBalance();
}

protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender && !columnsLoaded)
{
await LoadColumnLayout();

}
}

Expand Down Expand Up @@ -469,28 +467,42 @@
ToastService.ShowSuccess("Text copied");
}

private async Task<double?> GetPercentageBalance(Channel channel)
private async Task<int> GetPercentageBalance(Channel channel)
{
//If the last update was more than 60 seconds ago, we update the balance dictionary
if (DateTimeOffset.Now.Subtract(_lastBalanceUpdate).TotalSeconds > 60)
{
_channelsBalance = await LightningService.GetChannelsBalance();
_lastBalanceUpdate = DateTimeOffset.Now;
}

try
{
double? result = null;
var values = await LightningService.GetChannelBalance(channel);
if (values.Item1 != null && values.Item2 != null)
{
result = (values.Item2 / (double) (values.Item2 + values.Item1)) * 100;
result = Math.Round(result.Value, 2);
}
else
var result = -1.0;
if (_channelsBalance.TryGetValue(channel.ChanId, out var values))
{
result = null;
var sourceNodeId = values.Item1;
//If the source node is the local node, the remote balance is the third value, otherwise is the second
var capacity = values.Item2 + values.Item3;
if (sourceNodeId == channel.SourceNodeId)
{
result = (values.Item3 / (double) capacity) * 100;
}
else
{
result = (values.Item2 / (double) capacity) * 100;
}

result = Math.Round(result, 2);
}

return result;

return Convert.ToInt32(result);
}
catch (Exception e)
{
ToastService.ShowError($"Channel balance for channel id:{channel.Id} could not be retrieved");
return null;
return -1;
}
}

Expand Down Expand Up @@ -574,7 +586,7 @@
var sourceNode = await NodeRepository.GetById(channel.SourceNodeId);
var node = String.IsNullOrEmpty(sourceNode.ChannelAdminMacaroon) ? destinationNode : sourceNode;

//If there is a liquidity rule for this channel, we load it, the first one
//If there is a liquidity rule for this channel, we load it, the first one
_currentLiquidityRule = _selectedChannel?.LiquidityRules.FirstOrDefault() ?? new LiquidityRule
{
MinimumLocalBalance = 20,
Expand Down Expand Up @@ -718,7 +730,7 @@
private bool OnWalletFilter(object itemValue, object searchValue)
{
if (itemValue == null) return false;
return searchValue == null || (int)searchValue == 0 || (int)itemValue == (int)searchValue;
return searchValue == null || (int) searchValue == 0 || (int) itemValue == (int) searchValue;
}

private bool OnSourceNodeIdFilter(object itemValue, object searchValue)
Expand Down Expand Up @@ -766,9 +778,9 @@
{
ChannelOperationRequest? lastRequest = channel.ChannelOperationRequests.LastOrDefault();
if (lastRequest == null && channel.CreatedByNodeGuard == false) return false;
return channel.Status == Channel.ChannelStatus.Closed|| (lastRequest.RequestType == OperationRequestType.Close
&& lastRequest.Status == ChannelOperationRequestStatus.OnChainConfirmed
|| lastRequest.Status == ChannelOperationRequestStatus.OnChainConfirmationPending);
return channel.Status == Channel.ChannelStatus.Closed || (lastRequest.RequestType == OperationRequestType.Close
&& lastRequest.Status == ChannelOperationRequestStatus.OnChainConfirmed
|| lastRequest.Status == ChannelOperationRequestStatus.OnChainConfirmationPending);
}

private void OnColumnLayoutUpdate()
Expand All @@ -784,4 +796,5 @@
}
return ChannelsColumnLayout.IsColumnVisible(column);
}

}
Loading

0 comments on commit 08732a6

Please sign in to comment.