Skip to content

Commit b0f5d28

Browse files
authored
[ᚬmaster] chore: calculate average block time by latest 100 bloc… (#477)
[ᚬmaster] chore: calculate average block time by latest 100 blocks
2 parents 41fd335 + 4730361 commit b0f5d28

File tree

2 files changed

+6
-13
lines changed

2 files changed

+6
-13
lines changed

app/models/statistic_info.rb

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
class StatisticInfo
2-
def initialize(hash_rate_statistical_interval: nil)
2+
def initialize(hash_rate_statistical_interval: 100)
33
@hash_rate_statistical_interval = hash_rate_statistical_interval.presence || ENV["HASH_RATE_STATISTICAL_INTERVAL"]
44
end
55

@@ -21,11 +21,10 @@ def current_epoch_difficulty
2121
end
2222

2323
def current_epoch_average_block_time
24-
current_epoch_number = Block.recent.first&.epoch
25-
blocks = Block.where(epoch: current_epoch_number).order(:timestamp)
24+
blocks = Block.order(timestamp: :desc).limit(hash_rate_statistical_interval.to_i)
2625
return if blocks.empty?
2726

28-
total_block_time(blocks, current_epoch_number) / blocks.size
27+
total_block_time(blocks) / blocks.size
2928
end
3029

3130
def hash_rate(block_number = tip_block_number)
@@ -50,13 +49,7 @@ def blockchain_info
5049

5150
attr_reader :hash_rate_statistical_interval
5251

53-
def total_block_time(blocks, current_epoch_number)
54-
prev_epoch_nubmer = [current_epoch_number.to_i - 1, 0].max
55-
if prev_epoch_nubmer.zero?
56-
prev_epoch_last_block = Block.find_by(number: 0)
57-
else
58-
prev_epoch_last_block = Block.where(epoch: prev_epoch_nubmer).recent.first
59-
end
60-
(blocks.last.timestamp - prev_epoch_last_block.timestamp).to_d
52+
def total_block_time(blocks)
53+
(blocks.first.timestamp - blocks.last.timestamp).to_d
6154
end
6255
end

test/models/statistic_info_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ class StatisticInfoTest < ActiveSupport::TestCase
1010
test "the default statistical interval should equal to env config" do
1111
statistic_info = StatisticInfo.new
1212

13-
assert_equal ENV["HASH_RATE_STATISTICAL_INTERVAL"], statistic_info.instance_variable_get(:@hash_rate_statistical_interval)
13+
assert_equal 100, statistic_info.instance_variable_get(:@hash_rate_statistical_interval)
1414
end
1515

1616
test "id should present" do

0 commit comments

Comments
 (0)