optimize ERC721 inventory query

Inventory tab for ERC721 doesn't load
any token transfers because query is timing
out.

Looking into the query, it does a couple of
unnessary joins:
1. with `transactions` for `block_number`. But
token_transfers already have block_number
2. with `tokens` to check if `token_transfers` are
for ERC-721 token. But the query is only executed only
for ERC 721 tokens

One more issue that I found is that the query uses distinct
by `token_id`. But we don't have any indexes on `token_id`.
So this PR adds index on `token_id`.
pull/2635/head
Ayrat Badykov 5 years ago
parent 81d2b10959
commit eef64e47b5
No known key found for this signature in database
GPG Key ID: B44668E265E9396F
  1. 8
      apps/explorer/lib/explorer/chain/token_transfer.ex
  2. 7
      apps/explorer/priv/repo/migrations/20190827120224_add_index_on_token_transfer_token_id.exs

@ -238,12 +238,8 @@ defmodule Explorer.Chain.TokenTransfer do
def address_to_unique_tokens(contract_address_hash) do def address_to_unique_tokens(contract_address_hash) do
from( from(
tt in TokenTransfer, tt in TokenTransfer,
join: t in Token, where: tt.token_contract_address_hash == ^contract_address_hash,
on: tt.token_contract_address_hash == t.contract_address_hash, order_by: [desc: tt.block_number],
join: ts in Transaction,
on: tt.transaction_hash == ts.hash,
where: t.contract_address_hash == ^contract_address_hash and t.type == "ERC-721",
order_by: [desc: ts.block_number],
distinct: tt.token_id, distinct: tt.token_id,
preload: [:to_address], preload: [:to_address],
select: tt select: tt

@ -0,0 +1,7 @@
defmodule Explorer.Repo.Migrations.AddIndexOnTokenTransferTokenId do
use Ecto.Migration
def change do
create_if_not_exists(index(:token_transfers, [:token_id]))
end
end
Loading…
Cancel
Save