diff --git a/apps/explorer/lib/explorer/counters/average_block_time.ex b/apps/explorer/lib/explorer/counters/average_block_time.ex index 390a69398a..74ab6d9ed4 100644 --- a/apps/explorer/lib/explorer/counters/average_block_time.ex +++ b/apps/explorer/lib/explorer/counters/average_block_time.ex @@ -103,7 +103,7 @@ defmodule Explorer.Counters.AverageBlockTime do {sum + duration, count + 1} end) - average = sum / count + average = if count == 0, do: 0, else: sum / count average |> round() @@ -115,8 +115,13 @@ defmodule Explorer.Counters.AverageBlockTime do |> Enum.reduce({[], nil, nil}, fn {block_number, timestamp}, {durations, last_block_number, last_timestamp} -> if last_timestamp do block_numbers_range = last_block_number - block_number - duration = (last_timestamp - timestamp) / block_numbers_range - {[duration | durations], block_number, timestamp} + + if block_numbers_range == 0 do + {durations, block_number, timestamp} + else + duration = (last_timestamp - timestamp) / block_numbers_range + {[duration | durations], block_number, timestamp} + end else {durations, block_number, timestamp} end diff --git a/apps/explorer/test/explorer/counters/average_block_time_test.exs b/apps/explorer/test/explorer/counters/average_block_time_test.exs index 82db1f5af4..9d55664dcf 100644 --- a/apps/explorer/test/explorer/counters/average_block_time_test.exs +++ b/apps/explorer/test/explorer/counters/average_block_time_test.exs @@ -34,19 +34,27 @@ defmodule Explorer.Counters.AverageBlockTimeTest do first_timestamp = Timex.now() - insert(:block, number: block_number, consensus: true, timestamp: Timex.shift(first_timestamp, seconds: -100 - 3)) + insert(:block, number: block_number, consensus: true, timestamp: Timex.shift(first_timestamp, seconds: -100 - 6)) + + insert(:block, number: block_number, consensus: false, timestamp: Timex.shift(first_timestamp, seconds: -100 - 12)) + insert(:block, number: block_number, consensus: false, timestamp: Timex.shift(first_timestamp, seconds: -100 - 9)) - insert(:block, number: block_number, consensus: false, timestamp: Timex.shift(first_timestamp, seconds: -100 - 6)) + + insert(:block, + number: block_number + 1, + consensus: true, + timestamp: Timex.shift(first_timestamp, seconds: -100 - 3) + ) Enum.each(1..100, fn i -> insert(:block, - number: block_number + i, + number: block_number + 1 + i, consensus: true, - timestamp: Timex.shift(first_timestamp, seconds: -(101 - i) - 9) + timestamp: Timex.shift(first_timestamp, seconds: -(101 - i) - 12) ) end) - assert Repo.aggregate(Block, :count, :hash) == 103 + assert Repo.aggregate(Block, :count, :hash) == 104 AverageBlockTime.refresh()