-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
lib.rs
2346 lines (2186 loc) · 86.2 KB
/
lib.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
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
use alloy_consensus::TxEnvelope;
use alloy_dyn_abi::{DynSolType, DynSolValue, FunctionExt};
use alloy_json_abi::Function;
use alloy_network::AnyNetwork;
use alloy_primitives::{
hex,
utils::{keccak256, ParseUnits, Unit},
Address, Keccak256, TxHash, TxKind, B256, I256, U256,
};
use alloy_provider::{
network::eip2718::{Decodable2718, Encodable2718},
PendingTransactionBuilder, Provider,
};
use alloy_rlp::Decodable;
use alloy_rpc_types::{BlockId, BlockNumberOrTag, Filter, TransactionRequest};
use alloy_serde::WithOtherFields;
use alloy_sol_types::sol;
use alloy_transport::Transport;
use base::{Base, NumberWithBase, ToBase};
use chrono::DateTime;
use eyre::{Context, ContextCompat, Result};
use foundry_block_explorers::Client;
use foundry_common::{
abi::{encode_function_args, get_func},
compile::etherscan_project,
fmt::*,
fs, get_pretty_tx_receipt_attr, shell, TransactionReceiptWithRevertReason,
};
use foundry_compilers::flatten::Flattener;
use foundry_config::Chain;
use futures::{future::Either, FutureExt, StreamExt};
use rayon::prelude::*;
use revm::primitives::Eof;
use std::{
borrow::Cow,
fmt::Write,
io,
marker::PhantomData,
path::PathBuf,
str::FromStr,
sync::atomic::{AtomicBool, Ordering},
time::Duration,
};
use tokio::signal::ctrl_c;
use utils::decode_instructions;
use foundry_common::abi::encode_function_args_packed;
pub use foundry_evm::*;
pub mod base;
pub mod errors;
mod rlp_converter;
use rlp_converter::Item;
#[macro_use]
extern crate foundry_common;
// TODO: CastContract with common contract initializers? Same for CastProviders?
sol! {
#[sol(rpc)]
interface IERC20 {
#[derive(Debug)]
function balanceOf(address owner) external view returns (uint256);
}
}
pub struct Cast<P, T> {
provider: P,
transport: PhantomData<T>,
}
impl<T, P> Cast<P, T>
where
T: Transport + Clone,
P: Provider<T, AnyNetwork>,
{
/// Creates a new Cast instance from the provided client
///
/// # Example
///
/// ```
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// # Ok(())
/// # }
/// ```
pub fn new(provider: P) -> Self {
Self { provider, transport: PhantomData }
}
/// Makes a read-only call to the specified address
///
/// # Example
///
/// ```
/// use alloy_primitives::{Address, U256, Bytes};
/// use alloy_rpc_types::{TransactionRequest};
/// use alloy_serde::WithOtherFields;
/// use cast::Cast;
/// use alloy_provider::{RootProvider, ProviderBuilder, network::AnyNetwork};
/// use std::str::FromStr;
/// use alloy_sol_types::{sol, SolCall};
///
/// sol!(
/// function greeting(uint256 i) public returns (string);
/// );
///
/// # async fn foo() -> eyre::Result<()> {
/// let alloy_provider = ProviderBuilder::<_,_, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;;
/// let to = Address::from_str("0xB3C95ff08316fb2F2e3E52Ee82F8e7b605Aa1304")?;
/// let greeting = greetingCall { i: U256::from(5) }.abi_encode();
/// let bytes = Bytes::from_iter(greeting.iter());
/// let tx = TransactionRequest::default().to(to).input(bytes.into());
/// let tx = WithOtherFields::new(tx);
/// let cast = Cast::new(alloy_provider);
/// let data = cast.call(&tx, None, None).await?;
/// println!("{}", data);
/// # Ok(())
/// # }
/// ```
pub async fn call(
&self,
req: &WithOtherFields<TransactionRequest>,
func: Option<&Function>,
block: Option<BlockId>,
) -> Result<String> {
let res = self.provider.call(req).block(block.unwrap_or_default()).await?;
let mut decoded = vec![];
if let Some(func) = func {
// decode args into tokens
decoded = match func.abi_decode_output(res.as_ref(), false) {
Ok(decoded) => decoded,
Err(err) => {
// ensure the address is a contract
if res.is_empty() {
// check that the recipient is a contract that can be called
if let Some(TxKind::Call(addr)) = req.to {
if let Ok(code) = self
.provider
.get_code_at(addr)
.block_id(block.unwrap_or_default())
.await
{
if code.is_empty() {
eyre::bail!("contract {addr:?} does not have any code")
}
}
} else if Some(TxKind::Create) == req.to {
eyre::bail!("tx req is a contract deployment");
} else {
eyre::bail!("recipient is None");
}
}
return Err(err).wrap_err(
"could not decode output; did you specify the wrong function return data type?"
);
}
};
}
// handle case when return type is not specified
Ok(if decoded.is_empty() {
res.to_string()
} else if shell::is_json() {
let tokens = decoded.iter().map(format_token_raw).collect::<Vec<_>>();
serde_json::to_string_pretty(&tokens).unwrap()
} else {
// seth compatible user-friendly return type conversions
decoded.iter().map(format_token).collect::<Vec<_>>().join("\n")
})
}
/// Generates an access list for the specified transaction
///
/// # Example
///
/// ```
/// use cast::{Cast};
/// use alloy_primitives::{Address, U256, Bytes};
/// use alloy_rpc_types::{TransactionRequest};
/// use alloy_serde::WithOtherFields;
/// use alloy_provider::{RootProvider, ProviderBuilder, network::AnyNetwork};
/// use std::str::FromStr;
/// use alloy_sol_types::{sol, SolCall};
///
/// sol!(
/// function greeting(uint256 i) public returns (string);
/// );
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider = ProviderBuilder::<_,_, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;;
/// let to = Address::from_str("0xB3C95ff08316fb2F2e3E52Ee82F8e7b605Aa1304")?;
/// let greeting = greetingCall { i: U256::from(5) }.abi_encode();
/// let bytes = Bytes::from_iter(greeting.iter());
/// let tx = TransactionRequest::default().to(to).input(bytes.into());
/// let tx = WithOtherFields::new(tx);
/// let cast = Cast::new(&provider);
/// let access_list = cast.access_list(&tx, None).await?;
/// println!("{}", access_list);
/// # Ok(())
/// # }
/// ```
pub async fn access_list(
&self,
req: &WithOtherFields<TransactionRequest>,
block: Option<BlockId>,
) -> Result<String> {
let access_list =
self.provider.create_access_list(req).block_id(block.unwrap_or_default()).await?;
let res = if shell::is_json() {
serde_json::to_string(&access_list)?
} else {
let mut s =
vec![format!("gas used: {}", access_list.gas_used), "access list:".to_string()];
for al in access_list.access_list.0 {
s.push(format!("- address: {}", &al.address.to_checksum(None)));
if !al.storage_keys.is_empty() {
s.push(" keys:".to_string());
for key in al.storage_keys {
s.push(format!(" {key:?}"));
}
}
}
s.join("\n")
};
Ok(res)
}
pub async fn balance(&self, who: Address, block: Option<BlockId>) -> Result<U256> {
Ok(self.provider.get_balance(who).block_id(block.unwrap_or_default()).await?)
}
/// Sends a transaction to the specified address
///
/// # Example
///
/// ```
/// use cast::{Cast};
/// use alloy_primitives::{Address, U256, Bytes};
/// use alloy_serde::WithOtherFields;
/// use alloy_rpc_types::{TransactionRequest};
/// use alloy_provider::{RootProvider, ProviderBuilder, network::AnyNetwork};
/// use std::str::FromStr;
/// use alloy_sol_types::{sol, SolCall};
///
/// sol!(
/// function greet(string greeting) public;
/// );
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider = ProviderBuilder::<_,_, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;;
/// let from = Address::from_str("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")?;
/// let to = Address::from_str("0xB3C95ff08316fb2F2e3E52Ee82F8e7b605Aa1304")?;
/// let greeting = greetCall { greeting: "hello".to_string() }.abi_encode();
/// let bytes = Bytes::from_iter(greeting.iter());
/// let gas = U256::from_str("200000").unwrap();
/// let value = U256::from_str("1").unwrap();
/// let nonce = U256::from_str("1").unwrap();
/// let tx = TransactionRequest::default().to(to).input(bytes.into()).from(from);
/// let tx = WithOtherFields::new(tx);
/// let cast = Cast::new(provider);
/// let data = cast.send(tx).await?;
/// println!("{:#?}", data);
/// # Ok(())
/// # }
/// ```
pub async fn send(
&self,
tx: WithOtherFields<TransactionRequest>,
) -> Result<PendingTransactionBuilder<T, AnyNetwork>> {
let res = self.provider.send_transaction(tx).await?;
Ok(res)
}
/// Publishes a raw transaction to the network
///
/// # Example
///
/// ```
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let res = cast.publish("0x1234".to_string()).await?;
/// println!("{:?}", res);
/// # Ok(())
/// # }
/// ```
pub async fn publish(
&self,
mut raw_tx: String,
) -> Result<PendingTransactionBuilder<T, AnyNetwork>> {
raw_tx = match raw_tx.strip_prefix("0x") {
Some(s) => s.to_string(),
None => raw_tx,
};
let tx = hex::decode(raw_tx)?;
let res = self.provider.send_raw_transaction(&tx).await?;
Ok(res)
}
/// # Example
///
/// ```
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let block = cast.block(5, true, None).await?;
/// println!("{}", block);
/// # Ok(())
/// # }
/// ```
pub async fn block<B: Into<BlockId>>(
&self,
block: B,
full: bool,
field: Option<String>,
) -> Result<String> {
let block = block.into();
if let Some(ref field) = field {
if field == "transactions" && !full {
eyre::bail!("use --full to view transactions")
}
}
let block = self
.provider
.get_block(block, full.into())
.await?
.ok_or_else(|| eyre::eyre!("block {:?} not found", block))?;
let block = if let Some(ref field) = field {
get_pretty_block_attr(&block, field)
.unwrap_or_else(|| format!("{field} is not a valid block field"))
} else if shell::is_json() {
serde_json::to_value(&block).unwrap().to_string()
} else {
block.pretty()
};
Ok(block)
}
async fn block_field_as_num<B: Into<BlockId>>(&self, block: B, field: String) -> Result<U256> {
let block = block.into();
let block_field = Self::block(
self,
block,
false,
// Select only select field
Some(field),
)
.await?;
let ret = if block_field.starts_with("0x") {
U256::from_str_radix(strip_0x(&block_field), 16).expect("Unable to convert hex to U256")
} else {
U256::from_str_radix(&block_field, 10).expect("Unable to convert decimal to U256")
};
Ok(ret)
}
pub async fn base_fee<B: Into<BlockId>>(&self, block: B) -> Result<U256> {
Self::block_field_as_num(self, block, String::from("baseFeePerGas")).await
}
pub async fn age<B: Into<BlockId>>(&self, block: B) -> Result<String> {
let timestamp_str =
Self::block_field_as_num(self, block, String::from("timestamp")).await?.to_string();
let datetime = DateTime::from_timestamp(timestamp_str.parse::<i64>().unwrap(), 0).unwrap();
Ok(datetime.format("%a %b %e %H:%M:%S %Y").to_string())
}
pub async fn timestamp<B: Into<BlockId>>(&self, block: B) -> Result<U256> {
Self::block_field_as_num(self, block, "timestamp".to_string()).await
}
pub async fn chain(&self) -> Result<&str> {
let genesis_hash = Self::block(
self,
0,
false,
// Select only block hash
Some(String::from("hash")),
)
.await?;
Ok(match &genesis_hash[..] {
"0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" => {
match &(Self::block(self, 1920000, false, Some("hash".to_string())).await?)[..] {
"0x94365e3a8c0b35089c1d1195081fe7489b528a84b22199c916180db8b28ade7f" => {
"etclive"
}
_ => "ethlive",
}
}
"0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9" => "kovan",
"0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d" => "ropsten",
"0x7ca38a1916c42007829c55e69d3e9a73265554b586a499015373241b8a3fa48b" => {
"optimism-mainnet"
}
"0xc1fc15cd51159b1f1e5cbc4b82e85c1447ddfa33c52cf1d98d14fba0d6354be1" => {
"optimism-goerli"
}
"0x02adc9b449ff5f2467b8c674ece7ff9b21319d76c4ad62a67a70d552655927e5" => {
"optimism-kovan"
}
"0x521982bd54239dc71269eefb58601762cc15cfb2978e0becb46af7962ed6bfaa" => "fraxtal",
"0x910f5c4084b63fd860d0c2f9a04615115a5a991254700b39ba072290dbd77489" => {
"fraxtal-testnet"
}
"0x7ee576b35482195fc49205cec9af72ce14f003b9ae69f6ba0faef4514be8b442" => {
"arbitrum-mainnet"
}
"0x0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303" => "morden",
"0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177" => "rinkeby",
"0xbf7e331f7f7c1dd2e05159666b3bf8bc7a8a3a9eb1d518969eab529dd9b88c1a" => "goerli",
"0x14c2283285a88fe5fce9bf5c573ab03d6616695d717b12a127188bcacfc743c4" => "kotti",
"0xa9c28ce2141b56c474f1dc504bee9b01eb1bd7d1a507580d5519d4437a97de1b" => "polygon",
"0x7b66506a9ebdbf30d32b43c5f15a3b1216269a1ec3a75aa3182b86176a2b1ca7" => {
"polygon-mumbai"
}
"0x4f1dd23188aab3a76b463e4af801b52b1248ef073c648cbdc4c9333d3da79756" => "gnosis",
"0xada44fd8d2ecab8b08f256af07ad3e777f17fb434f8f8e678b312f576212ba9a" => "chiado",
"0x6d3c66c5357ec91d5c43af47e234a939b22557cbb552dc45bebbceeed90fbe34" => "bsctest",
"0x0d21840abff46b96c84b2ac9e10e4f5cdaeb5693cb665db62a2f3b02d2d57b5b" => "bsc",
"0x31ced5b9beb7f8782b014660da0cb18cc409f121f408186886e1ca3e8eeca96b" => {
match &(Self::block(self, 1, false, Some(String::from("hash"))).await?)[..] {
"0x738639479dc82d199365626f90caa82f7eafcfe9ed354b456fb3d294597ceb53" => {
"avalanche-fuji"
}
_ => "avalanche",
}
}
_ => "unknown",
})
}
pub async fn chain_id(&self) -> Result<u64> {
Ok(self.provider.get_chain_id().await?)
}
pub async fn block_number(&self) -> Result<u64> {
Ok(self.provider.get_block_number().await?)
}
pub async fn gas_price(&self) -> Result<u128> {
Ok(self.provider.get_gas_price().await?)
}
/// # Example
///
/// ```
/// use alloy_primitives::Address;
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
/// use std::str::FromStr;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let addr = Address::from_str("0x7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
/// let nonce = cast.nonce(addr, None).await?;
/// println!("{}", nonce);
/// # Ok(())
/// # }
/// ```
pub async fn nonce(&self, who: Address, block: Option<BlockId>) -> Result<u64> {
Ok(self.provider.get_transaction_count(who).block_id(block.unwrap_or_default()).await?)
}
/// #Example
///
/// ```
/// use alloy_primitives::{Address, FixedBytes};
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
/// use std::str::FromStr;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let addr = Address::from_str("0x7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
/// let slots = vec![FixedBytes::from_str("0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")?];
/// let codehash = cast.codehash(addr, slots, None).await?;
/// println!("{}", codehash);
/// # Ok(())
/// # }
pub async fn codehash(
&self,
who: Address,
slots: Vec<B256>,
block: Option<BlockId>,
) -> Result<String> {
Ok(self
.provider
.get_proof(who, slots)
.block_id(block.unwrap_or_default())
.await?
.code_hash
.to_string())
}
/// #Example
///
/// ```
/// use alloy_primitives::{Address, FixedBytes};
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
/// use std::str::FromStr;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let addr = Address::from_str("0x7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
/// let slots = vec![FixedBytes::from_str("0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")?];
/// let storage_root = cast.storage_root(addr, slots, None).await?;
/// println!("{}", storage_root);
/// # Ok(())
/// # }
pub async fn storage_root(
&self,
who: Address,
slots: Vec<B256>,
block: Option<BlockId>,
) -> Result<String> {
Ok(self
.provider
.get_proof(who, slots)
.block_id(block.unwrap_or_default())
.await?
.storage_hash
.to_string())
}
/// # Example
///
/// ```
/// use alloy_primitives::Address;
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
/// use std::str::FromStr;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let addr = Address::from_str("0x7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
/// let implementation = cast.implementation(addr, false, None).await?;
/// println!("{}", implementation);
/// # Ok(())
/// # }
/// ```
pub async fn implementation(
&self,
who: Address,
is_beacon: bool,
block: Option<BlockId>,
) -> Result<String> {
let slot = match is_beacon {
true => {
// Use the beacon slot : bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)
B256::from_str(
"0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50",
)?
}
false => {
// Use the implementation slot :
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
B256::from_str(
"0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc",
)?
}
};
let value = self
.provider
.get_storage_at(who, slot.into())
.block_id(block.unwrap_or_default())
.await?;
let addr = Address::from_word(value.into());
Ok(format!("{addr:?}"))
}
/// # Example
///
/// ```
/// use alloy_primitives::Address;
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
/// use std::str::FromStr;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let addr = Address::from_str("0x7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
/// let admin = cast.admin(addr, None).await?;
/// println!("{}", admin);
/// # Ok(())
/// # }
/// ```
pub async fn admin(&self, who: Address, block: Option<BlockId>) -> Result<String> {
let slot =
B256::from_str("0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103")?;
let value = self
.provider
.get_storage_at(who, slot.into())
.block_id(block.unwrap_or_default())
.await?;
let addr = Address::from_word(value.into());
Ok(format!("{addr:?}"))
}
/// # Example
///
/// ```
/// use alloy_primitives::{Address, U256};
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
/// use std::str::FromStr;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let addr = Address::from_str("7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
/// let computed_address = cast.compute_address(addr, None).await?;
/// println!("Computed address for address {addr}: {computed_address}");
/// # Ok(())
/// # }
/// ```
pub async fn compute_address(&self, address: Address, nonce: Option<u64>) -> Result<Address> {
let unpacked = if let Some(n) = nonce { n } else { self.nonce(address, None).await? };
Ok(address.create(unpacked))
}
/// # Example
///
/// ```
/// use alloy_primitives::Address;
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
/// use std::str::FromStr;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let addr = Address::from_str("0x00000000219ab540356cbb839cbe05303d7705fa")?;
/// let code = cast.code(addr, None, false).await?;
/// println!("{}", code);
/// # Ok(())
/// # }
/// ```
pub async fn code(
&self,
who: Address,
block: Option<BlockId>,
disassemble: bool,
) -> Result<String> {
if disassemble {
let code =
self.provider.get_code_at(who).block_id(block.unwrap_or_default()).await?.to_vec();
SimpleCast::disassemble(&code)
} else {
Ok(format!(
"{}",
self.provider.get_code_at(who).block_id(block.unwrap_or_default()).await?
))
}
}
/// Example
///
/// ```
/// use alloy_primitives::Address;
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
/// use std::str::FromStr;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let addr = Address::from_str("0x00000000219ab540356cbb839cbe05303d7705fa")?;
/// let codesize = cast.codesize(addr, None).await?;
/// println!("{}", codesize);
/// # Ok(())
/// # }
/// ```
pub async fn codesize(&self, who: Address, block: Option<BlockId>) -> Result<String> {
let code =
self.provider.get_code_at(who).block_id(block.unwrap_or_default()).await?.to_vec();
Ok(format!("{}", code.len()))
}
/// # Example
///
/// ```
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let tx_hash = "0xf8d1713ea15a81482958fb7ddf884baee8d3bcc478c5f2f604e008dc788ee4fc";
/// let tx = cast.transaction(tx_hash.to_string(), None, false).await?;
/// println!("{}", tx);
/// # Ok(())
/// # }
/// ```
pub async fn transaction(
&self,
tx_hash: String,
field: Option<String>,
raw: bool,
) -> Result<String> {
let tx_hash = TxHash::from_str(&tx_hash).wrap_err("invalid tx hash")?;
let tx = self
.provider
.get_transaction_by_hash(tx_hash)
.await?
.ok_or_else(|| eyre::eyre!("tx not found: {:?}", tx_hash))?;
Ok(if raw {
format!("0x{}", hex::encode(tx.inner.inner.encoded_2718()))
} else if let Some(field) = field {
get_pretty_tx_attr(&tx.inner, field.as_str())
.ok_or_else(|| eyre::eyre!("invalid tx field: {}", field.to_string()))?
} else if shell::is_json() {
// to_value first to sort json object keys
serde_json::to_value(&tx)?.to_string()
} else {
tx.pretty()
})
}
/// # Example
///
/// ```
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let tx_hash = "0xf8d1713ea15a81482958fb7ddf884baee8d3bcc478c5f2f604e008dc788ee4fc";
/// let receipt = cast.receipt(tx_hash.to_string(), None, 1, None, false).await?;
/// println!("{}", receipt);
/// # Ok(())
/// # }
/// ```
pub async fn receipt(
&self,
tx_hash: String,
field: Option<String>,
confs: u64,
timeout: Option<u64>,
cast_async: bool,
) -> Result<String> {
let tx_hash = TxHash::from_str(&tx_hash).wrap_err("invalid tx hash")?;
let mut receipt: TransactionReceiptWithRevertReason =
match self.provider.get_transaction_receipt(tx_hash).await? {
Some(r) => r,
None => {
// if the async flag is provided, immediately exit if no tx is found, otherwise
// try to poll for it
if cast_async {
eyre::bail!("tx not found: {:?}", tx_hash)
} else {
PendingTransactionBuilder::new(self.provider.root().clone(), tx_hash)
.with_required_confirmations(confs)
.with_timeout(timeout.map(Duration::from_secs))
.get_receipt()
.await?
}
}
}
.into();
// Allow to fail silently
let _ = receipt.update_revert_reason(&self.provider).await;
Ok(if let Some(ref field) = field {
get_pretty_tx_receipt_attr(&receipt, field)
.ok_or_else(|| eyre::eyre!("invalid receipt field: {}", field))?
} else if shell::is_json() {
// to_value first to sort json object keys
serde_json::to_value(&receipt)?.to_string()
} else {
receipt.pretty()
})
}
/// Perform a raw JSON-RPC request
///
/// # Example
///
/// ```
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let result = cast
/// .rpc("eth_getBalance", &["0xc94770007dda54cF92009BFF0dE90c06F603a09f", "latest"])
/// .await?;
/// println!("{}", result);
/// # Ok(())
/// # }
/// ```
pub async fn rpc<V>(&self, method: &str, params: V) -> Result<String>
where
V: alloy_json_rpc::RpcParam,
{
let res = self
.provider
.raw_request::<V, serde_json::Value>(Cow::Owned(method.to_string()), params)
.await?;
Ok(serde_json::to_string(&res)?)
}
/// Returns the slot
///
/// # Example
///
/// ```
/// use alloy_primitives::{Address, B256};
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use cast::Cast;
/// use std::str::FromStr;
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
/// let addr = Address::from_str("0x00000000006c3852cbEf3e08E8dF289169EdE581")?;
/// let slot = B256::ZERO;
/// let storage = cast.storage(addr, slot, None).await?;
/// println!("{}", storage);
/// # Ok(())
/// # }
/// ```
pub async fn storage(
&self,
from: Address,
slot: B256,
block: Option<BlockId>,
) -> Result<String> {
Ok(format!(
"{:?}",
B256::from(
self.provider
.get_storage_at(from, slot.into())
.block_id(block.unwrap_or_default())
.await?
)
))
}
pub async fn filter_logs(&self, filter: Filter) -> Result<String> {
let logs = self.provider.get_logs(&filter).await?;
let res = if shell::is_json() {
serde_json::to_string(&logs)?
} else {
let mut s = vec![];
for log in logs {
let pretty = log
.pretty()
.replacen('\n', "- ", 1) // Remove empty first line
.replace('\n', "\n "); // Indent
s.push(pretty);
}
s.join("\n")
};
Ok(res)
}
/// Converts a block identifier into a block number.
///
/// If the block identifier is a block number, then this function returns the block number. If
/// the block identifier is a block hash, then this function returns the block number of
/// that block hash. If the block identifier is `None`, then this function returns `None`.
///
/// # Example
///
/// ```
/// use alloy_primitives::fixed_bytes;
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use alloy_rpc_types::{BlockId, BlockNumberOrTag};
/// use cast::Cast;
/// use std::{convert::TryFrom, str::FromStr};
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("http://localhost:8545").await?;
/// let cast = Cast::new(provider);
///
/// let block_number = cast.convert_block_number(Some(BlockId::number(5))).await?;
/// assert_eq!(block_number, Some(BlockNumberOrTag::Number(5)));
///
/// let block_number = cast
/// .convert_block_number(Some(BlockId::hash(fixed_bytes!(
/// "0000000000000000000000000000000000000000000000000000000000001234"
/// ))))
/// .await?;
/// assert_eq!(block_number, Some(BlockNumberOrTag::Number(4660)));
///
/// let block_number = cast.convert_block_number(None).await?;
/// assert_eq!(block_number, None);
/// # Ok(())
/// # }
/// ```
pub async fn convert_block_number(
&self,
block: Option<BlockId>,
) -> Result<Option<BlockNumberOrTag>, eyre::Error> {
match block {
Some(block) => match block {
BlockId::Number(block_number) => Ok(Some(block_number)),
BlockId::Hash(hash) => {
let block =
self.provider.get_block_by_hash(hash.block_hash, false.into()).await?;
Ok(block.map(|block| block.header.number).map(BlockNumberOrTag::from))
}
},
None => Ok(None),
}
}
/// Sets up a subscription to the given filter and writes the logs to the given output.
///
/// # Example
///
/// ```
/// use alloy_primitives::Address;
/// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
/// use alloy_rpc_types::Filter;
/// use alloy_transport::BoxTransport;
/// use cast::Cast;
/// use std::{io, str::FromStr};
///
/// # async fn foo() -> eyre::Result<()> {
/// let provider =
/// ProviderBuilder::<_, _, AnyNetwork>::default().on_builtin("wss://localhost:8545").await?;
/// let cast = Cast::new(provider);
///
/// let filter =
/// Filter::new().address(Address::from_str("0x00000000006c3852cbEf3e08E8dF289169EdE581")?);
/// let mut output = io::stdout();
/// cast.subscribe(filter, &mut output).await?;
/// # Ok(())
/// # }
/// ```
pub async fn subscribe(&self, filter: Filter, output: &mut dyn io::Write) -> Result<()> {
// Initialize the subscription stream for logs
let mut subscription = self.provider.subscribe_logs(&filter).await?.into_stream();
// Check if a to_block is specified, if so, subscribe to blocks
let mut block_subscription = if filter.get_to_block().is_some() {
Some(self.provider.subscribe_blocks().await?.into_stream())
} else {
None
};
let format_json = shell::is_json();
let to_block_number = filter.get_to_block();