diff --git a/apps/explorer/lib/explorer/chain.ex b/apps/explorer/lib/explorer/chain.ex index 841084b251..bbb4da16ca 100644 --- a/apps/explorer/lib/explorer/chain.ex +++ b/apps/explorer/lib/explorer/chain.ex @@ -32,6 +32,7 @@ defmodule Explorer.Chain do Block, BlockCountCache, BlockNumberCache, + BlocksCache, Data, DecompiledSmartContract, Hash, @@ -1148,16 +1149,22 @@ defmodule Explorer.Chain do @spec list_blocks([paging_options | necessity_by_association_option]) :: [Block.t()] def list_blocks(options \\ []) when is_list(options) do necessity_by_association = Keyword.get(options, :necessity_by_association, %{}) - paging_options = Keyword.get(options, :paging_options, @default_paging_options) + paging_options = Keyword.get(options, :paging_options) || @default_paging_options block_type = Keyword.get(options, :block_type, "Block") - Block - |> Block.block_type_filter(block_type) - |> page_blocks(paging_options) - |> limit(^paging_options.page_size) - |> order_by(desc: :number) - |> join_associations(necessity_by_association) - |> Repo.all() + if block_type == "Block" && !paging_options.key && BlocksCache.enough_elements?(paging_options.page_size) do + cached_blocks = BlocksCache.blocks() + + Enum.slice(cached_blocks, 0, paging_options.page_size) + else + Block + |> Block.block_type_filter(block_type) + |> page_blocks(paging_options) + |> limit(^paging_options.page_size) + |> order_by(desc: :number) + |> join_associations(necessity_by_association) + |> Repo.all() + end end @doc """ diff --git a/apps/explorer/lib/explorer/chain/blocks_cache.ex b/apps/explorer/lib/explorer/chain/blocks_cache.ex index e442c2f8a2..50d054e165 100644 --- a/apps/explorer/lib/explorer/chain/blocks_cache.ex +++ b/apps/explorer/lib/explorer/chain/blocks_cache.ex @@ -22,6 +22,16 @@ defmodule Explorer.Chain.BlocksCache do end end + def enough_elements?(number) do + ConCache.size(@cache_name) > number + 1 + end + + def update_blocks(blocks) do + Enum.each(blocks, fn block -> + update(block) + end) + end + def blocks do numbers = block_numbers() diff --git a/apps/indexer/lib/indexer/block/fetcher.ex b/apps/indexer/lib/indexer/block/fetcher.ex index 06a702aa4b..4d4cd978ec 100644 --- a/apps/indexer/lib/indexer/block/fetcher.ex +++ b/apps/indexer/lib/indexer/block/fetcher.ex @@ -11,7 +11,7 @@ defmodule Indexer.Block.Fetcher do alias EthereumJSONRPC.{Blocks, FetchedBeneficiaries} alias Explorer.Chain - alias Explorer.Chain.{Address, Block, BlockNumberCache, Hash, Import, Transaction} + alias Explorer.Chain.{Address, Block, BlockNumberCache, BlocksCache, Hash, Import, Transaction} alias Indexer.Block.Fetcher.Receipts alias Indexer.Fetcher.{ @@ -186,6 +186,7 @@ defmodule Indexer.Block.Fetcher do BlockNumberCache.update(max_block.number) BlockNumberCache.update(min_block.number) + BlocksCache.update_blocks(blocks) end def import(