-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy patheth.rs
More file actions
1325 lines (1172 loc) · 47.4 KB
/
eth.rs
File metadata and controls
1325 lines (1172 loc) · 47.4 KB
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
// Copyright 2022-2024 Protocol Labs
// SPDX-License-Identifier: Apache-2.0, MIT
// See the following for inspiration:
// * https://github.com/evmos/ethermint/blob/ebbe0ffd0d474abd745254dc01e60273ea758dae/rpc/namespaces/ethereum/eth/api.go#L44
// * https://github.com/filecoin-project/lotus/blob/v1.23.1-rc2/api/api_full.go#L783
// * https://github.com/filecoin-project/lotus/blob/v1.23.1-rc2/node/impl/full/eth.go
use std::collections::HashSet;
use anyhow::Context;
use ethers_core::types::transaction::eip2718::TypedTransaction;
use ethers_core::types::{self as et, BlockNumber};
use ethers_core::utils::rlp;
use fendermint_rpc::message::SignedMessageFactory;
use fendermint_rpc::query::QueryClient;
use fendermint_rpc::response::{decode_data, decode_fevm_invoke, decode_fevm_return_data};
use fendermint_vm_actor_interface::eam::{EthAddress, EAM_ACTOR_ADDR};
use fendermint_vm_actor_interface::evm;
use fendermint_vm_message::chain::ChainMessage;
use fendermint_vm_message::query::FvmQueryHeight;
use fendermint_vm_message::signed::SignedMessage;
use futures::FutureExt;
use fvm_ipld_encoding::RawBytes;
use fvm_shared::address::Address;
use fvm_shared::bigint::BigInt;
use fvm_shared::crypto::signature::Signature;
use fvm_shared::{chainid::ChainID, error::ExitCode};
use jsonrpc_v2::Params;
use rand::Rng;
use tendermint::block::Height;
use tendermint_rpc::endpoint::{self, status};
use tendermint_rpc::SubscriptionClient;
use tendermint_rpc::{
endpoint::{block, block_results, broadcast::tx_sync, consensus_params, header},
Client,
};
use fil_actors_evm_shared::uints;
use crate::conv::from_eth::{self, to_fvm_message};
use crate::conv::from_tm::{self, msg_hash, to_chain_message, to_cumulative, to_eth_block_zero};
use crate::error::{error_with_revert, OutOfSequence};
use crate::filters::{matches_topics, FilterId, FilterKind, FilterRecords};
use crate::{
conv::{
from_eth::to_fvm_address,
from_fvm::to_eth_tokens,
from_tm::{to_eth_receipt, to_eth_transaction},
},
error, JsonRpcData, JsonRpcResult,
};
/// Returns a list of addresses owned by client.
///
/// It will always return [] since we don't expect Fendermint to manage private keys.
pub async fn accounts<C>(_data: JsonRpcData<C>) -> JsonRpcResult<Vec<et::Address>> {
Ok(vec![])
}
/// Returns the number of most recent block.
pub async fn block_number<C>(data: JsonRpcData<C>) -> JsonRpcResult<et::U64>
where
C: Client + Sync + Send,
{
let height = data.latest_height().await?;
Ok(et::U64::from(height.value()))
}
/// Returns the chain ID used for signing replay-protected transactions.
pub async fn chain_id<C>(data: JsonRpcData<C>) -> JsonRpcResult<et::U64>
where
C: Client + Sync + Send,
{
let res = data.client.state_params(FvmQueryHeight::default()).await?;
Ok(et::U64::from(res.value.chain_id))
}
/// The current FVM network version.
pub async fn protocol_version<C>(data: JsonRpcData<C>) -> JsonRpcResult<String>
where
C: Client + Sync + Send,
{
let res = data.client.state_params(FvmQueryHeight::default()).await?;
let version: u32 = res.value.network_version.into();
Ok(version.to_string())
}
/// Returns a fee per gas that is an estimate of how much you can pay as a
/// priority fee, or 'tip', to get a transaction included in the current block.
pub async fn max_priority_fee_per_gas<C>(data: JsonRpcData<C>) -> JsonRpcResult<et::U256>
where
C: Client + Sync + Send,
{
// get the latest block
let res: block::Response = data.tm().latest_block().await?;
let latest_h = res.block.header.height;
// get consensus params to fetch block gas limit
// (this just needs to be done once as we assume that is constant
// for all blocks)
let consensus_params: consensus_params::Response = data
.tm()
.consensus_params(latest_h)
.await
.context("failed to get consensus params")?;
let mut block_gas_limit = consensus_params.consensus_params.block.max_gas;
if block_gas_limit <= 0 {
block_gas_limit =
i64::try_from(fvm_shared::BLOCK_GAS_LIMIT).expect("FVM block gas limit not i64")
};
let mut premiums = Vec::new();
// iterate through the blocks in the range
// we may be able to de-duplicate a lot of this code from fee_history
let latest_h: u64 = latest_h.into();
let mut blk = latest_h;
while blk > latest_h - data.gas_opt.num_blocks_max_prio_fee {
let block = data
.block_by_height(blk.into())
.await
.context("failed to get block")?;
let height = block.header().height;
// Genesis has height 1, but no relevant fees.
if height.value() <= 1 {
break;
}
let state_params = data
.client
.state_params(FvmQueryHeight::Height(height.value()))
.await?;
let base_fee = &state_params.value.base_fee;
// The latest block might not have results yet.
if let Ok(block_results) = data.tm().block_results(height).await {
let txs_results = block_results.txs_results.unwrap_or_default();
for (tx, txres) in block.data().iter().zip(txs_results) {
let msg = fvm_ipld_encoding::from_slice::<ChainMessage>(tx)
.context("failed to decode tx as ChainMessage")?;
if let ChainMessage::Signed(msg) = msg {
let premium = crate::gas::effective_gas_premium(&msg.message, base_fee);
premiums.push((premium, txres.gas_used));
}
}
}
blk -= 1;
}
// compute median gas price
let mut median = crate::gas::median_gas_premium(&mut premiums, block_gas_limit);
let min_premium = data.gas_opt.min_gas_premium.clone();
if median < min_premium {
median = min_premium;
}
// add some noise to normalize behaviour of message selection
// mean 1, stddev 0.005 => 95% within +-1%
const PRECISION: u32 = 32;
let mut rng = rand::thread_rng();
let noise: f64 = 1.0 + rng.gen::<f64>() * 0.005;
let precision: i64 = 32;
let coeff: u64 = ((noise * (1 << precision) as f64) as u64) + 1;
median *= BigInt::from(coeff);
median.div_ceil(BigInt::from(1 << PRECISION));
Ok(to_eth_tokens(&median)?)
}
/// Returns transaction base fee per gas and effective priority fee per gas for the requested/supported block range.
pub async fn fee_history<C>(
data: JsonRpcData<C>,
Params((block_count, last_block, reward_percentiles)): Params<(
et::U256,
et::BlockNumber,
Vec<f64>,
)>,
) -> JsonRpcResult<et::FeeHistory>
where
C: Client + Sync + Send,
{
if block_count > et::U256::from(data.gas_opt.max_fee_hist_size) {
return error(
ExitCode::USR_ILLEGAL_ARGUMENT,
"block_count must be <= 1024",
);
}
let mut hist = et::FeeHistory {
base_fee_per_gas: Vec::new(),
gas_used_ratio: Vec::new(),
oldest_block: et::U256::default(),
reward: Vec::new(),
};
let mut block_number = last_block;
let mut block_count = block_count.as_usize();
let get_base_fee = |height: Height| {
data.client
.state_params(FvmQueryHeight::Height(height.value()))
.map(|result| result.map(|state_params| state_params.value.base_fee))
};
while block_count > 0 {
let block = data
.block_by_height(block_number)
.await
.context("failed to get block")?;
let height = block.header().height;
// Apparently the base fees have to include the next fee after the newest block.
// See https://github.com/filecoin-project/lotus/blob/v1.25.2/node/impl/full/eth.go#L721-L725
if hist.base_fee_per_gas.is_empty() {
let base_fee = get_base_fee(height.increment())
.await
.context("failed to get next base fee")?;
hist.base_fee_per_gas.push(to_eth_tokens(&base_fee)?);
}
let base_fee = get_base_fee(height)
.await
.context("failed to get block base fee")?;
let consensus_params: consensus_params::Response = data
.tm()
.consensus_params(height)
.await
.context("failed to get consensus params")?;
let mut block_gas_limit = consensus_params.consensus_params.block.max_gas;
if block_gas_limit <= 0 {
block_gas_limit =
i64::try_from(fvm_shared::BLOCK_GAS_LIMIT).expect("FVM block gas limit not i64")
};
// The latest block might not have results yet.
if let Ok(block_results) = data.tm().block_results(height).await {
let txs_results = block_results.txs_results.unwrap_or_default();
let total_gas_used: i64 = txs_results.iter().map(|r| r.gas_used).sum();
let mut premiums = Vec::new();
for (tx, txres) in block.data().iter().zip(txs_results) {
let msg = fvm_ipld_encoding::from_slice::<ChainMessage>(tx)
.context("failed to decode tx as ChainMessage")?;
if let ChainMessage::Signed(msg) = msg {
let premium = crate::gas::effective_gas_premium(&msg.message, &base_fee);
premiums.push((premium, txres.gas_used));
}
}
premiums.sort();
let premium_gas_used: i64 = premiums.iter().map(|(_, gas)| *gas).sum();
let rewards: Result<Vec<et::U256>, _> = reward_percentiles
.iter()
.map(|p| {
if premiums.is_empty() {
Ok(et::U256::zero())
} else {
let threshold_gas_used = (premium_gas_used as f64 * p / 100f64) as i64;
let mut sum_gas_used = 0;
let mut idx = 0;
while sum_gas_used < threshold_gas_used && idx < premiums.len() - 1 {
sum_gas_used += premiums[idx].1;
idx += 1;
}
to_eth_tokens(&premiums[idx].0)
}
})
.collect();
hist.oldest_block = et::U256::from(height.value());
hist.base_fee_per_gas.push(to_eth_tokens(&base_fee)?);
hist.gas_used_ratio
.push(total_gas_used as f64 / block_gas_limit as f64);
hist.reward.push(rewards?);
block_count -= 1;
}
// Genesis has height 1.
if height.value() <= 1 {
break;
}
block_number = et::BlockNumber::Number(et::U64::from(height.value() - 1));
}
// Reverse data to be oldest-to-newest.
hist.base_fee_per_gas.reverse();
hist.gas_used_ratio.reverse();
hist.reward.reverse();
Ok(hist)
}
/// Returns the current price per gas in wei.
pub async fn gas_price<C>(data: JsonRpcData<C>) -> JsonRpcResult<et::U256>
where
C: Client + Sync + Send,
{
let res = data.client.state_params(FvmQueryHeight::default()).await?;
let price = to_eth_tokens(&res.value.base_fee)?;
Ok(price)
}
/// Returns the balance of the account of given address.
pub async fn get_balance<C>(
data: JsonRpcData<C>,
Params((addr, block_id)): Params<(et::Address, et::BlockId)>,
) -> JsonRpcResult<et::U256>
where
C: Client + Sync + Send,
{
let addr = to_fvm_address(addr);
let height = data.query_height(block_id).await?;
let res = data.client.actor_state(&addr, height).await?;
match res.value {
Some((_, state)) => Ok(to_eth_tokens(&state.balance)?),
None => Ok(et::U256::zero()),
}
}
/// Returns information about a block by hash.
pub async fn get_block_by_hash<C>(
data: JsonRpcData<C>,
Params((block_hash, full_tx)): Params<(et::H256, bool)>,
) -> JsonRpcResult<Option<et::Block<serde_json::Value>>>
where
C: Client + Sync + Send,
{
match data.block_by_hash_opt(block_hash).await? {
Some(block) if from_tm::is_block_zero(&block) => Ok(Some(to_eth_block_zero(block)?)),
Some(block) => data.enrich_block(block, full_tx).await.map(Some),
None => Ok(None),
}
}
/// Returns information about a block by block number.
pub async fn get_block_by_number<C>(
data: JsonRpcData<C>,
Params((block_number, full_tx)): Params<(et::BlockNumber, bool)>,
) -> JsonRpcResult<Option<et::Block<serde_json::Value>>>
where
C: Client + Sync + Send,
{
match data.block_by_height(block_number).await? {
block if block.header().height.value() > 0 => {
data.enrich_block(block, full_tx).await.map(Some)
}
block if from_tm::is_block_zero(&block) => Ok(Some(to_eth_block_zero(block)?)),
_ => Ok(None),
}
}
/// Returns the number of transactions in a block matching the given block number.
pub async fn get_block_transaction_count_by_number<C>(
data: JsonRpcData<C>,
Params((block_number,)): Params<(et::BlockNumber,)>,
) -> JsonRpcResult<et::U64>
where
C: Client + Sync + Send,
{
let block = data.block_by_height(block_number).await?;
Ok(et::U64::from(block.data.len()))
}
/// Returns the number of transactions in a block from a block matching the given block hash.
pub async fn get_block_transaction_count_by_hash<C>(
data: JsonRpcData<C>,
Params((block_hash,)): Params<(et::H256,)>,
) -> JsonRpcResult<et::U64>
where
C: Client + Sync + Send,
{
let block = data.block_by_hash_opt(block_hash).await?;
let count = block
.map(|b| et::U64::from(b.data.len()))
.unwrap_or_default();
Ok(count)
}
/// Returns the information about a transaction requested by transaction hash.
pub async fn get_transaction_by_block_hash_and_index<C>(
data: JsonRpcData<C>,
Params((block_hash, index)): Params<(et::H256, et::U64)>,
) -> JsonRpcResult<Option<et::Transaction>>
where
C: Client + Sync + Send,
{
if let Some(block) = data.block_by_hash_opt(block_hash).await? {
data.transaction_by_index(block, index).await
} else {
Ok(None)
}
}
/// Returns the information about a transaction requested by transaction hash.
pub async fn get_transaction_by_block_number_and_index<C>(
data: JsonRpcData<C>,
Params((block_number, index)): Params<(et::BlockNumber, et::U64)>,
) -> JsonRpcResult<Option<et::Transaction>>
where
C: Client + Sync + Send,
{
let block = data.block_by_height(block_number).await?;
data.transaction_by_index(block, index).await
}
/// Returns the information about a transaction requested by transaction hash.
pub async fn get_transaction_by_hash<C>(
data: JsonRpcData<C>,
Params((tx_hash,)): Params<(et::H256,)>,
) -> JsonRpcResult<Option<et::Transaction>>
where
C: Client + Sync + Send,
{
// Check in the pending cache first.
if let Some(tx) = data.tx_cache.get(&tx_hash) {
Ok(Some(tx))
} else if let Some(res) = data.tx_by_hash(tx_hash).await? {
let msg = to_chain_message(&res.tx)?;
if let ChainMessage::Signed(msg) = msg {
let header: header::Response = data.tm().header(res.height).await?;
let sp = data
.client
.state_params(FvmQueryHeight::Height(header.header.height.value()))
.await?;
let chain_id = ChainID::from(sp.value.chain_id);
let hash = msg_hash(&res.tx_result.events, &res.tx);
let mut tx = to_eth_transaction(msg, chain_id, hash)?;
tx.transaction_index = Some(et::U64::from(res.index));
tx.block_hash = Some(et::H256::from_slice(header.header.hash().as_bytes()));
tx.block_number = Some(et::U64::from(res.height.value()));
Ok(Some(tx))
} else {
error(ExitCode::USR_ILLEGAL_ARGUMENT, "incompatible transaction")
}
} else {
Ok(None)
}
}
/// Returns the number of transactions sent from an address, up to a specific block.
///
/// This is done by looking up the nonce of the account.
pub async fn get_transaction_count<C>(
data: JsonRpcData<C>,
Params((addr, block_id)): Params<(et::Address, et::BlockId)>,
) -> JsonRpcResult<et::U64>
where
C: Client + Sync + Send,
{
let addr = to_fvm_address(addr);
let height = data.query_height(block_id).await?;
let res = data.client.actor_state(&addr, height).await?;
match res.value {
Some((_, state)) => {
let nonce = state.sequence;
Ok(et::U64::from(nonce))
}
None => Ok(et::U64::zero()),
}
}
/// Returns the receipt of a transaction by transaction hash.
pub async fn get_transaction_receipt<C>(
data: JsonRpcData<C>,
Params((tx_hash,)): Params<(et::H256,)>,
) -> JsonRpcResult<Option<et::TransactionReceipt>>
where
C: Client + Sync + Send,
{
let Some(tx_res) = data.tx_by_hash(tx_hash).await? else {
return Ok(None);
};
let Ok(header) = data.tm().header(tx_res.height).await else {
// this means the txn hash is found, but block header is not found, this could happen
// when the txn is at the chain head and the block not finalized yet. We give the
// benefit of the doubt and return None for the txn
return Ok(None);
};
// Header is found, block results are expected to be present, raise error is not found
let block_results: block_results::Response = data.tm().block_results(tx_res.height).await?;
let cumulative = to_cumulative(&block_results);
let state_params = data
.client
.state_params(FvmQueryHeight::Height(header.header.height.value()))
.await?;
let msg = to_chain_message(&tx_res.tx)?;
if let ChainMessage::Signed(msg) = msg {
let receipt = to_eth_receipt(
&msg,
&tx_res,
&cumulative,
&header.header,
&state_params.value.base_fee,
)
.await
.context("failed to convert to receipt")?;
Ok(Some(receipt))
} else {
error(ExitCode::USR_ILLEGAL_ARGUMENT, "incompatible transaction")
}
}
/// Returns receipts for all the transactions in a block.
pub async fn get_block_receipts<C>(
data: JsonRpcData<C>,
Params((block_number,)): Params<(et::BlockNumber,)>,
) -> JsonRpcResult<Vec<et::TransactionReceipt>>
where
C: Client + Sync + Send,
{
let block = data.block_by_height(block_number).await?;
if from_tm::is_block_zero(&block) {
return Ok(Vec::new());
}
let height = block.header.height;
let state_params = data
.client
.state_params(FvmQueryHeight::Height(height.value()))
.await?;
let block_results: block_results::Response = data.tm().block_results(height).await?;
let cumulative = to_cumulative(&block_results);
let mut receipts = Vec::new();
for (index, (tx, tx_result)) in block
.data
.into_iter()
.zip(block_results.txs_results.unwrap_or_default())
.enumerate()
{
let msg = to_chain_message(&tx)?;
if let ChainMessage::Signed(msg) = msg {
let result = endpoint::tx::Response {
hash: Default::default(), // Shouldn't use this anyway.
height,
index: index as u32,
tx_result,
tx,
proof: None,
};
let receipt = to_eth_receipt(
&msg,
&result,
&cumulative,
&block.header,
&state_params.value.base_fee,
)
.await?;
receipts.push(receipt)
}
}
Ok(receipts)
}
/// Returns the number of uncles in a block from a block matching the given block hash.
///
/// It will always return 0 since Tendermint doesn't have uncles.
pub async fn get_uncle_count_by_block_hash<C>(
_data: JsonRpcData<C>,
_params: Params<(et::H256,)>,
) -> JsonRpcResult<et::U256> {
Ok(et::U256::zero())
}
/// Returns the number of uncles in a block from a block matching the given block number.
///
/// It will always return 0 since Tendermint doesn't have uncles.
pub async fn get_uncle_count_by_block_number<C>(
_data: JsonRpcData<C>,
_params: Params<(et::BlockNumber,)>,
) -> JsonRpcResult<et::U256> {
Ok(et::U256::zero())
}
/// Returns information about a uncle of a block by hash and uncle index position.
///
/// It will always return None since Tendermint doesn't have uncles.
pub async fn get_uncle_by_block_hash_and_index<C>(
_data: JsonRpcData<C>,
_params: Params<(et::H256, et::U64)>,
) -> JsonRpcResult<Option<et::Block<et::H256>>> {
Ok(None)
}
/// Returns information about a uncle of a block by number and uncle index position.
///
/// It will always return None since Tendermint doesn't have uncles.
pub async fn get_uncle_by_block_number_and_index<C>(
_data: JsonRpcData<C>,
_params: Params<(et::BlockNumber, et::U64)>,
) -> JsonRpcResult<Option<et::Block<et::H256>>> {
Ok(None)
}
/// Creates new message call transaction or a contract creation for signed transactions.
pub async fn send_raw_transaction<C>(
data: JsonRpcData<C>,
Params((tx,)): Params<(et::Bytes,)>,
) -> JsonRpcResult<et::TxHash>
where
C: Client + Sync + Send,
{
let rlp = rlp::Rlp::new(tx.as_ref());
let (tx, sig): (TypedTransaction, et::Signature) = TypedTransaction::decode_signed(&rlp)
.context("failed to decode RLP as signed TypedTransaction")?;
let sighash = tx.sighash();
let msghash = et::TxHash::from(ethers_core::utils::keccak256(rlp.as_raw()));
tracing::debug!(?sighash, eth_hash = ?msghash, ?tx, "received raw transaction");
if let Some(tx) = tx.as_eip1559_ref() {
let tx = from_eth::to_eth_transaction(tx.clone(), sig, msghash);
data.tx_cache.insert(msghash, tx);
}
let msg = to_fvm_message(tx, false)?;
let sender = msg.from;
let nonce = msg.sequence;
let msg = SignedMessage {
message: msg,
signature: Signature::new_secp256k1(sig.to_vec()),
};
let msg = ChainMessage::Signed(msg);
let bz: Vec<u8> = SignedMessageFactory::serialize(&msg)?;
// Use the broadcast version which waits for basic checks to complete,
// but not the execution results - those will have to be polled with get_transaction_receipt.
let res: tx_sync::Response = data.tm().broadcast_tx_sync(bz).await?;
if res.code.is_ok() {
// The following hash would be okay for ethers-rs,and we could use it to look up the TX with Tendermint,
// but ethers.js would reject it because it doesn't match what Ethereum would use.
// Ok(et::TxHash::from_slice(res.hash.as_bytes()))
Ok(msghash)
} else {
// Try to decode any errors returned in the data.
let bz = RawBytes::from(res.data.to_vec());
// Might have to first call `decode_fevm_data` here in case CometBFT
// wraps the data into Base64 encoding like it does for `DeliverTx`.
let bz = decode_fevm_return_data(bz)
.or_else(|_| decode_data(&res.data).and_then(decode_fevm_return_data))
.ok();
let exit_code = ExitCode::new(res.code.value());
// NOTE: We could have checked up front if we have buffered transactions already waiting,
// in which case this have just been appended to the list.
if let Some(oos) = OutOfSequence::try_parse(exit_code, &res.log) {
let is_admissible = oos.is_admissible(data.max_nonce_gap);
tracing::debug!(eth_hash = ?msghash, expected = oos.expected, got = oos.got, is_admissible, "out-of-sequence transaction received");
if is_admissible {
data.tx_buffer.insert(sender, nonce, msg);
return Ok(msghash);
}
}
error_with_revert(exit_code, res.log, bz)
}
}
/// Executes a new message call immediately without creating a transaction on the block chain.
pub async fn call<C>(
data: JsonRpcData<C>,
Params((tx, block_id)): Params<(TypedTransactionCompat, et::BlockId)>,
) -> JsonRpcResult<et::Bytes>
where
C: Client + Sync + Send,
{
let msg = to_fvm_message(tx.into(), true)?;
let is_create = msg.to == EAM_ACTOR_ADDR;
let height = data.query_height(block_id).await?;
let response = data.client.call(msg, height).await?;
let deliver_tx = response.value;
// Based on Lotus, we should return the data from the receipt.
if deliver_tx.code.is_err() {
// There might be some revert data encoded as ABI in the response.
let (msg, data) = match decode_fevm_invoke(&deliver_tx) {
Ok(h) => (deliver_tx.info, Some(h)),
Err(e) => (
format!("{}\nfailed to decode return data: {:#}", deliver_tx.info, e),
None,
),
};
error_with_revert(ExitCode::new(deliver_tx.code.value()), msg, data)
} else if is_create {
// It's not clear why some tools like Remix call this with deployment transaction, but they do.
// We could parse the deployed contract address, but it would be of very limited use;
// the call effect isn't persisted, so one would have to send an actual transaction
// and then run a call on `pending` state with this address to have a chance to hit
// that contract before the transaction is included in a block, assuming address
// creation is deterministic.
// Lotus returns empty: https://github.com/filecoin-project/lotus/blob/v1.23.1-rc2/node/impl/full/eth.go#L1091-L1094
Ok(Default::default())
} else {
let return_data = decode_fevm_invoke(&deliver_tx)
.context("error decoding data from deliver_tx in query")?;
Ok(return_data.into())
}
}
/// Generates and returns an estimate of how much gas is necessary to allow the transaction to complete.
/// The transaction will not be added to the blockchain.
/// Note that the estimate may be significantly more than the amount of gas actually used by the transaction, f
/// or a variety of reasons including EVM mechanics and node performance.
pub async fn estimate_gas<C>(
data: JsonRpcData<C>,
Params(params): Params<EstimateGasParams>,
) -> JsonRpcResult<et::U256>
where
C: Client + Sync + Send,
{
let (tx, block_id) = match params {
EstimateGasParams::One((tx,)) => (tx, et::BlockId::Number(et::BlockNumber::Latest)),
EstimateGasParams::Two((tx, block_id)) => (tx, block_id),
};
let msg = to_fvm_message(tx.into(), true).context("failed to convert to FVM message")?;
let height = data
.query_height(block_id)
.await
.context("failed to get height")?;
let response = data
.client
.estimate_gas(msg, height)
.await
.context("failed to call estimate gas query")?;
let estimate = response.value;
if !estimate.exit_code.is_success() {
// There might be some revert data encoded as ABI in the response.
let msg = format!("failed to estimate gas: {}", estimate.info);
let (msg, data) = match decode_fevm_return_data(estimate.return_data) {
Ok(h) => (msg, Some(h)),
Err(e) => (format!("{msg}\n{e:#}"), None),
};
error_with_revert(estimate.exit_code, msg, data)
} else {
Ok(estimate.gas_limit.into())
}
}
/// Returns the value from a storage position at a given address.
///
/// The return value is a hex encoded U256.
pub async fn get_storage_at<C>(
data: JsonRpcData<C>,
Params((address, position, block_id)): Params<(et::H160, et::U256, et::BlockId)>,
) -> JsonRpcResult<String>
where
C: Client + Sync + Send,
{
let encode = |data: Option<uints::U256>| {
let mut bz = [0u8; 32];
if let Some(data) = data {
data.to_big_endian(&mut bz);
}
// The client library expects hex encoded string. The JS client might want a prefix too.
Ok(format!("0x{}", hex::encode(bz)))
};
let height = data.query_height(block_id).await?;
// If not an EVM actor, return empty.
if data.get_actor_type(&address, height).await? != ActorType::EVM {
// The client library expects hex encoded string.
return encode(None);
}
let params = evm::GetStorageAtParams {
storage_key: {
let mut bz = [0u8; 32];
position.to_big_endian(&mut bz);
evm::uints::U256::from_big_endian(&bz)
},
};
let params = RawBytes::serialize(params).context("failed to serialize position to IPLD")?;
let ret = data
.read_evm_actor::<evm::GetStorageAtReturn>(
address,
evm::Method::GetStorageAt,
params,
height,
)
.await?;
if let Some(ret) = ret {
// ret.storage.to_big_endian(&mut bz);
return encode(Some(ret.storage));
}
encode(None)
}
/// Returns code at a given address.
pub async fn get_code<C>(
data: JsonRpcData<C>,
Params((address, block_id)): Params<(et::H160, et::BlockId)>,
) -> JsonRpcResult<et::Bytes>
where
C: Client + Sync + Send,
{
let height = data.query_height(block_id).await?;
// Return empty if not an EVM actor.
if data.get_actor_type(&address, height).await? != ActorType::EVM {
return Ok(Default::default());
}
// This method has no input parameters.
let params = RawBytes::default();
let ret = data
.read_evm_actor::<evm::BytecodeReturn>(address, evm::Method::GetBytecode, params, height)
.await?;
match ret.and_then(|r| r.code) {
None => Ok(et::Bytes::default()),
Some(cid) => {
let code = data
.client
.ipld(&cid, height)
.await
.context("failed to fetch bytecode")?;
Ok(code.map(et::Bytes::from).unwrap_or_default())
}
}
}
/// Returns an object with data about the sync status or false.
pub async fn syncing<C>(data: JsonRpcData<C>) -> JsonRpcResult<et::SyncingStatus>
where
C: Client + Sync + Send,
{
let status: status::Response = data.tm().status().await.context("failed to fetch status")?;
let info = status.sync_info;
let status = if !info.catching_up {
et::SyncingStatus::IsFalse
} else {
let progress = et::SyncProgress {
// This would be the block we executed.
current_block: et::U64::from(info.latest_block_height.value()),
// This would be the block we know about but haven't got to yet.
highest_block: et::U64::from(info.latest_block_height.value()),
// This would be the block we started syncing from.
starting_block: Default::default(),
pulled_states: None,
known_states: None,
healed_bytecode_bytes: None,
healed_bytecodes: None,
healed_trienode_bytes: None,
healed_trienodes: None,
healing_bytecode: None,
healing_trienodes: None,
synced_account_bytes: None,
synced_accounts: None,
synced_bytecode_bytes: None,
synced_bytecodes: None,
synced_storage: None,
synced_storage_bytes: None,
};
et::SyncingStatus::IsSyncing(Box::new(progress))
};
Ok(status)
}
/// Returns an array of all logs matching a given filter object.
pub async fn get_logs<C>(
data: JsonRpcData<C>,
Params((filter,)): Params<(et::Filter,)>,
) -> JsonRpcResult<Vec<et::Log>>
where
C: Client + Sync + Send,
{
let (from_height, to_height) = match filter.block_option {
et::FilterBlockOption::Range {
from_block,
to_block,
} => {
// Turn block number into a height.
async fn resolve_height<C: Client + Send + Sync>(
data: &JsonRpcData<C>,
bn: BlockNumber,
) -> JsonRpcResult<Height> {
match bn {
BlockNumber::Number(n) => {
Ok(Height::try_from(n.as_u64()).context("invalid height")?)
}
other => {
let h = data.header_by_height(other).await?;
Ok(h.height)
}
}
}
let from_block = from_block.unwrap_or_default();
let mut to_block = to_block.unwrap_or_default();
// Automatically restrict the end to the highest available block to allow queries by fixed ranges.
// This is only applied ot the end, not the start, so if `from > to` then we return nothing.
if let BlockNumber::Number(n) = to_block {
let latest_height = data.latest_height().await?;
if n.as_u64() > latest_height.value() {
to_block = BlockNumber::Number(et::U64::from(latest_height.value()));
}
}
// Resolve named heights to a number.
let to_height = resolve_height(&data, to_block).await?;
let from_height = if from_block == to_block {
to_height
} else {
resolve_height(&data, from_block).await?
};
(from_height, to_height)
}
et::FilterBlockOption::AtBlockHash(block_hash) => {
let header = data.header_by_hash(block_hash).await?;
(header.height, header.height)
}
};
let addrs = match &filter.address {
Some(et::ValueOrArray::Value(addr)) => vec![*addr],
Some(et::ValueOrArray::Array(addrs)) => addrs.clone(),
None => Vec::new(),
};
let addrs = addrs
.into_iter()
.map(|addr| Address::from(EthAddress(addr.0)))
.collect::<HashSet<_>>();
let mut height = from_height;
let mut logs = Vec::new();
while height <= to_height {
if let Ok(block_results) = data.tm().block_results(height).await {
let block_number = et::U64::from(height.value());
if let Some(tx_results) = block_results.txs_results {
let block = data
.block_by_height(et::BlockNumber::Number(block_number))
.await?;
let block_hash = et::H256::from_slice(block.header().hash().as_bytes());
let mut log_index_start = 0usize;
for ((tx_idx, tx_result), tx) in tx_results.iter().enumerate().zip(block.data()) {
let emitters = from_tm::collect_emitters(&tx_result.events);
let no_intersection =
!addrs.is_empty() && addrs.intersection(&emitters).next().is_none();
match to_chain_message(tx) {
Ok(ChainMessage::Signed(msg)) => {
// Filter by sender and recipient addresses.
if no_intersection
&& !addrs.contains(&msg.message().from)
&& !addrs.contains(&msg.message().to)
{
continue;
}
}
Ok(ChainMessage::Ipc(_)) => {
// ipc messages are system messages, no need to check from and to
if no_intersection {
continue;
}
}
_ => continue,
};