Skip to content

Commit

Permalink
[ᚬmaster] chore: calculate average block time by latest 100 bloc… (#477)
Browse files Browse the repository at this point in the history
[ᚬmaster] chore: calculate average block time by latest 100 blocks
  • Loading branch information
shaojunda authored Nov 18, 2019
2 parents 41fd335 + 4730361 commit b0f5d28
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 13 deletions.
17 changes: 5 additions & 12 deletions app/models/statistic_info.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class StatisticInfo
def initialize(hash_rate_statistical_interval: nil)
def initialize(hash_rate_statistical_interval: 100)
@hash_rate_statistical_interval = hash_rate_statistical_interval.presence || ENV["HASH_RATE_STATISTICAL_INTERVAL"]
end

Expand All @@ -21,11 +21,10 @@ def current_epoch_difficulty
end

def current_epoch_average_block_time
current_epoch_number = Block.recent.first&.epoch
blocks = Block.where(epoch: current_epoch_number).order(:timestamp)
blocks = Block.order(timestamp: :desc).limit(hash_rate_statistical_interval.to_i)
return if blocks.empty?

total_block_time(blocks, current_epoch_number) / blocks.size
total_block_time(blocks) / blocks.size
end

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

attr_reader :hash_rate_statistical_interval

def total_block_time(blocks, current_epoch_number)
prev_epoch_nubmer = [current_epoch_number.to_i - 1, 0].max
if prev_epoch_nubmer.zero?
prev_epoch_last_block = Block.find_by(number: 0)
else
prev_epoch_last_block = Block.where(epoch: prev_epoch_nubmer).recent.first
end
(blocks.last.timestamp - prev_epoch_last_block.timestamp).to_d
def total_block_time(blocks)
(blocks.first.timestamp - blocks.last.timestamp).to_d
end
end
2 changes: 1 addition & 1 deletion test/models/statistic_info_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class StatisticInfoTest < ActiveSupport::TestCase
test "the default statistical interval should equal to env config" do
statistic_info = StatisticInfo.new

assert_equal ENV["HASH_RATE_STATISTICAL_INTERVAL"], statistic_info.instance_variable_get(:@hash_rate_statistical_interval)
assert_equal 100, statistic_info.instance_variable_get(:@hash_rate_statistical_interval)
end

test "id should present" do
Expand Down

0 comments on commit b0f5d28

Please sign in to comment.