diff --git a/apps/explorer/lib/explorer/chain/address/token_balance.ex b/apps/explorer/lib/explorer/chain/address/token_balance.ex index 4b78049c18..c8dec08d45 100644 --- a/apps/explorer/lib/explorer/chain/address/token_balance.ex +++ b/apps/explorer/lib/explorer/chain/address/token_balance.ex @@ -65,18 +65,20 @@ defmodule Explorer.Chain.Address.TokenBalance do end @doc """ - Builds an `Ecto.Query` to fetch the last token balances. + Builds an `Ecto.Query` to fetch the last token balances that have value greater than 0. The last token balances from an Address is the last block indexed. """ def last_token_balances(address_hash) do - from( - tb in TokenBalance, - where: tb.address_hash == ^address_hash and tb.value > 0, - distinct: :token_contract_address_hash, - order_by: [desc: :block_number], - preload: :token - ) + query = + from( + tb in TokenBalance, + where: tb.address_hash == ^address_hash, + distinct: :token_contract_address_hash, + order_by: [desc: :block_number] + ) + + from(tb in subquery(query), where: tb.value > 0, preload: :token) end @doc """ diff --git a/apps/explorer/test/explorer/chain_test.exs b/apps/explorer/test/explorer/chain_test.exs index d680f9436f..ce7c6351c7 100644 --- a/apps/explorer/test/explorer/chain_test.exs +++ b/apps/explorer/test/explorer/chain_test.exs @@ -2665,6 +2665,29 @@ defmodule Explorer.ChainTest do assert Chain.fetch_last_token_balances(address.hash) == [] end + + test "does not consider other blocks when the last block has the value 0" do + address = insert(:address) + token = insert(:token, contract_address: build(:contract_address)) + + insert( + :token_balance, + address: address, + block_number: 1000, + token_contract_address_hash: token.contract_address_hash, + value: 5000 + ) + + insert( + :token_balance, + address: address, + block_number: 1001, + token_contract_address_hash: token.contract_address_hash, + value: 0 + ) + + assert Chain.fetch_last_token_balances(address.hash) == [] + end end describe "fetch_token_holders_from_token_hash/2" do