This repository has been archived by the owner on Oct 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 792
/
provider.rs
2059 lines (1794 loc) · 72.7 KB
/
provider.rs
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
use ethers_core::types::SyncingStatus;
use crate::{
call_raw::CallBuilder,
errors::ProviderError,
ext::{ens, erc},
stream::{FilterWatcher, DEFAULT_LOCAL_POLL_INTERVAL, DEFAULT_POLL_INTERVAL},
utils::maybe,
Http as HttpProvider, JsonRpcClient, JsonRpcClientWrapper, LogQuery, MiddlewareError,
MockProvider, NodeInfo, PeerInfo, PendingTransaction, PubsubClient, QuorumProvider, RwClient,
SubscriptionStream,
};
#[cfg(not(target_arch = "wasm32"))]
use crate::{HttpRateLimitRetryPolicy, RetryClient};
use std::net::Ipv4Addr;
pub use crate::Middleware;
use async_trait::async_trait;
use ethers_core::{
abi::{self, Detokenize, ParamType},
types::{
transaction::{eip2718::TypedTransaction, eip2930::AccessListWithGasUsed},
Address, Block, BlockId, BlockNumber, BlockTrace, Bytes, Chain, EIP1186ProofResponse,
FeeHistory, Filter, FilterBlockOption, GethDebugTracingCallOptions,
GethDebugTracingOptions, GethTrace, Log, NameOrAddress, Selector, Signature, Trace,
TraceFilter, TraceType, Transaction, TransactionReceipt, TransactionRequest, TxHash,
TxpoolContent, TxpoolInspect, TxpoolStatus, H256, U256, U64,
},
utils,
};
use futures_util::{lock::Mutex, try_join};
use serde::{de::DeserializeOwned, Serialize};
use std::{collections::VecDeque, fmt::Debug, str::FromStr, sync::Arc, time::Duration};
use tracing::trace;
use tracing_futures::Instrument;
use url::{Host, ParseError, Url};
/// Node Clients
#[derive(Copy, Clone)]
pub enum NodeClient {
/// Geth
Geth,
/// Erigon
Erigon,
/// OpenEthereum
OpenEthereum,
/// Nethermind
Nethermind,
/// Besu
Besu,
}
impl FromStr for NodeClient {
type Err = ProviderError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.split('/').next().unwrap().to_lowercase().as_str() {
"geth" => Ok(NodeClient::Geth),
"erigon" => Ok(NodeClient::Erigon),
"openethereum" => Ok(NodeClient::OpenEthereum),
"nethermind" => Ok(NodeClient::Nethermind),
"besu" => Ok(NodeClient::Besu),
_ => Err(ProviderError::UnsupportedNodeClient),
}
}
}
/// An abstract provider for interacting with the [Ethereum JSON RPC
/// API](https://github.com/ethereum/wiki/wiki/JSON-RPC). Must be instantiated
/// with a data transport which implements the [`JsonRpcClient`](trait@crate::JsonRpcClient) trait
/// (e.g. [HTTP](crate::Http), Websockets etc.)
///
/// # Example
///
/// ```no_run
/// # async fn foo() -> Result<(), Box<dyn std::error::Error>> {
/// use ethers_providers::{Middleware, Provider, Http};
/// use std::convert::TryFrom;
///
/// let provider = Provider::<Http>::try_from(
/// "https://eth.llamarpc.com"
/// ).expect("could not instantiate HTTP Provider");
///
/// let block = provider.get_block(100u64).await?;
/// println!("Got block: {}", serde_json::to_string(&block)?);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct Provider<P> {
inner: P,
ens: Option<Address>,
interval: Option<Duration>,
from: Option<Address>,
/// Node client hasn't been checked yet = `None`
/// Unsupported node client = `Some(None)`
/// Supported node client = `Some(Some(NodeClient))`
_node_client: Arc<Mutex<Option<NodeClient>>>,
}
impl<P> AsRef<P> for Provider<P> {
fn as_ref(&self) -> &P {
&self.inner
}
}
/// Types of filters supported by the JSON-RPC.
#[derive(Clone, Debug)]
pub enum FilterKind<'a> {
/// `eth_newBlockFilter`
Logs(&'a Filter),
/// `eth_newBlockFilter` filter
NewBlocks,
/// `eth_newPendingTransactionFilter` filter
PendingTransactions,
}
// JSON RPC bindings
impl<P: JsonRpcClient> Provider<P> {
/// Instantiate a new provider with a backend.
pub fn new(provider: P) -> Self {
Self {
inner: provider,
ens: None,
interval: None,
from: None,
_node_client: Arc::new(Mutex::new(None)),
}
}
/// Returns the type of node we're connected to, while also caching the value for use
/// in other node-specific API calls, such as the get_block_receipts call.
pub async fn node_client(&self) -> Result<NodeClient, ProviderError> {
let mut node_client = self._node_client.lock().await;
if let Some(node_client) = *node_client {
Ok(node_client)
} else {
let client_version = self.client_version().await?;
let client_version = match client_version.parse::<NodeClient>() {
Ok(res) => res,
Err(_) => return Err(ProviderError::UnsupportedNodeClient),
};
*node_client = Some(client_version);
Ok(client_version)
}
}
#[must_use]
/// Set the default sender on the provider
pub fn with_sender(mut self, address: impl Into<Address>) -> Self {
self.from = Some(address.into());
self
}
/// Make an RPC request via the internal connection, and return the result.
pub async fn request<T, R>(&self, method: &str, params: T) -> Result<R, ProviderError>
where
T: Debug + Serialize + Send + Sync,
R: Serialize + DeserializeOwned + Debug + Send,
{
let span =
tracing::trace_span!("rpc", method = method, params = ?serde_json::to_string(¶ms)?);
// https://docs.rs/tracing/0.1.22/tracing/span/struct.Span.html#in-asynchronous-code
let res = async move {
trace!("tx");
let res: R = self.inner.request(method, params).await.map_err(Into::into)?;
trace!(rx = ?serde_json::to_string(&res)?);
Ok::<_, ProviderError>(res)
}
.instrument(span)
.await?;
Ok(res)
}
async fn get_block_gen<Tx: Default + Serialize + DeserializeOwned + Debug + Send>(
&self,
id: BlockId,
include_txs: bool,
) -> Result<Option<Block<Tx>>, ProviderError> {
let include_txs = utils::serialize(&include_txs);
Ok(match id {
BlockId::Hash(hash) => {
let hash = utils::serialize(&hash);
self.request("eth_getBlockByHash", [hash, include_txs]).await?
}
BlockId::Number(num) => {
let num = utils::serialize(&num);
self.request("eth_getBlockByNumber", [num, include_txs]).await?
}
})
}
/// Analogous to [`Middleware::call`], but returns a [`CallBuilder`] that can either be
/// `.await`d or used to override the parameters sent to `eth_call`.
///
/// See the [`ethers_core::types::spoof`] for functions to construct state override
/// parameters.
///
/// Note: this method _does not_ send a transaction from your account
///
/// [`ethers_core::types::spoof`]: ethers_core::types::spoof
///
/// # Example
///
/// ```no_run
/// # use ethers_core::{
/// # types::{Address, TransactionRequest, H256, spoof},
/// # utils::{parse_ether, Geth},
/// # };
/// # use ethers_providers::{Provider, Http, Middleware, call_raw::RawCall};
/// # async fn foo() -> Result<(), Box<dyn std::error::Error>> {
/// let geth = Geth::new().spawn();
/// let provider = Provider::<Http>::try_from(geth.endpoint()).unwrap();
///
/// let adr1: Address = "0x6fC21092DA55B392b045eD78F4732bff3C580e2c".parse()?;
/// let adr2: Address = "0x295a70b2de5e3953354a6a8344e616ed314d7251".parse()?;
/// let pay_amt = parse_ether(1u64)?;
///
/// // Not enough ether to pay for the transaction
/// let tx = TransactionRequest::pay(adr2, pay_amt).from(adr1).into();
///
/// // override the sender's balance for the call
/// let mut state = spoof::balance(adr1, pay_amt * 2);
/// provider.call_raw(&tx).state(&state).await?;
/// # Ok(()) }
/// ```
pub fn call_raw<'a>(&'a self, tx: &'a TypedTransaction) -> CallBuilder<'a, P> {
CallBuilder::new(self, tx)
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<P: JsonRpcClient> Middleware for Provider<P> {
type Error = ProviderError;
type Provider = P;
type Inner = Self;
fn inner(&self) -> &Self::Inner {
unreachable!("There is no inner provider here")
}
fn provider(&self) -> &Provider<Self::Provider> {
self
}
fn convert_err(p: ProviderError) -> Self::Error {
// no conversion necessary
p
}
fn default_sender(&self) -> Option<Address> {
self.from
}
async fn client_version(&self) -> Result<String, Self::Error> {
self.request("web3_clientVersion", ()).await
}
async fn fill_transaction(
&self,
tx: &mut TypedTransaction,
block: Option<BlockId>,
) -> Result<(), Self::Error> {
if let Some(default_sender) = self.default_sender() {
if tx.from().is_none() {
tx.set_from(default_sender);
}
}
// TODO: Join the name resolution and gas price future
// set the ENS name
if let Some(NameOrAddress::Name(ref ens_name)) = tx.to() {
let addr = self.resolve_name(ens_name).await?;
tx.set_to(addr);
}
// fill gas price
match tx {
TypedTransaction::Eip2930(_) | TypedTransaction::Legacy(_) => {
let gas_price = maybe(tx.gas_price(), self.get_gas_price()).await?;
tx.set_gas_price(gas_price);
}
TypedTransaction::Eip1559(ref mut inner) => {
if inner.max_fee_per_gas.is_none() || inner.max_priority_fee_per_gas.is_none() {
let (max_fee_per_gas, max_priority_fee_per_gas) =
self.estimate_eip1559_fees(None).await?;
// we want to avoid overriding the user if either of these
// are set. In order to do this, we refuse to override the
// `max_fee_per_gas` if already set.
// However, we must preserve the constraint that the tip
// cannot be higher than max fee, so we override user
// intent if that is so. We override by
// - first: if set, set to the min(current value, MFPG)
// - second, if still unset, use the RPC estimated amount
let mfpg = inner.max_fee_per_gas.get_or_insert(max_fee_per_gas);
inner.max_priority_fee_per_gas = inner
.max_priority_fee_per_gas
.map(|tip| std::cmp::min(tip, *mfpg))
.or(Some(max_priority_fee_per_gas));
};
}
#[cfg(feature = "optimism")]
TypedTransaction::DepositTransaction(_) => {
let gas_price = maybe(tx.gas_price(), self.get_gas_price()).await?;
tx.set_gas_price(gas_price);
}
}
// Set gas to estimated value only if it was not set by the caller,
// even if the access list has been populated and saves gas
if tx.gas().is_none() {
let gas_estimate = self.estimate_gas(tx, block).await?;
tx.set_gas(gas_estimate);
}
Ok(())
}
async fn get_block_number(&self) -> Result<U64, ProviderError> {
self.request("eth_blockNumber", ()).await
}
async fn get_block<T: Into<BlockId> + Send + Sync>(
&self,
block_hash_or_number: T,
) -> Result<Option<Block<TxHash>>, Self::Error> {
self.get_block_gen(block_hash_or_number.into(), false).await
}
async fn get_header<T: Into<BlockId> + Send + Sync>(
&self,
block_hash_or_number: T,
) -> Result<Option<Block<Transaction>>, Self::Error> {
let id = block_hash_or_number.into();
Ok(match id {
BlockId::Number(num) => {
let num = utils::serialize(&num);
self.request("eth_getHeaderByNumber", [num]).await?
}
BlockId::Hash(hash) => {
let hash = utils::serialize(&hash);
self.request("eth_getHeaderByHash", [hash]).await?
}
})
}
async fn get_block_with_txs<T: Into<BlockId> + Send + Sync>(
&self,
block_hash_or_number: T,
) -> Result<Option<Block<Transaction>>, ProviderError> {
self.get_block_gen(block_hash_or_number.into(), true).await
}
async fn get_uncle_count<T: Into<BlockId> + Send + Sync>(
&self,
block_hash_or_number: T,
) -> Result<U256, Self::Error> {
let id = block_hash_or_number.into();
Ok(match id {
BlockId::Hash(hash) => {
let hash = utils::serialize(&hash);
self.request("eth_getUncleCountByBlockHash", [hash]).await?
}
BlockId::Number(num) => {
let num = utils::serialize(&num);
self.request("eth_getUncleCountByBlockNumber", [num]).await?
}
})
}
async fn get_uncle<T: Into<BlockId> + Send + Sync>(
&self,
block_hash_or_number: T,
idx: U64,
) -> Result<Option<Block<H256>>, ProviderError> {
let blk_id = block_hash_or_number.into();
let idx = utils::serialize(&idx);
Ok(match blk_id {
BlockId::Hash(hash) => {
let hash = utils::serialize(&hash);
self.request("eth_getUncleByBlockHashAndIndex", [hash, idx]).await?
}
BlockId::Number(num) => {
let num = utils::serialize(&num);
self.request("eth_getUncleByBlockNumberAndIndex", [num, idx]).await?
}
})
}
async fn get_transaction<T: Send + Sync + Into<TxHash>>(
&self,
transaction_hash: T,
) -> Result<Option<Transaction>, ProviderError> {
let hash = transaction_hash.into();
self.request("eth_getTransactionByHash", [hash]).await
}
async fn get_transaction_by_block_and_index<T: Into<BlockId> + Send + Sync>(
&self,
block_hash_or_number: T,
idx: U64,
) -> Result<Option<Transaction>, ProviderError> {
let blk_id = block_hash_or_number.into();
let idx = ethers_core::utils::serialize(&idx);
Ok(match blk_id {
BlockId::Hash(hash) => {
let hash = ethers_core::utils::serialize(&hash);
self.request("eth_getTransactionByBlockHashAndIndex", [hash, idx]).await?
}
BlockId::Number(num) => {
let num = ethers_core::utils::serialize(&num);
self.request("eth_getTransactionByBlockNumberAndIndex", [num, idx]).await?
}
})
}
async fn get_transaction_receipt<T: Send + Sync + Into<TxHash>>(
&self,
transaction_hash: T,
) -> Result<Option<TransactionReceipt>, ProviderError> {
let hash = transaction_hash.into();
self.request("eth_getTransactionReceipt", [hash]).await
}
async fn get_block_receipts<T: Into<BlockNumber> + Send + Sync>(
&self,
block: T,
) -> Result<Vec<TransactionReceipt>, Self::Error> {
self.request("eth_getBlockReceipts", [block.into()]).await
}
async fn parity_block_receipts<T: Into<BlockNumber> + Send + Sync>(
&self,
block: T,
) -> Result<Vec<TransactionReceipt>, Self::Error> {
self.request("parity_getBlockReceipts", vec![block.into()]).await
}
async fn get_gas_price(&self) -> Result<U256, ProviderError> {
self.request("eth_gasPrice", ()).await
}
async fn estimate_eip1559_fees(
&self,
estimator: Option<fn(U256, Vec<Vec<U256>>) -> (U256, U256)>,
) -> Result<(U256, U256), Self::Error> {
let base_fee_per_gas = self
.get_block(BlockNumber::Latest)
.await?
.ok_or_else(|| ProviderError::CustomError("Latest block not found".into()))?
.base_fee_per_gas
.ok_or_else(|| ProviderError::CustomError("EIP-1559 not activated".into()))?;
let fee_history = self
.fee_history(
utils::EIP1559_FEE_ESTIMATION_PAST_BLOCKS,
BlockNumber::Latest,
&[utils::EIP1559_FEE_ESTIMATION_REWARD_PERCENTILE],
)
.await?;
// use the provided fee estimator function, or fallback to the default implementation.
let (max_fee_per_gas, max_priority_fee_per_gas) = if let Some(es) = estimator {
es(base_fee_per_gas, fee_history.reward)
} else {
utils::eip1559_default_estimator(base_fee_per_gas, fee_history.reward)
};
Ok((max_fee_per_gas, max_priority_fee_per_gas))
}
async fn get_accounts(&self) -> Result<Vec<Address>, ProviderError> {
self.request("eth_accounts", ()).await
}
async fn get_transaction_count<T: Into<NameOrAddress> + Send + Sync>(
&self,
from: T,
block: Option<BlockId>,
) -> Result<U256, ProviderError> {
let from = match from.into() {
NameOrAddress::Name(ens_name) => self.resolve_name(&ens_name).await?,
NameOrAddress::Address(addr) => addr,
};
let from = utils::serialize(&from);
let block = utils::serialize(&block.unwrap_or_else(|| BlockNumber::Latest.into()));
self.request("eth_getTransactionCount", [from, block]).await
}
async fn get_balance<T: Into<NameOrAddress> + Send + Sync>(
&self,
from: T,
block: Option<BlockId>,
) -> Result<U256, ProviderError> {
let from = match from.into() {
NameOrAddress::Name(ens_name) => self.resolve_name(&ens_name).await?,
NameOrAddress::Address(addr) => addr,
};
let from = utils::serialize(&from);
let block = utils::serialize(&block.unwrap_or_else(|| BlockNumber::Latest.into()));
self.request("eth_getBalance", [from, block]).await
}
async fn get_chainid(&self) -> Result<U256, ProviderError> {
self.request("eth_chainId", ()).await
}
async fn syncing(&self) -> Result<SyncingStatus, Self::Error> {
self.request("eth_syncing", ()).await
}
async fn get_net_version(&self) -> Result<String, ProviderError> {
self.request("net_version", ()).await
}
async fn call(
&self,
tx: &TypedTransaction,
block: Option<BlockId>,
) -> Result<Bytes, ProviderError> {
let tx = utils::serialize(tx);
let block = utils::serialize(&block.unwrap_or_else(|| BlockNumber::Latest.into()));
self.request("eth_call", [tx, block]).await
}
async fn estimate_gas(
&self,
tx: &TypedTransaction,
block: Option<BlockId>,
) -> Result<U256, ProviderError> {
let tx = utils::serialize(tx);
// Some nodes (e.g. old Optimism clients) don't support a block ID being passed as a param,
// so refrain from defaulting to BlockNumber::Latest.
let params = if let Some(block_id) = block {
vec![tx, utils::serialize(&block_id)]
} else {
vec![tx]
};
self.request("eth_estimateGas", params).await
}
async fn create_access_list(
&self,
tx: &TypedTransaction,
block: Option<BlockId>,
) -> Result<AccessListWithGasUsed, ProviderError> {
let tx = utils::serialize(tx);
let block = utils::serialize(&block.unwrap_or_else(|| BlockNumber::Latest.into()));
self.request("eth_createAccessList", [tx, block]).await
}
async fn send_transaction<T: Into<TypedTransaction> + Send + Sync>(
&self,
tx: T,
block: Option<BlockId>,
) -> Result<PendingTransaction<'_, P>, ProviderError> {
let mut tx = tx.into();
self.fill_transaction(&mut tx, block).await?;
let tx_hash = self.request("eth_sendTransaction", [tx]).await?;
Ok(PendingTransaction::new(tx_hash, self))
}
async fn send_raw_transaction<'a>(
&'a self,
tx: Bytes,
) -> Result<PendingTransaction<'a, P>, ProviderError> {
let rlp = utils::serialize(&tx);
let tx_hash = self.request("eth_sendRawTransaction", [rlp]).await?;
Ok(PendingTransaction::new(tx_hash, self))
}
async fn is_signer(&self) -> bool {
match self.from {
Some(sender) => self.sign(vec![], &sender).await.is_ok(),
None => false,
}
}
async fn sign<T: Into<Bytes> + Send + Sync>(
&self,
data: T,
from: &Address,
) -> Result<Signature, ProviderError> {
let data = utils::serialize(&data.into());
let from = utils::serialize(from);
// get the response from `eth_sign` call
let sig: String = self.request("eth_sign", [from, data]).await?;
// decode the signature
let sig = hex::decode(sig)?;
Ok(Signature::try_from(sig.as_slice())
.map_err(|e| ProviderError::CustomError(e.to_string()))?)
}
/// Sign a transaction via RPC call
async fn sign_transaction(
&self,
_tx: &TypedTransaction,
_from: Address,
) -> Result<Signature, Self::Error> {
Err(MiddlewareError::from_err(ProviderError::SignerUnavailable))
}
////// Contract state
async fn get_logs(&self, filter: &Filter) -> Result<Vec<Log>, ProviderError> {
self.request("eth_getLogs", [filter]).await
}
fn get_logs_paginated<'a>(&'a self, filter: &Filter, page_size: u64) -> LogQuery<'a, P> {
LogQuery::new(self, filter).with_page_size(page_size)
}
async fn watch<'a>(
&'a self,
filter: &Filter,
) -> Result<FilterWatcher<'a, P, Log>, ProviderError> {
let id = self.new_filter(FilterKind::Logs(filter)).await?;
let filter = FilterWatcher::new(id, self).interval(self.get_interval());
Ok(filter)
}
async fn watch_blocks(&self) -> Result<FilterWatcher<'_, P, H256>, ProviderError> {
let id = self.new_filter(FilterKind::NewBlocks).await?;
let filter = FilterWatcher::new(id, self).interval(self.get_interval());
Ok(filter)
}
/// Streams pending transactions
async fn watch_pending_transactions(
&self,
) -> Result<FilterWatcher<'_, P, H256>, ProviderError> {
let id = self.new_filter(FilterKind::PendingTransactions).await?;
let filter = FilterWatcher::new(id, self).interval(self.get_interval());
Ok(filter)
}
async fn new_filter(&self, filter: FilterKind<'_>) -> Result<U256, ProviderError> {
let (method, args) = match filter {
FilterKind::NewBlocks => ("eth_newBlockFilter", vec![]),
FilterKind::PendingTransactions => ("eth_newPendingTransactionFilter", vec![]),
FilterKind::Logs(filter) => ("eth_newFilter", vec![utils::serialize(&filter)]),
};
self.request(method, args).await
}
async fn uninstall_filter<T: Into<U256> + Send + Sync>(
&self,
id: T,
) -> Result<bool, ProviderError> {
let id = utils::serialize(&id.into());
self.request("eth_uninstallFilter", [id]).await
}
async fn get_filter_changes<T, R>(&self, id: T) -> Result<Vec<R>, ProviderError>
where
T: Into<U256> + Send + Sync,
R: Serialize + DeserializeOwned + Send + Sync + Debug,
{
let id = utils::serialize(&id.into());
self.request("eth_getFilterChanges", [id]).await
}
async fn get_storage_at<T: Into<NameOrAddress> + Send + Sync>(
&self,
from: T,
location: H256,
block: Option<BlockId>,
) -> Result<H256, ProviderError> {
let from = match from.into() {
NameOrAddress::Name(ens_name) => self.resolve_name(&ens_name).await?,
NameOrAddress::Address(addr) => addr,
};
// position is a QUANTITY according to the [spec](https://eth.wiki/json-rpc/API#eth_getstorageat): integer of the position in the storage, converting this to a U256
// will make sure the number is formatted correctly as [quantity](https://eips.ethereum.org/EIPS/eip-1474#quantity)
let position = U256::from_big_endian(location.as_bytes());
let position = utils::serialize(&position);
let from = utils::serialize(&from);
let block = utils::serialize(&block.unwrap_or_else(|| BlockNumber::Latest.into()));
// get the hex encoded value
let value: String = self.request("eth_getStorageAt", [from, position, block]).await?;
// decode and left-pad to 32 bytes
let bytes = hex::decode(value)?;
if bytes.len() > 32 {
Err(hex::FromHexError::InvalidStringLength.into())
} else {
let mut buf = [0; 32];
buf[32 - bytes.len()..].copy_from_slice(&bytes);
Ok(H256(buf))
}
}
async fn get_code<T: Into<NameOrAddress> + Send + Sync>(
&self,
at: T,
block: Option<BlockId>,
) -> Result<Bytes, ProviderError> {
let at = match at.into() {
NameOrAddress::Name(ens_name) => self.resolve_name(&ens_name).await?,
NameOrAddress::Address(addr) => addr,
};
let at = utils::serialize(&at);
let block = utils::serialize(&block.unwrap_or_else(|| BlockNumber::Latest.into()));
self.request("eth_getCode", [at, block]).await
}
async fn get_proof<T: Into<NameOrAddress> + Send + Sync>(
&self,
from: T,
locations: Vec<H256>,
block: Option<BlockId>,
) -> Result<EIP1186ProofResponse, ProviderError> {
let from = match from.into() {
NameOrAddress::Name(ens_name) => self.resolve_name(&ens_name).await?,
NameOrAddress::Address(addr) => addr,
};
let from = utils::serialize(&from);
let locations = locations.iter().map(|location| utils::serialize(&location)).collect();
let block = utils::serialize(&block.unwrap_or_else(|| BlockNumber::Latest.into()));
self.request("eth_getProof", [from, locations, block]).await
}
/// Returns an indication if this node is currently mining.
async fn mining(&self) -> Result<bool, Self::Error> {
self.request("eth_mining", ()).await
}
async fn import_raw_key(
&self,
private_key: Bytes,
passphrase: String,
) -> Result<Address, ProviderError> {
// private key should not be prefixed with 0x - it is also up to the user to pass in a key
// of the correct length
// the private key argument is supposed to be a string
let private_key_hex = hex::encode(private_key);
let private_key = utils::serialize(&private_key_hex);
let passphrase = utils::serialize(&passphrase);
self.request("personal_importRawKey", [private_key, passphrase]).await
}
async fn unlock_account<T: Into<Address> + Send + Sync>(
&self,
account: T,
passphrase: String,
duration: Option<u64>,
) -> Result<bool, ProviderError> {
let account = utils::serialize(&account.into());
let duration = utils::serialize(&duration.unwrap_or(0));
let passphrase = utils::serialize(&passphrase);
self.request("personal_unlockAccount", [account, passphrase, duration]).await
}
async fn add_peer(&self, enode_url: String) -> Result<bool, Self::Error> {
let enode_url = utils::serialize(&enode_url);
self.request("admin_addPeer", [enode_url]).await
}
async fn add_trusted_peer(&self, enode_url: String) -> Result<bool, Self::Error> {
let enode_url = utils::serialize(&enode_url);
self.request("admin_addTrustedPeer", [enode_url]).await
}
async fn node_info(&self) -> Result<NodeInfo, Self::Error> {
self.request("admin_nodeInfo", ()).await
}
async fn peers(&self) -> Result<Vec<PeerInfo>, Self::Error> {
self.request("admin_peers", ()).await
}
async fn remove_peer(&self, enode_url: String) -> Result<bool, Self::Error> {
let enode_url = utils::serialize(&enode_url);
self.request("admin_removePeer", [enode_url]).await
}
async fn remove_trusted_peer(&self, enode_url: String) -> Result<bool, Self::Error> {
let enode_url = utils::serialize(&enode_url);
self.request("admin_removeTrustedPeer", [enode_url]).await
}
async fn start_mining(&self) -> Result<(), Self::Error> {
self.request("miner_start", ()).await
}
async fn stop_mining(&self) -> Result<(), Self::Error> {
self.request("miner_stop", ()).await
}
async fn resolve_name(&self, ens_name: &str) -> Result<Address, ProviderError> {
self.query_resolver(ParamType::Address, ens_name, ens::ADDR_SELECTOR).await
}
async fn lookup_address(&self, address: Address) -> Result<String, ProviderError> {
let ens_name = ens::reverse_address(address);
let domain: String =
self.query_resolver(ParamType::String, &ens_name, ens::NAME_SELECTOR).await?;
let reverse_address = self.resolve_name(&domain).await?;
if address != reverse_address {
Err(ProviderError::EnsNotOwned(domain))
} else {
Ok(domain)
}
}
async fn resolve_avatar(&self, ens_name: &str) -> Result<Url, ProviderError> {
let (field, owner) =
try_join!(self.resolve_field(ens_name, "avatar"), self.resolve_name(ens_name))?;
let url = Url::from_str(&field).map_err(|e| ProviderError::CustomError(e.to_string()))?;
match url.scheme() {
"https" | "data" => Ok(url),
"ipfs" => erc::http_link_ipfs(url).map_err(ProviderError::CustomError),
"eip155" => {
let token =
erc::ERCNFT::from_str(url.path()).map_err(ProviderError::CustomError)?;
match token.type_ {
erc::ERCNFTType::ERC721 => {
let tx = TransactionRequest {
data: Some(
[&erc::ERC721_OWNER_SELECTOR[..], &token.id].concat().into(),
),
to: Some(NameOrAddress::Address(token.contract)),
..Default::default()
};
let data = self.call(&tx.into(), None).await?;
if decode_bytes::<Address>(ParamType::Address, data) != owner {
return Err(ProviderError::CustomError("Incorrect owner.".to_string()))
}
}
erc::ERCNFTType::ERC1155 => {
let tx = TransactionRequest {
data: Some(
[
&erc::ERC1155_BALANCE_SELECTOR[..],
&[0x0; 12],
&owner.0,
&token.id,
]
.concat()
.into(),
),
to: Some(NameOrAddress::Address(token.contract)),
..Default::default()
};
let data = self.call(&tx.into(), None).await?;
if decode_bytes::<u64>(ParamType::Uint(64), data) == 0 {
return Err(ProviderError::CustomError("Incorrect balance.".to_string()))
}
}
}
let image_url = self.resolve_nft(token).await?;
match image_url.scheme() {
"https" | "data" => Ok(image_url),
"ipfs" => erc::http_link_ipfs(image_url).map_err(ProviderError::CustomError),
_ => Err(ProviderError::CustomError(
"Unsupported scheme for the image".to_string(),
)),
}
}
_ => Err(ProviderError::CustomError("Unsupported scheme".to_string())),
}
}
async fn resolve_nft(&self, token: erc::ERCNFT) -> Result<Url, ProviderError> {
let selector = token.type_.resolution_selector();
let tx = TransactionRequest {
data: Some([&selector[..], &token.id].concat().into()),
to: Some(NameOrAddress::Address(token.contract)),
..Default::default()
};
let data = self.call(&tx.into(), None).await?;
let mut metadata_url = Url::parse(&decode_bytes::<String>(ParamType::String, data))
.map_err(|e| ProviderError::CustomError(format!("Invalid metadata url: {e}")))?;
if token.type_ == erc::ERCNFTType::ERC1155 {
metadata_url.set_path(&metadata_url.path().replace("%7Bid%7D", &hex::encode(token.id)));
}
if metadata_url.scheme() == "ipfs" {
metadata_url = erc::http_link_ipfs(metadata_url).map_err(ProviderError::CustomError)?;
}
let metadata: erc::Metadata = reqwest::get(metadata_url).await?.json().await?;
Url::parse(&metadata.image).map_err(|e| ProviderError::CustomError(e.to_string()))
}
async fn resolve_field(&self, ens_name: &str, field: &str) -> Result<String, ProviderError> {
let field: String = self
.query_resolver_parameters(
ParamType::String,
ens_name,
ens::FIELD_SELECTOR,
Some(&ens::parameterhash(field)),
)
.await?;
Ok(field)
}
async fn txpool_content(&self) -> Result<TxpoolContent, ProviderError> {
self.request("txpool_content", ()).await
}
async fn txpool_inspect(&self) -> Result<TxpoolInspect, ProviderError> {
self.request("txpool_inspect", ()).await
}
async fn txpool_status(&self) -> Result<TxpoolStatus, ProviderError> {
self.request("txpool_status", ()).await
}
async fn debug_trace_transaction(
&self,
tx_hash: TxHash,
trace_options: GethDebugTracingOptions,
) -> Result<GethTrace, ProviderError> {
let tx_hash = utils::serialize(&tx_hash);
let trace_options = utils::serialize(&trace_options);
self.request("debug_traceTransaction", [tx_hash, trace_options]).await
}
async fn debug_trace_call<T: Into<TypedTransaction> + Send + Sync>(
&self,
req: T,
block: Option<BlockId>,
trace_options: GethDebugTracingCallOptions,
) -> Result<GethTrace, ProviderError> {
let req = req.into();
let req = utils::serialize(&req);
let block = utils::serialize(&block.unwrap_or_else(|| BlockNumber::Latest.into()));
let trace_options = utils::serialize(&trace_options);
self.request("debug_traceCall", [req, block, trace_options]).await
}
async fn debug_trace_block_by_number(
&self,
block: Option<BlockNumber>,
trace_options: GethDebugTracingOptions,
) -> Result<Vec<GethTrace>, ProviderError> {
let block = utils::serialize(&block.unwrap_or(BlockNumber::Latest));
let trace_options = utils::serialize(&trace_options);
self.request("debug_traceBlockByNumber", [block, trace_options]).await
}
async fn debug_trace_block_by_hash(
&self,
block: H256,
trace_options: GethDebugTracingOptions,
) -> Result<Vec<GethTrace>, ProviderError> {
let block = utils::serialize(&block);
let trace_options = utils::serialize(&trace_options);
self.request("debug_traceBlockByHash", [block, trace_options]).await
}
async fn trace_call<T: Into<TypedTransaction> + Send + Sync>(
&self,
req: T,
trace_type: Vec<TraceType>,
block: Option<BlockNumber>,
) -> Result<BlockTrace, ProviderError> {
let req = req.into();
let req = utils::serialize(&req);
let block = utils::serialize(&block.unwrap_or(BlockNumber::Latest));
let trace_type = utils::serialize(&trace_type);
self.request("trace_call", [req, trace_type, block]).await
}
async fn trace_call_many<T: Into<TypedTransaction> + Send + Sync>(
&self,
req: Vec<(T, Vec<TraceType>)>,
block: Option<BlockNumber>,
) -> Result<Vec<BlockTrace>, ProviderError> {
let req: Vec<(TypedTransaction, Vec<TraceType>)> =
req.into_iter().map(|(tx, trace_type)| (tx.into(), trace_type)).collect();
let req = utils::serialize(&req);
let block = utils::serialize(&block.unwrap_or(BlockNumber::Latest));
self.request("trace_callMany", [req, block]).await
}
async fn trace_raw_transaction(
&self,
data: Bytes,