-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
chain.ex
6469 lines (5354 loc) · 206 KB
/
chain.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Explorer.Chain do
@moduledoc """
The chain context.
"""
import Ecto.Query,
only: [
dynamic: 1,
dynamic: 2,
from: 2,
join: 4,
join: 5,
limit: 2,
lock: 2,
offset: 2,
order_by: 2,
order_by: 3,
preload: 2,
preload: 3,
select: 2,
select: 3,
subquery: 1,
union: 2,
where: 2,
where: 3
]
import EthereumJSONRPC, only: [integer_to_quantity: 1, fetch_block_internal_transactions: 2]
require Logger
alias ABI.TypeDecoder
alias Ecto.{Changeset, Multi}
alias EthereumJSONRPC.Transaction, as: EthereumJSONRPCTransaction
alias Explorer.Counters.{LastFetchedCounter, TokenHoldersCounter, TokenTransfersCounter}
alias Explorer.Chain
alias Explorer.Chain.{
Address,
Address.CoinBalance,
Address.CoinBalanceDaily,
Address.CurrentTokenBalance,
Address.TokenBalance,
Block,
CurrencyHelpers,
Data,
DecompiledSmartContract,
Hash,
Import,
InternalTransaction,
Log,
PendingBlockOperation,
SmartContract,
SmartContractAdditionalSource,
Token,
Token.Instance,
TokenTransfer,
Transaction,
Wei
}
alias Explorer.Chain.Block.{EmissionReward, Reward}
alias Explorer.Chain.Cache.{
Accounts,
BlockNumber,
Blocks,
ContractsCounter,
NewContractsCounter,
NewVerifiedContractsCounter,
Transactions,
Uncles,
VerifiedContractsCounter
}
alias Explorer.Chain.Cache.Block, as: BlockCache
alias Explorer.Chain.Fetcher.CheckBytecodeMatchingOnDemand
alias Explorer.Chain.Import.Runner
alias Explorer.Chain.InternalTransaction.{CallType, Type}
alias Explorer.Counters.{
AddressesCounter,
AddressesWithBalanceCounter,
AddressTokenTransfersCounter,
AddressTransactionsCounter,
AddressTransactionsGasUsageCounter
}
alias Explorer.Market.MarketHistoryCache
alias Explorer.{PagingOptions, Repo}
alias Explorer.SmartContract.Helper
alias Dataloader.Ecto, as: DataloaderEcto
@default_paging_options %PagingOptions{page_size: 50}
@token_transfers_per_transaction_preview 10
@token_transfers_necessity_by_association %{
[from_address: :smart_contract] => :optional,
[to_address: :smart_contract] => :optional,
[from_address: :names] => :optional,
[to_address: :names] => :optional,
token: :required
}
@method_name_to_id_map %{
"approve" => "095ea7b3",
"transfer" => "a9059cbb",
"multicall" => "5ae401dc",
"mint" => "40c10f19",
"commit" => "f14fcbc8"
}
@max_incoming_transactions_count 10_000
@revert_msg_prefix_1 "Revert: "
@revert_msg_prefix_2 "revert: "
@revert_msg_prefix_3 "reverted "
@revert_msg_prefix_4 "Reverted "
# Geth-like node
@revert_msg_prefix_5 "execution reverted: "
# keccak256("Error(string)")
@revert_error_method_id "08c379a0"
@burn_address_hash_str "0x0000000000000000000000000000000000000000"
@limit_showing_transactions 10_000
@default_page_size 50
@typedoc """
The name of an association on the `t:Ecto.Schema.t/0`
"""
@type association :: atom()
@typedoc """
The max `t:Explorer.Chain.Block.block_number/0` for `consensus` `true` `t:Explorer.Chain.Block.t/0`s.
"""
@type block_height :: Block.block_number()
@typedoc """
Event type where data is broadcasted whenever data is inserted from chain indexing.
"""
@type chain_event ::
:addresses
| :address_coin_balances
| :blocks
| :block_rewards
| :exchange_rate
| :internal_transactions
| :logs
| :transactions
| :token_transfers
@type direction :: :from | :to
@typedoc """
* `:optional` - the association is optional and only needs to be loaded if available
* `:required` - the association is required and MUST be loaded. If it is not available, then the parent struct
SHOULD NOT be returned.
"""
@type necessity :: :optional | :required
@typedoc """
The `t:necessity/0` of each association that should be loaded
"""
@type necessity_by_association :: %{association => necessity}
@typep necessity_by_association_option :: {:necessity_by_association, necessity_by_association}
@typep paging_options :: {:paging_options, PagingOptions.t()}
@typep balance_by_day :: %{date: String.t(), value: Wei.t()}
@doc """
Gets from the cache the count of `t:Explorer.Chain.Address.t/0`'s where the `fetched_coin_balance` is > 0
"""
@spec count_addresses_with_balance_from_cache :: non_neg_integer()
def count_addresses_with_balance_from_cache do
AddressesWithBalanceCounter.fetch()
end
@doc """
Estimated count of `t:Explorer.Chain.Address.t/0`.
Estimated count of addresses.
"""
@spec address_estimated_count() :: non_neg_integer()
def address_estimated_count do
cached_value = AddressesCounter.fetch()
if is_nil(cached_value) || cached_value == 0 do
%Postgrex.Result{rows: [[count]]} = Repo.query!("SELECT reltuples FROM pg_class WHERE relname = 'addresses';")
max(count, 0)
else
cached_value
end
end
@doc """
Counts the number of addresses with fetched coin balance > 0.
This function should be used with caution. In larger databases, it may take a
while to have the return back.
"""
def count_addresses_with_balance do
Repo.one(
Address.count_with_fetched_coin_balance(),
timeout: :infinity
)
end
@doc """
Counts the number of all addresses.
This function should be used with caution. In larger databases, it may take a
while to have the return back.
"""
def count_addresses do
Repo.aggregate(Address, :count, timeout: :infinity)
end
@doc """
`t:Explorer.Chain.InternalTransaction/0`s from the address with the given `hash`.
This function excludes any internal transactions in the results where the
internal transaction has no siblings within the parent transaction.
## Options
* `:direction` - if specified, will filter internal transactions by address type. If `:to` is specified, only
internal transactions where the "to" address matches will be returned. Likewise, if `:from` is specified, only
internal transactions where the "from" address matches will be returned. If `:direction` is omitted, internal
transactions either to or from the address will be returned.
* `:necessity_by_association` - use to load `t:association/0` as `:required` or `:optional`. If an association is
`:required`, and the `t:Explorer.Chain.InternalTransaction.t/0` has no associated record for that association,
then the `t:Explorer.Chain.InternalTransaction.t/0` will not be included in the page `entries`.
* `:paging_options` - a `t:Explorer.PagingOptions.t/0` used to specify the `:page_size` and
`:key` (a tuple of the lowest/oldest `{block_number, transaction_index, index}`) and. Results will be the internal
transactions older than the `block_number`, `transaction index`, and `index` that are passed.
"""
@spec address_to_internal_transactions(Hash.Address.t(), [paging_options | necessity_by_association_option]) :: [
InternalTransaction.t()
]
def address_to_internal_transactions(hash, options \\ []) do
necessity_by_association = Keyword.get(options, :necessity_by_association, %{})
direction = Keyword.get(options, :direction)
from_block = from_block(options)
to_block = to_block(options)
paging_options = Keyword.get(options, :paging_options, @default_paging_options)
if direction == nil do
query_to_address_hash_wrapped =
InternalTransaction
|> InternalTransaction.where_nonpending_block()
|> InternalTransaction.where_address_fields_match(hash, :to_address_hash)
|> InternalTransaction.where_block_number_in_period(from_block, to_block)
|> common_where_limit_order(paging_options)
|> wrapped_union_subquery()
query_from_address_hash_wrapped =
InternalTransaction
|> InternalTransaction.where_nonpending_block()
|> InternalTransaction.where_address_fields_match(hash, :from_address_hash)
|> InternalTransaction.where_block_number_in_period(from_block, to_block)
|> common_where_limit_order(paging_options)
|> wrapped_union_subquery()
query_created_contract_address_hash_wrapped =
InternalTransaction
|> InternalTransaction.where_nonpending_block()
|> InternalTransaction.where_address_fields_match(hash, :created_contract_address_hash)
|> InternalTransaction.where_block_number_in_period(from_block, to_block)
|> common_where_limit_order(paging_options)
|> wrapped_union_subquery()
query_to_address_hash_wrapped
|> union(^query_from_address_hash_wrapped)
|> union(^query_created_contract_address_hash_wrapped)
|> wrapped_union_subquery()
|> common_where_limit_order(paging_options)
|> preload(transaction: :block)
|> join_associations(necessity_by_association)
|> Repo.all()
else
InternalTransaction
|> InternalTransaction.where_nonpending_block()
|> InternalTransaction.where_address_fields_match(hash, direction)
|> InternalTransaction.where_block_number_in_period(from_block, to_block)
|> common_where_limit_order(paging_options)
|> preload(transaction: :block)
|> join_associations(necessity_by_association)
|> Repo.all()
end
end
def wrapped_union_subquery(query) do
from(
q in subquery(query),
select: q
)
end
defp common_where_limit_order(query, paging_options) do
query
|> InternalTransaction.where_is_different_from_parent_transaction()
|> InternalTransaction.where_block_number_is_not_null()
|> page_internal_transaction(paging_options, %{index_int_tx_desc_order: true})
|> limit(^paging_options.page_size)
|> order_by(
[it],
desc: it.block_number,
desc: it.transaction_index,
desc: it.index
)
end
@doc """
Get the total number of transactions sent by the address with the given hash according to the last block indexed.
We have to increment +1 in the last nonce result because it works like an array position, the first
nonce has the value 0. When last nonce is nil, it considers that the given address has 0 transactions.
"""
@spec total_transactions_sent_by_address(Hash.Address.t()) :: non_neg_integer()
def total_transactions_sent_by_address(address_hash) do
last_nonce =
address_hash
|> Transaction.last_nonce_by_address_query()
|> Repo.one(timeout: :infinity)
case last_nonce do
nil -> 0
value -> value + 1
end
end
@doc """
Fetches the transactions related to the address with the given hash, including
transactions that only have the address in the `token_transfers` related table
and rewards for block validation.
This query is divided into multiple subqueries intentionally in order to
improve the listing performance.
The `token_transfers` table tends to grow exponentially, and the query results
with a `transactions` `join` statement takes too long.
To solve this the `transaction_hashes` are fetched in a separate query, and
paginated through the `block_number` already present in the `token_transfers`
table.
## Options
* `:necessity_by_association` - use to load `t:association/0` as `:required` or `:optional`. If an association is
`:required`, and the `t:Explorer.Chain.Transaction.t/0` has no associated record for that association, then the
`t:Explorer.Chain.Transaction.t/0` will not be included in the page `entries`.
* `:paging_options` - a `t:Explorer.PagingOptions.t/0` used to specify the `:page_size` and
`:key` (a tuple of the lowest/oldest `{block_number, index}`) and. Results will be the transactions older than
the `block_number` and `index` that are passed.
"""
@spec address_to_transactions_with_rewards(Hash.Address.t(), [paging_options | necessity_by_association_option]) ::
[
Transaction.t()
]
def address_to_transactions_with_rewards(address_hash, options \\ []) when is_list(options) do
paging_options = Keyword.get(options, :paging_options, @default_paging_options)
if Application.get_env(:block_scout_web, BlockScoutWeb.Chain)[:has_emission_funds] do
cond do
Keyword.get(options, :direction) == :from ->
address_to_transactions_without_rewards(address_hash, options)
address_has_rewards?(address_hash) ->
%{payout_key: block_miner_payout_address} = Reward.get_validator_payout_key_by_mining(address_hash)
if block_miner_payout_address && address_hash == block_miner_payout_address do
transactions_with_rewards_results(address_hash, options, paging_options)
else
address_to_transactions_without_rewards(address_hash, options)
end
true ->
address_to_transactions_without_rewards(address_hash, options)
end
else
address_to_transactions_without_rewards(address_hash, options)
end
end
defp transactions_with_rewards_results(address_hash, options, paging_options) do
blocks_range = address_to_transactions_tasks_range_of_blocks(address_hash, options)
rewards_task =
Task.async(fn -> Reward.fetch_emission_rewards_tuples(address_hash, paging_options, blocks_range) end)
[rewards_task | address_to_transactions_tasks(address_hash, options)]
|> wait_for_address_transactions()
|> Enum.sort_by(fn item ->
case item do
{%Reward{} = emission_reward, _} ->
{-emission_reward.block.number, 1}
item ->
block_number = if item.block_number, do: -item.block_number, else: 0
index = if item.index, do: -item.index, else: 0
{block_number, index}
end
end)
|> Enum.dedup_by(fn item ->
case item do
{%Reward{} = emission_reward, _} ->
{emission_reward.block_hash, emission_reward.address_hash, emission_reward.address_type}
transaction ->
transaction.hash
end
end)
|> Enum.take(paging_options.page_size)
end
def address_to_transactions_without_rewards(address_hash, options) do
paging_options = Keyword.get(options, :paging_options, @default_paging_options)
address_hash
|> address_to_transactions_tasks(options)
|> wait_for_address_transactions()
|> Enum.sort_by(&{&1.block_number, &1.index}, &>=/2)
|> Enum.dedup_by(& &1.hash)
|> Enum.take(paging_options.page_size)
end
def address_to_mined_transactions_without_rewards(address_hash, options) do
paging_options = Keyword.get(options, :paging_options, @default_paging_options)
address_hash
|> address_to_mined_transactions_tasks(options)
|> wait_for_address_transactions()
|> Enum.sort_by(&{&1.block_number, &1.index}, &>=/2)
|> Enum.dedup_by(& &1.hash)
|> Enum.take(paging_options.page_size)
end
defp address_to_transactions_tasks_query(options) do
from_block = from_block(options)
to_block = to_block(options)
options
|> Keyword.get(:paging_options, @default_paging_options)
|> fetch_transactions(from_block, to_block, true)
end
defp transactions_block_numbers_at_address(address_hash, options) do
direction = Keyword.get(options, :direction)
options
|> address_to_transactions_tasks_query()
|> Transaction.not_pending_transactions()
|> select([t], t.block_number)
|> Transaction.matching_address_queries_list(direction, address_hash)
end
defp address_to_transactions_tasks(address_hash, options) do
direction = Keyword.get(options, :direction)
necessity_by_association = Keyword.get(options, :necessity_by_association, %{})
from_block = from_block(options)
to_block = to_block(options)
options
|> address_to_transactions_tasks_query()
|> Transaction.not_dropped_or_replaced_transactions()
|> where_block_number_in_period(from_block, to_block)
|> join_associations(necessity_by_association)
|> Transaction.matching_address_queries_list(direction, address_hash)
|> Enum.map(fn query -> Task.async(fn -> Repo.all(query) end) end)
end
defp address_to_mined_transactions_tasks(address_hash, options) do
direction = Keyword.get(options, :direction)
necessity_by_association = Keyword.get(options, :necessity_by_association, %{})
options
|> address_to_transactions_tasks_query()
|> Transaction.not_pending_transactions()
|> join_associations(necessity_by_association)
|> Transaction.matching_address_queries_list(direction, address_hash)
|> Enum.map(fn query -> Task.async(fn -> Repo.all(query) end) end)
end
def address_to_transactions_tasks_range_of_blocks(address_hash, options) do
extremums_list =
address_hash
|> transactions_block_numbers_at_address(options)
|> Enum.map(fn query ->
extremum_query =
from(
q in subquery(query),
select: %{min_block_number: min(q.block_number), max_block_number: max(q.block_number)}
)
extremum_query
|> Repo.one!()
end)
extremums_list
|> Enum.reduce(%{min_block_number: nil, max_block_number: 0}, fn %{
min_block_number: min_number,
max_block_number: max_number
},
extremums_result ->
current_min_number = Map.get(extremums_result, :min_block_number)
current_max_number = Map.get(extremums_result, :max_block_number)
extremums_result =
if is_number(current_min_number) do
if is_number(min_number) and min_number > 0 and min_number < current_min_number do
extremums_result
|> Map.put(:min_block_number, min_number)
else
extremums_result
end
else
extremums_result
|> Map.put(:min_block_number, min_number)
end
if is_number(max_number) and max_number > 0 and max_number > current_max_number do
extremums_result
|> Map.put(:max_block_number, max_number)
else
extremums_result
end
end)
end
defp wait_for_address_transactions(tasks) do
tasks
|> Task.yield_many(:timer.seconds(20))
|> Enum.flat_map(fn {_task, res} ->
case res do
{:ok, result} ->
result
{:exit, reason} ->
raise "Query fetching address transactions terminated: #{inspect(reason)}"
nil ->
raise "Query fetching address transactions timed out."
end
end)
end
@spec address_hash_to_token_transfers(Hash.Address.t(), Keyword.t()) :: [Transaction.t()]
def address_hash_to_token_transfers(address_hash, options \\ []) do
paging_options = Keyword.get(options, :paging_options, @default_paging_options)
direction = Keyword.get(options, :direction)
direction
|> Transaction.transactions_with_token_transfers_direction(address_hash)
|> Transaction.preload_token_transfers(address_hash)
|> handle_paging_options(paging_options)
|> Repo.all()
end
@spec address_hash_to_token_transfers_new(Hash.Address.t() | String.t(), Keyword.t()) :: [TokenTransfer.t()]
def address_hash_to_token_transfers_new(address_hash, options \\ []) do
paging_options = Keyword.get(options, :paging_options, @default_paging_options)
direction = Keyword.get(options, :direction)
filters = Keyword.get(options, :token_type)
necessity_by_association = Keyword.get(options, :necessity_by_association)
direction
|> TokenTransfer.token_transfers_by_address_hash(address_hash, filters)
|> join_associations(necessity_by_association)
|> TokenTransfer.handle_paging_options(paging_options)
|> Repo.all()
end
@spec address_hash_to_token_transfers_by_token_address_hash(
Hash.Address.t() | String.t(),
Hash.Address.t() | String.t(),
Keyword.t()
) :: [TokenTransfer.t()]
def address_hash_to_token_transfers_by_token_address_hash(address_hash, token_address_hash, options \\ []) do
paging_options = Keyword.get(options, :paging_options, @default_paging_options)
necessity_by_association = Keyword.get(options, :necessity_by_association)
address_hash
|> TokenTransfer.token_transfers_by_address_hash_and_token_address_hash(token_address_hash)
|> join_associations(necessity_by_association)
|> TokenTransfer.handle_paging_options(paging_options)
|> Repo.all()
end
@doc """
address_hash_to_token_transfers_including_contract/2 function returns token transfers on address (to/from/contract).
It is used by CSV export of token transfers button.
"""
@spec address_hash_to_token_transfers_including_contract(Hash.Address.t(), Keyword.t()) :: [TokenTransfer.t()]
def address_hash_to_token_transfers_including_contract(address_hash, options \\ []) do
paging_options = Keyword.get(options, :paging_options, @default_paging_options)
from_block = Keyword.get(options, :from_block)
to_block = Keyword.get(options, :to_block)
query =
from_block
|> query_address_hash_to_token_transfers_including_contract(to_block, address_hash)
|> order_by([token_transfer], asc: token_transfer.block_number, asc: token_transfer.log_index)
query
|> handle_token_transfer_paging_options(paging_options)
|> preload(transaction: :block)
|> preload(:token)
|> Repo.all()
end
defp query_address_hash_to_token_transfers_including_contract(nil, to_block, address_hash)
when not is_nil(to_block) do
from(
token_transfer in TokenTransfer,
where:
(token_transfer.to_address_hash == ^address_hash or
token_transfer.from_address_hash == ^address_hash or
token_transfer.token_contract_address_hash == ^address_hash) and
token_transfer.block_number <= ^to_block
)
end
defp query_address_hash_to_token_transfers_including_contract(from_block, nil, address_hash)
when not is_nil(from_block) do
from(
token_transfer in TokenTransfer,
where:
(token_transfer.to_address_hash == ^address_hash or
token_transfer.from_address_hash == ^address_hash or
token_transfer.token_contract_address_hash == ^address_hash) and
token_transfer.block_number >= ^from_block
)
end
defp query_address_hash_to_token_transfers_including_contract(from_block, to_block, address_hash)
when not is_nil(from_block) and not is_nil(to_block) do
from(
token_transfer in TokenTransfer,
where:
(token_transfer.to_address_hash == ^address_hash or
token_transfer.from_address_hash == ^address_hash or
token_transfer.token_contract_address_hash == ^address_hash) and
(token_transfer.block_number >= ^from_block and token_transfer.block_number <= ^to_block)
)
end
defp query_address_hash_to_token_transfers_including_contract(_, _, address_hash) do
from(
token_transfer in TokenTransfer,
where:
token_transfer.to_address_hash == ^address_hash or
token_transfer.from_address_hash == ^address_hash or
token_transfer.token_contract_address_hash == ^address_hash
)
end
@spec address_to_logs(Hash.Address.t(), Keyword.t()) :: [Log.t()]
def address_to_logs(address_hash, options \\ []) when is_list(options) do
paging_options = Keyword.get(options, :paging_options) || %PagingOptions{page_size: 50}
from_block = from_block(options)
to_block = to_block(options)
{block_number, transaction_index, log_index} = paging_options.key || {BlockNumber.get_max(), 0, 0}
base =
from(log in Log,
inner_join: transaction in Transaction,
on: transaction.hash == log.transaction_hash,
order_by: [desc: log.block_number, desc: log.index],
where: transaction.block_number < ^block_number,
or_where: transaction.block_number == ^block_number and transaction.index > ^transaction_index,
or_where:
transaction.block_number == ^block_number and transaction.index == ^transaction_index and
log.index > ^log_index,
where: log.address_hash == ^address_hash,
limit: ^paging_options.page_size,
select: log
)
base_query =
base
|> filter_topic(options)
wrapped_query =
from(
log in subquery(base_query),
inner_join: transaction in Transaction,
preload: [:transaction, transaction: [to_address: :smart_contract]],
where:
log.block_hash == transaction.block_hash and
log.block_number == transaction.block_number and
log.transaction_hash == transaction.hash,
select: log
)
wrapped_query
|> where_block_number_in_period(from_block, to_block)
|> Repo.all()
|> Enum.take(paging_options.page_size)
end
defp filter_topic(base_query, topic: topic) do
from(log in base_query,
where:
log.first_topic == ^topic or log.second_topic == ^topic or log.third_topic == ^topic or
log.fourth_topic == ^topic
)
end
defp filter_topic(base_query, _), do: base_query
def where_block_number_in_period(base_query, from_block, to_block) when is_nil(from_block) and not is_nil(to_block) do
from(q in base_query,
where: q.block_number <= ^to_block
)
end
def where_block_number_in_period(base_query, from_block, to_block) when not is_nil(from_block) and is_nil(to_block) do
from(q in base_query,
where: q.block_number > ^from_block
)
end
def where_block_number_in_period(base_query, from_block, to_block) when is_nil(from_block) and is_nil(to_block) do
base_query
end
def where_block_number_in_period(base_query, from_block, to_block) do
from(q in base_query,
where: q.block_number > ^from_block and q.block_number <= ^to_block
)
end
@doc """
Finds all `t:Explorer.Chain.Transaction.t/0`s given the address_hash and the token contract
address hash.
## Options
* `:paging_options` - a `t:Explorer.PagingOptions.t/0` used to specify the `:page_size` and
`:key` (in the form of `%{"inserted_at" => inserted_at}`). Results will be the transactions
older than the `index` that are passed.
"""
@spec address_to_transactions_with_token_transfers(Hash.t(), Hash.t(), [paging_options]) :: [Transaction.t()]
def address_to_transactions_with_token_transfers(address_hash, token_hash, options \\ []) do
paging_options = Keyword.get(options, :paging_options, @default_paging_options)
address_hash
|> Transaction.transactions_with_token_transfers(token_hash)
|> Transaction.preload_token_transfers(address_hash)
|> handle_paging_options(paging_options)
|> Repo.all()
end
@doc """
The `t:Explorer.Chain.Address.t/0` `balance` in `unit`.
"""
@spec balance(Address.t(), :wei) :: Wei.wei() | nil
@spec balance(Address.t(), :gwei) :: Wei.gwei() | nil
@spec balance(Address.t(), :ether) :: Wei.ether() | nil
def balance(%Address{fetched_coin_balance: balance}, unit) do
case balance do
nil -> nil
_ -> Wei.to(balance, unit)
end
end
@doc """
The number of `t:Explorer.Chain.Block.t/0`.
iex> insert_list(2, :block)
iex> Explorer.Chain.block_count()
2
When there are no `t:Explorer.Chain.Block.t/0`.
iex> Explorer.Chain.block_count()
0
"""
def block_count do
Repo.aggregate(Block, :count, :hash)
end
@doc """
Reward for mining a block.
The block reward is the sum of the following:
* Sum of the transaction fees (gas_used * gas_price) for the block
* A static reward for miner (this value may change during the life of the chain)
* The reward for uncle blocks (1/32 * static_reward * number_of_uncles)
*NOTE*
Uncles are not currently accounted for.
"""
@spec block_reward(Block.block_number()) :: Wei.t()
def block_reward(block_number) do
block_hash =
Block
|> where([block], block.number == ^block_number and block.consensus)
|> select([block], block.hash)
|> Repo.one!()
case Repo.one!(
from(reward in Reward,
where: reward.block_hash == ^block_hash,
select: %Wei{
value: coalesce(sum(reward.reward), 0)
}
)
) do
%Wei{
value: %Decimal{coef: 0}
} ->
Repo.one!(
from(block in Block,
left_join: transaction in assoc(block, :transactions),
inner_join: emission_reward in EmissionReward,
on: fragment("? <@ ?", block.number, emission_reward.block_range),
where: block.number == ^block_number and block.consensus,
group_by: [emission_reward.reward, block.hash],
select: %Wei{
value: coalesce(sum(transaction.gas_used * transaction.gas_price), 0) + emission_reward.reward
}
)
)
other_value ->
other_value
end
end
def txn_fees(transactions) do
Enum.reduce(transactions, Decimal.new(0), fn %{gas_used: gas_used, gas_price: gas_price}, acc ->
gas_used
|> Decimal.new()
|> Decimal.mult(gas_price_to_decimal(gas_price))
|> Decimal.add(acc)
end)
end
defp gas_price_to_decimal(%Wei{} = wei), do: wei.value
defp gas_price_to_decimal(gas_price), do: Decimal.new(gas_price)
def burned_fees(transactions, base_fee_per_gas) do
burned_fee_counter =
transactions
|> Enum.reduce(Decimal.new(0), fn %{gas_used: gas_used}, acc ->
gas_used
|> Decimal.new()
|> Decimal.add(acc)
end)
base_fee_per_gas && Wei.mult(base_fee_per_gas_to_wei(base_fee_per_gas), burned_fee_counter)
end
defp base_fee_per_gas_to_wei(%Wei{} = wei), do: wei
defp base_fee_per_gas_to_wei(base_fee_per_gas), do: %Wei{value: Decimal.new(base_fee_per_gas)}
@uncle_reward_coef 1 / 32
def block_reward_by_parts(block, transactions) do
%{hash: block_hash, number: block_number} = block
base_fee_per_gas = Map.get(block, :base_fee_per_gas)
txn_fees = txn_fees(transactions)
static_reward =
Repo.one(
from(
er in EmissionReward,
where: fragment("int8range(?, ?) <@ ?", ^block_number, ^(block_number + 1), er.block_range),
select: er.reward
)
) || %Wei{value: Decimal.new(0)}
has_uncles? = is_list(block.uncles) and not Enum.empty?(block.uncles)
burned_fees = burned_fees(transactions, base_fee_per_gas)
uncle_reward = (has_uncles? && Wei.mult(static_reward, Decimal.from_float(@uncle_reward_coef))) || nil
%{
block_number: block_number,
block_hash: block_hash,
miner_hash: block.miner_hash,
static_reward: static_reward,
txn_fees: %Wei{value: txn_fees},
burned_fees: burned_fees || %Wei{value: Decimal.new(0)},
uncle_reward: uncle_reward || %Wei{value: Decimal.new(0)}
}
end
@doc """
The `t:Explorer.Chain.Wei.t/0` paid to the miners of the `t:Explorer.Chain.Block.t/0`s with `hash`
`Explorer.Chain.Hash.Full.t/0` by the signers of the transactions in those blocks to cover the gas fee
(`gas_used * gas_price`).
"""
@spec gas_payment_by_block_hash([Hash.Full.t()]) :: %{Hash.Full.t() => Wei.t()}
def gas_payment_by_block_hash(block_hashes) when is_list(block_hashes) do
query =
from(
block in Block,
left_join: transaction in assoc(block, :transactions),
where: block.hash in ^block_hashes and block.consensus == true,
group_by: block.hash,
select: {block.hash, %Wei{value: coalesce(sum(transaction.gas_used * transaction.gas_price), 0)}}
)
query
|> Repo.all()
|> Enum.into(%{})
end
def timestamp_by_block_hash(block_hashes) when is_list(block_hashes) do
query =
from(
block in Block,
where: block.hash in ^block_hashes and block.consensus == true,
group_by: block.hash,
select: {block.hash, block.timestamp}
)
query
|> Repo.all()
|> Enum.into(%{})
end
@doc """
Finds all `t:Explorer.Chain.Transaction.t/0`s in the `t:Explorer.Chain.Block.t/0`.
## Options
* `:necessity_by_association` - use to load `t:association/0` as `:required` or `:optional`. If an association is
`:required`, and the `t:Explorer.Chain.Transaction.t/0` has no associated record for that association, then the
`t:Explorer.Chain.Transaction.t/0` will not be included in the page `entries`.
* `:paging_options` - a `t:Explorer.PagingOptions.t/0` used to specify the `:page_size` and
`:key` (a tuple of the lowest/oldest `{index}`) and. Results will be the transactions older than
the `index` that are passed.
"""
@spec block_to_transactions(Hash.Full.t(), [paging_options | necessity_by_association_option], true | false) :: [
Transaction.t()
]
def block_to_transactions(block_hash, options \\ [], old_ui? \\ true) when is_list(options) do
necessity_by_association = Keyword.get(options, :necessity_by_association, %{})
options
|> Keyword.get(:paging_options, @default_paging_options)
|> fetch_transactions_in_ascending_order_by_index()
|> join(:inner, [transaction], block in assoc(transaction, :block))
|> where([_, block], block.hash == ^block_hash)
|> join_associations(necessity_by_association)
|> (&if(old_ui?, do: preload(&1, [{:token_transfers, [:token, :from_address, :to_address]}]), else: &1)).()
|> Repo.all()
|> (&if(old_ui?,
do: &1,
else: Enum.map(&1, fn tx -> preload_token_transfers(tx, @token_transfers_necessity_by_association) end)
)).()
end
@doc """
Finds sum of gas_used for new (EIP-1559) txs belongs to block
"""
@spec block_to_gas_used_by_1559_txs(Hash.Full.t()) :: non_neg_integer()
def block_to_gas_used_by_1559_txs(block_hash) do
query =
from(
tx in Transaction,
where: tx.block_hash == ^block_hash,
select: sum(tx.gas_used)
)
result = Repo.one(query)
if result, do: result, else: 0
end
@doc """
Finds sum of priority fee for new (EIP-1559) txs belongs to block
"""
@spec block_to_priority_fee_of_1559_txs(Hash.Full.t()) :: Decimal.t()
def block_to_priority_fee_of_1559_txs(block_hash) do
block = Repo.get_by(Block, hash: block_hash)
case block.base_fee_per_gas do
%Wei{value: base_fee_per_gas} ->
query =
from(