cast/lib.rs
1//! Cast is a Swiss Army knife for interacting with Ethereum applications from the command line.
2
3#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
4#![cfg_attr(not(test), warn(unused_crate_dependencies))]
5
6use alloy_consensus::{Header, TxEnvelope};
7use alloy_dyn_abi::{DynSolType, DynSolValue, FunctionExt};
8use alloy_ens::NameOrAddress;
9use alloy_json_abi::Function;
10use alloy_network::{AnyNetwork, AnyRpcTransaction};
11use alloy_primitives::{
12 Address, B256, I256, Keccak256, Selector, TxHash, TxKind, U64, U256, hex,
13 utils::{ParseUnits, Unit, keccak256},
14};
15use alloy_provider::{
16 PendingTransactionBuilder, Provider,
17 network::eip2718::{Decodable2718, Encodable2718},
18};
19use alloy_rlp::Decodable;
20use alloy_rpc_types::{
21 BlockId, BlockNumberOrTag, BlockOverrides, Filter, TransactionRequest, state::StateOverride,
22};
23use alloy_serde::WithOtherFields;
24use alloy_sol_types::sol;
25use base::{Base, NumberWithBase, ToBase};
26use chrono::DateTime;
27use eyre::{Context, ContextCompat, OptionExt, Result};
28use foundry_block_explorers::Client;
29use foundry_common::{
30 TransactionReceiptWithRevertReason,
31 abi::{encode_function_args, get_func},
32 compile::etherscan_project,
33 fmt::*,
34 fs, get_pretty_tx_receipt_attr, shell,
35};
36use foundry_compilers::flatten::Flattener;
37use foundry_config::Chain;
38use foundry_evm_core::ic::decode_instructions;
39use futures::{FutureExt, StreamExt, future::Either};
40use op_alloy_consensus::OpTxEnvelope;
41use rayon::prelude::*;
42use std::{
43 borrow::Cow,
44 fmt::Write,
45 io,
46 path::PathBuf,
47 str::FromStr,
48 sync::atomic::{AtomicBool, Ordering},
49 time::Duration,
50};
51use tokio::signal::ctrl_c;
52
53use foundry_common::abi::encode_function_args_packed;
54pub use foundry_evm::*;
55
56pub mod args;
57pub mod cmd;
58pub mod opts;
59
60pub mod base;
61pub mod errors;
62mod rlp_converter;
63pub mod tx;
64
65use rlp_converter::Item;
66
67#[macro_use]
68extern crate tracing;
69
70#[macro_use]
71extern crate foundry_common;
72
73// TODO: CastContract with common contract initializers? Same for CastProviders?
74
75sol! {
76 #[sol(rpc)]
77 interface IERC20 {
78 #[derive(Debug)]
79 function balanceOf(address owner) external view returns (uint256);
80 }
81}
82
83pub struct Cast<P> {
84 provider: P,
85}
86
87impl<P: Provider<AnyNetwork>> Cast<P> {
88 /// Creates a new Cast instance from the provided client
89 ///
90 /// # Example
91 ///
92 /// ```
93 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
94 /// use cast::Cast;
95 ///
96 /// # async fn foo() -> eyre::Result<()> {
97 /// let provider =
98 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
99 /// let cast = Cast::new(provider);
100 /// # Ok(())
101 /// # }
102 /// ```
103 pub fn new(provider: P) -> Self {
104 Self { provider }
105 }
106
107 /// Makes a read-only call to the specified address
108 ///
109 /// # Example
110 ///
111 /// ```
112 /// use alloy_primitives::{Address, U256, Bytes};
113 /// use alloy_rpc_types::{TransactionRequest, BlockOverrides, state::{StateOverride, AccountOverride}};
114 /// use alloy_serde::WithOtherFields;
115 /// use cast::Cast;
116 /// use alloy_provider::{RootProvider, ProviderBuilder, network::AnyNetwork};
117 /// use std::{str::FromStr, collections::HashMap};
118 /// use alloy_rpc_types::state::StateOverridesBuilder;
119 /// use alloy_sol_types::{sol, SolCall};
120 ///
121 /// sol!(
122 /// function greeting(uint256 i) public returns (string);
123 /// );
124 ///
125 /// # async fn foo() -> eyre::Result<()> {
126 /// let alloy_provider = ProviderBuilder::<_,_, AnyNetwork>::default().connect("http://localhost:8545").await?;;
127 /// let to = Address::from_str("0xB3C95ff08316fb2F2e3E52Ee82F8e7b605Aa1304")?;
128 /// let greeting = greetingCall { i: U256::from(5) }.abi_encode();
129 /// let bytes = Bytes::from_iter(greeting.iter());
130 /// let tx = TransactionRequest::default().to(to).input(bytes.into());
131 /// let tx = WithOtherFields::new(tx);
132 ///
133 /// // Create state overrides
134 /// let mut state_override = StateOverride::default();
135 /// let mut account_override = AccountOverride::default();
136 /// account_override.balance = Some(U256::from(1000));
137 /// state_override.insert(to, account_override);
138 /// let state_override_object = StateOverridesBuilder::default().build();
139 /// let block_override_object = BlockOverrides::default();
140 ///
141 /// let cast = Cast::new(alloy_provider);
142 /// let data = cast.call(&tx, None, None, Some(state_override_object), Some(block_override_object)).await?;
143 /// println!("{}", data);
144 /// # Ok(())
145 /// # }
146 /// ```
147 pub async fn call(
148 &self,
149 req: &WithOtherFields<TransactionRequest>,
150 func: Option<&Function>,
151 block: Option<BlockId>,
152 state_override: Option<StateOverride>,
153 block_override: Option<BlockOverrides>,
154 ) -> Result<String> {
155 let mut call = self
156 .provider
157 .call(req.clone())
158 .block(block.unwrap_or_default())
159 .with_block_overrides_opt(block_override);
160 if let Some(state_override) = state_override {
161 call = call.overrides(state_override)
162 }
163
164 let res = call.await?;
165 let mut decoded = vec![];
166
167 if let Some(func) = func {
168 // decode args into tokens
169 decoded = match func.abi_decode_output(res.as_ref()) {
170 Ok(decoded) => decoded,
171 Err(err) => {
172 // ensure the address is a contract
173 if res.is_empty() {
174 // check that the recipient is a contract that can be called
175 if let Some(TxKind::Call(addr)) = req.to {
176 if let Ok(code) = self
177 .provider
178 .get_code_at(addr)
179 .block_id(block.unwrap_or_default())
180 .await
181 && code.is_empty()
182 {
183 eyre::bail!("contract {addr:?} does not have any code")
184 }
185 } else if Some(TxKind::Create) == req.to {
186 eyre::bail!("tx req is a contract deployment");
187 } else {
188 eyre::bail!("recipient is None");
189 }
190 }
191 return Err(err).wrap_err(
192 "could not decode output; did you specify the wrong function return data type?"
193 );
194 }
195 };
196 }
197
198 // handle case when return type is not specified
199 Ok(if decoded.is_empty() {
200 res.to_string()
201 } else if shell::is_json() {
202 let tokens = decoded.iter().map(format_token_raw).collect::<Vec<_>>();
203 serde_json::to_string_pretty(&tokens).unwrap()
204 } else {
205 // seth compatible user-friendly return type conversions
206 decoded.iter().map(format_token).collect::<Vec<_>>().join("\n")
207 })
208 }
209
210 /// Generates an access list for the specified transaction
211 ///
212 /// # Example
213 ///
214 /// ```
215 /// use cast::{Cast};
216 /// use alloy_primitives::{Address, U256, Bytes};
217 /// use alloy_rpc_types::{TransactionRequest};
218 /// use alloy_serde::WithOtherFields;
219 /// use alloy_provider::{RootProvider, ProviderBuilder, network::AnyNetwork};
220 /// use std::str::FromStr;
221 /// use alloy_sol_types::{sol, SolCall};
222 ///
223 /// sol!(
224 /// function greeting(uint256 i) public returns (string);
225 /// );
226 ///
227 /// # async fn foo() -> eyre::Result<()> {
228 /// let provider = ProviderBuilder::<_,_, AnyNetwork>::default().connect("http://localhost:8545").await?;;
229 /// let to = Address::from_str("0xB3C95ff08316fb2F2e3E52Ee82F8e7b605Aa1304")?;
230 /// let greeting = greetingCall { i: U256::from(5) }.abi_encode();
231 /// let bytes = Bytes::from_iter(greeting.iter());
232 /// let tx = TransactionRequest::default().to(to).input(bytes.into());
233 /// let tx = WithOtherFields::new(tx);
234 /// let cast = Cast::new(&provider);
235 /// let access_list = cast.access_list(&tx, None).await?;
236 /// println!("{}", access_list);
237 /// # Ok(())
238 /// # }
239 /// ```
240 pub async fn access_list(
241 &self,
242 req: &WithOtherFields<TransactionRequest>,
243 block: Option<BlockId>,
244 ) -> Result<String> {
245 let access_list =
246 self.provider.create_access_list(req).block_id(block.unwrap_or_default()).await?;
247 let res = if shell::is_json() {
248 serde_json::to_string(&access_list)?
249 } else {
250 let mut s =
251 vec![format!("gas used: {}", access_list.gas_used), "access list:".to_string()];
252 for al in access_list.access_list.0 {
253 s.push(format!("- address: {}", &al.address.to_checksum(None)));
254 if !al.storage_keys.is_empty() {
255 s.push(" keys:".to_string());
256 for key in al.storage_keys {
257 s.push(format!(" {key:?}"));
258 }
259 }
260 }
261 s.join("\n")
262 };
263
264 Ok(res)
265 }
266
267 pub async fn balance(&self, who: Address, block: Option<BlockId>) -> Result<U256> {
268 Ok(self.provider.get_balance(who).block_id(block.unwrap_or_default()).await?)
269 }
270
271 /// Sends a transaction to the specified address
272 ///
273 /// # Example
274 ///
275 /// ```
276 /// use cast::{Cast};
277 /// use alloy_primitives::{Address, U256, Bytes};
278 /// use alloy_serde::WithOtherFields;
279 /// use alloy_rpc_types::{TransactionRequest};
280 /// use alloy_provider::{RootProvider, ProviderBuilder, network::AnyNetwork};
281 /// use std::str::FromStr;
282 /// use alloy_sol_types::{sol, SolCall};
283 ///
284 /// sol!(
285 /// function greet(string greeting) public;
286 /// );
287 ///
288 /// # async fn foo() -> eyre::Result<()> {
289 /// let provider = ProviderBuilder::<_,_, AnyNetwork>::default().connect("http://localhost:8545").await?;;
290 /// let from = Address::from_str("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045")?;
291 /// let to = Address::from_str("0xB3C95ff08316fb2F2e3E52Ee82F8e7b605Aa1304")?;
292 /// let greeting = greetCall { greeting: "hello".to_string() }.abi_encode();
293 /// let bytes = Bytes::from_iter(greeting.iter());
294 /// let gas = U256::from_str("200000").unwrap();
295 /// let value = U256::from_str("1").unwrap();
296 /// let nonce = U256::from_str("1").unwrap();
297 /// let tx = TransactionRequest::default().to(to).input(bytes.into()).from(from);
298 /// let tx = WithOtherFields::new(tx);
299 /// let cast = Cast::new(provider);
300 /// let data = cast.send(tx).await?;
301 /// println!("{:#?}", data);
302 /// # Ok(())
303 /// # }
304 /// ```
305 pub async fn send(
306 &self,
307 tx: WithOtherFields<TransactionRequest>,
308 ) -> Result<PendingTransactionBuilder<AnyNetwork>> {
309 let res = self.provider.send_transaction(tx).await?;
310
311 Ok(res)
312 }
313
314 /// Publishes a raw transaction to the network
315 ///
316 /// # Example
317 ///
318 /// ```
319 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
320 /// use cast::Cast;
321 ///
322 /// # async fn foo() -> eyre::Result<()> {
323 /// let provider =
324 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
325 /// let cast = Cast::new(provider);
326 /// let res = cast.publish("0x1234".to_string()).await?;
327 /// println!("{:?}", res);
328 /// # Ok(())
329 /// # }
330 /// ```
331 pub async fn publish(
332 &self,
333 mut raw_tx: String,
334 ) -> Result<PendingTransactionBuilder<AnyNetwork>> {
335 raw_tx = match raw_tx.strip_prefix("0x") {
336 Some(s) => s.to_string(),
337 None => raw_tx,
338 };
339 let tx = hex::decode(raw_tx)?;
340 let res = self.provider.send_raw_transaction(&tx).await?;
341
342 Ok(res)
343 }
344
345 /// # Example
346 ///
347 /// ```
348 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
349 /// use cast::Cast;
350 ///
351 /// # async fn foo() -> eyre::Result<()> {
352 /// let provider =
353 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
354 /// let cast = Cast::new(provider);
355 /// let block = cast.block(5, true, None, false).await?;
356 /// println!("{}", block);
357 /// # Ok(())
358 /// # }
359 /// ```
360 pub async fn block<B: Into<BlockId>>(
361 &self,
362 block: B,
363 full: bool,
364 field: Option<String>,
365 raw: bool,
366 ) -> Result<String> {
367 let block = block.into();
368 if let Some(ref field) = field
369 && field == "transactions"
370 && !full
371 {
372 eyre::bail!("use --full to view transactions")
373 }
374
375 let block = self
376 .provider
377 .get_block(block)
378 .kind(full.into())
379 .await?
380 .ok_or_else(|| eyre::eyre!("block {:?} not found", block))?;
381
382 Ok(if raw {
383 let header: Header = block.into_inner().header.inner.try_into_header()?;
384 format!("0x{}", hex::encode(alloy_rlp::encode(&header)))
385 } else if let Some(ref field) = field {
386 get_pretty_block_attr(&block, field)
387 .unwrap_or_else(|| format!("{field} is not a valid block field"))
388 } else if shell::is_json() {
389 serde_json::to_value(&block).unwrap().to_string()
390 } else {
391 block.pretty()
392 })
393 }
394
395 async fn block_field_as_num<B: Into<BlockId>>(&self, block: B, field: String) -> Result<U256> {
396 Self::block(
397 self,
398 block.into(),
399 false,
400 // Select only select field
401 Some(field),
402 false,
403 )
404 .await?
405 .parse()
406 .map_err(Into::into)
407 }
408
409 pub async fn base_fee<B: Into<BlockId>>(&self, block: B) -> Result<U256> {
410 Self::block_field_as_num(self, block, String::from("baseFeePerGas")).await
411 }
412
413 pub async fn age<B: Into<BlockId>>(&self, block: B) -> Result<String> {
414 let timestamp_str =
415 Self::block_field_as_num(self, block, String::from("timestamp")).await?.to_string();
416 let datetime = DateTime::from_timestamp(timestamp_str.parse::<i64>().unwrap(), 0).unwrap();
417 Ok(datetime.format("%a %b %e %H:%M:%S %Y").to_string())
418 }
419
420 pub async fn timestamp<B: Into<BlockId>>(&self, block: B) -> Result<U256> {
421 Self::block_field_as_num(self, block, "timestamp".to_string()).await
422 }
423
424 pub async fn chain(&self) -> Result<&str> {
425 let genesis_hash = Self::block(
426 self,
427 0,
428 false,
429 // Select only block hash
430 Some(String::from("hash")),
431 false,
432 )
433 .await?;
434
435 Ok(match &genesis_hash[..] {
436 "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" => {
437 match &(Self::block(self, 1920000, false, Some("hash".to_string()), false).await?)[..]
438 {
439 "0x94365e3a8c0b35089c1d1195081fe7489b528a84b22199c916180db8b28ade7f" => {
440 "etclive"
441 }
442 _ => "ethlive",
443 }
444 }
445 "0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9" => "kovan",
446 "0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d" => "ropsten",
447 "0x7ca38a1916c42007829c55e69d3e9a73265554b586a499015373241b8a3fa48b" => {
448 "optimism-mainnet"
449 }
450 "0xc1fc15cd51159b1f1e5cbc4b82e85c1447ddfa33c52cf1d98d14fba0d6354be1" => {
451 "optimism-goerli"
452 }
453 "0x02adc9b449ff5f2467b8c674ece7ff9b21319d76c4ad62a67a70d552655927e5" => {
454 "optimism-kovan"
455 }
456 "0x521982bd54239dc71269eefb58601762cc15cfb2978e0becb46af7962ed6bfaa" => "fraxtal",
457 "0x910f5c4084b63fd860d0c2f9a04615115a5a991254700b39ba072290dbd77489" => {
458 "fraxtal-testnet"
459 }
460 "0x7ee576b35482195fc49205cec9af72ce14f003b9ae69f6ba0faef4514be8b442" => {
461 "arbitrum-mainnet"
462 }
463 "0x0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303" => "morden",
464 "0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177" => "rinkeby",
465 "0xbf7e331f7f7c1dd2e05159666b3bf8bc7a8a3a9eb1d518969eab529dd9b88c1a" => "goerli",
466 "0x14c2283285a88fe5fce9bf5c573ab03d6616695d717b12a127188bcacfc743c4" => "kotti",
467 "0xa9c28ce2141b56c474f1dc504bee9b01eb1bd7d1a507580d5519d4437a97de1b" => "polygon-pos",
468 "0x7202b2b53c5a0836e773e319d18922cc756dd67432f9a1f65352b61f4406c697" => {
469 "polygon-pos-amoy-testnet"
470 }
471 "0x81005434635456a16f74ff7023fbe0bf423abbc8a8deb093ffff455c0ad3b741" => "polygon-zkevm",
472 "0x676c1a76a6c5855a32bdf7c61977a0d1510088a4eeac1330466453b3d08b60b9" => {
473 "polygon-zkevm-cardona-testnet"
474 }
475 "0x4f1dd23188aab3a76b463e4af801b52b1248ef073c648cbdc4c9333d3da79756" => "gnosis",
476 "0xada44fd8d2ecab8b08f256af07ad3e777f17fb434f8f8e678b312f576212ba9a" => "chiado",
477 "0x6d3c66c5357ec91d5c43af47e234a939b22557cbb552dc45bebbceeed90fbe34" => "bsctest",
478 "0x0d21840abff46b96c84b2ac9e10e4f5cdaeb5693cb665db62a2f3b02d2d57b5b" => "bsc",
479 "0x31ced5b9beb7f8782b014660da0cb18cc409f121f408186886e1ca3e8eeca96b" => {
480 match &(Self::block(self, 1, false, Some(String::from("hash")), false).await?)[..] {
481 "0x738639479dc82d199365626f90caa82f7eafcfe9ed354b456fb3d294597ceb53" => {
482 "avalanche-fuji"
483 }
484 _ => "avalanche",
485 }
486 }
487 "0x23a2658170ba70d014ba0d0d2709f8fbfe2fa660cd868c5f282f991eecbe38ee" => "ink",
488 "0xe5fd5cf0be56af58ad5751b401410d6b7a09d830fa459789746a3d0dd1c79834" => "ink-sepolia",
489 _ => "unknown",
490 })
491 }
492
493 pub async fn chain_id(&self) -> Result<u64> {
494 Ok(self.provider.get_chain_id().await?)
495 }
496
497 pub async fn block_number(&self) -> Result<u64> {
498 Ok(self.provider.get_block_number().await?)
499 }
500
501 pub async fn gas_price(&self) -> Result<u128> {
502 Ok(self.provider.get_gas_price().await?)
503 }
504
505 /// # Example
506 ///
507 /// ```
508 /// use alloy_primitives::Address;
509 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
510 /// use cast::Cast;
511 /// use std::str::FromStr;
512 ///
513 /// # async fn foo() -> eyre::Result<()> {
514 /// let provider =
515 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
516 /// let cast = Cast::new(provider);
517 /// let addr = Address::from_str("0x7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
518 /// let nonce = cast.nonce(addr, None).await?;
519 /// println!("{}", nonce);
520 /// # Ok(())
521 /// # }
522 /// ```
523 pub async fn nonce(&self, who: Address, block: Option<BlockId>) -> Result<u64> {
524 Ok(self.provider.get_transaction_count(who).block_id(block.unwrap_or_default()).await?)
525 }
526
527 /// #Example
528 ///
529 /// ```
530 /// use alloy_primitives::{Address, FixedBytes};
531 /// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
532 /// use cast::Cast;
533 /// use std::str::FromStr;
534 ///
535 /// # async fn foo() -> eyre::Result<()> {
536 /// let provider =
537 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
538 /// let cast = Cast::new(provider);
539 /// let addr = Address::from_str("0x7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
540 /// let slots = vec![FixedBytes::from_str("0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")?];
541 /// let codehash = cast.codehash(addr, slots, None).await?;
542 /// println!("{}", codehash);
543 /// # Ok(())
544 /// # }
545 pub async fn codehash(
546 &self,
547 who: Address,
548 slots: Vec<B256>,
549 block: Option<BlockId>,
550 ) -> Result<String> {
551 Ok(self
552 .provider
553 .get_proof(who, slots)
554 .block_id(block.unwrap_or_default())
555 .await?
556 .code_hash
557 .to_string())
558 }
559
560 /// #Example
561 ///
562 /// ```
563 /// use alloy_primitives::{Address, FixedBytes};
564 /// use alloy_provider::{network::AnyNetwork, ProviderBuilder, RootProvider};
565 /// use cast::Cast;
566 /// use std::str::FromStr;
567 ///
568 /// # async fn foo() -> eyre::Result<()> {
569 /// let provider =
570 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
571 /// let cast = Cast::new(provider);
572 /// let addr = Address::from_str("0x7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
573 /// let slots = vec![FixedBytes::from_str("0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")?];
574 /// let storage_root = cast.storage_root(addr, slots, None).await?;
575 /// println!("{}", storage_root);
576 /// # Ok(())
577 /// # }
578 pub async fn storage_root(
579 &self,
580 who: Address,
581 slots: Vec<B256>,
582 block: Option<BlockId>,
583 ) -> Result<String> {
584 Ok(self
585 .provider
586 .get_proof(who, slots)
587 .block_id(block.unwrap_or_default())
588 .await?
589 .storage_hash
590 .to_string())
591 }
592
593 /// # Example
594 ///
595 /// ```
596 /// use alloy_primitives::Address;
597 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
598 /// use cast::Cast;
599 /// use std::str::FromStr;
600 ///
601 /// # async fn foo() -> eyre::Result<()> {
602 /// let provider =
603 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
604 /// let cast = Cast::new(provider);
605 /// let addr = Address::from_str("0x7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
606 /// let implementation = cast.implementation(addr, false, None).await?;
607 /// println!("{}", implementation);
608 /// # Ok(())
609 /// # }
610 /// ```
611 pub async fn implementation(
612 &self,
613 who: Address,
614 is_beacon: bool,
615 block: Option<BlockId>,
616 ) -> Result<String> {
617 let slot = match is_beacon {
618 true => {
619 // Use the beacon slot : bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)
620 B256::from_str(
621 "0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50",
622 )?
623 }
624 false => {
625 // Use the implementation slot :
626 // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
627 B256::from_str(
628 "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc",
629 )?
630 }
631 };
632
633 let value = self
634 .provider
635 .get_storage_at(who, slot.into())
636 .block_id(block.unwrap_or_default())
637 .await?;
638 let addr = Address::from_word(value.into());
639 Ok(format!("{addr:?}"))
640 }
641
642 /// # Example
643 ///
644 /// ```
645 /// use alloy_primitives::Address;
646 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
647 /// use cast::Cast;
648 /// use std::str::FromStr;
649 ///
650 /// # async fn foo() -> eyre::Result<()> {
651 /// let provider =
652 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
653 /// let cast = Cast::new(provider);
654 /// let addr = Address::from_str("0x7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
655 /// let admin = cast.admin(addr, None).await?;
656 /// println!("{}", admin);
657 /// # Ok(())
658 /// # }
659 /// ```
660 pub async fn admin(&self, who: Address, block: Option<BlockId>) -> Result<String> {
661 let slot =
662 B256::from_str("0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103")?;
663 let value = self
664 .provider
665 .get_storage_at(who, slot.into())
666 .block_id(block.unwrap_or_default())
667 .await?;
668 let addr = Address::from_word(value.into());
669 Ok(format!("{addr:?}"))
670 }
671
672 /// # Example
673 ///
674 /// ```
675 /// use alloy_primitives::{Address, U256};
676 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
677 /// use cast::Cast;
678 /// use std::str::FromStr;
679 ///
680 /// # async fn foo() -> eyre::Result<()> {
681 /// let provider =
682 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
683 /// let cast = Cast::new(provider);
684 /// let addr = Address::from_str("7eD52863829AB99354F3a0503A622e82AcD5F7d3")?;
685 /// let computed_address = cast.compute_address(addr, None).await?;
686 /// println!("Computed address for address {addr}: {computed_address}");
687 /// # Ok(())
688 /// # }
689 /// ```
690 pub async fn compute_address(&self, address: Address, nonce: Option<u64>) -> Result<Address> {
691 let unpacked = if let Some(n) = nonce { n } else { self.nonce(address, None).await? };
692 Ok(address.create(unpacked))
693 }
694
695 /// # Example
696 ///
697 /// ```
698 /// use alloy_primitives::Address;
699 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
700 /// use cast::Cast;
701 /// use std::str::FromStr;
702 ///
703 /// # async fn foo() -> eyre::Result<()> {
704 /// let provider =
705 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
706 /// let cast = Cast::new(provider);
707 /// let addr = Address::from_str("0x00000000219ab540356cbb839cbe05303d7705fa")?;
708 /// let code = cast.code(addr, None, false).await?;
709 /// println!("{}", code);
710 /// # Ok(())
711 /// # }
712 /// ```
713 pub async fn code(
714 &self,
715 who: Address,
716 block: Option<BlockId>,
717 disassemble: bool,
718 ) -> Result<String> {
719 if disassemble {
720 let code =
721 self.provider.get_code_at(who).block_id(block.unwrap_or_default()).await?.to_vec();
722 SimpleCast::disassemble(&code)
723 } else {
724 Ok(format!(
725 "{}",
726 self.provider.get_code_at(who).block_id(block.unwrap_or_default()).await?
727 ))
728 }
729 }
730
731 /// Example
732 ///
733 /// ```
734 /// use alloy_primitives::Address;
735 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
736 /// use cast::Cast;
737 /// use std::str::FromStr;
738 ///
739 /// # async fn foo() -> eyre::Result<()> {
740 /// let provider =
741 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
742 /// let cast = Cast::new(provider);
743 /// let addr = Address::from_str("0x00000000219ab540356cbb839cbe05303d7705fa")?;
744 /// let codesize = cast.codesize(addr, None).await?;
745 /// println!("{}", codesize);
746 /// # Ok(())
747 /// # }
748 /// ```
749 pub async fn codesize(&self, who: Address, block: Option<BlockId>) -> Result<String> {
750 let code =
751 self.provider.get_code_at(who).block_id(block.unwrap_or_default()).await?.to_vec();
752 Ok(format!("{}", code.len()))
753 }
754
755 /// # Example
756 ///
757 /// ```
758 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
759 /// use cast::Cast;
760 ///
761 /// # async fn foo() -> eyre::Result<()> {
762 /// let provider =
763 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
764 /// let cast = Cast::new(provider);
765 /// let tx_hash = "0xf8d1713ea15a81482958fb7ddf884baee8d3bcc478c5f2f604e008dc788ee4fc";
766 /// let tx = cast.transaction(Some(tx_hash.to_string()), None, None, None, false).await?;
767 /// println!("{}", tx);
768 /// # Ok(())
769 /// # }
770 /// ```
771 pub async fn transaction(
772 &self,
773 tx_hash: Option<String>,
774 from: Option<NameOrAddress>,
775 nonce: Option<u64>,
776 field: Option<String>,
777 raw: bool,
778 ) -> Result<String> {
779 let tx = if let Some(tx_hash) = tx_hash {
780 let tx_hash = TxHash::from_str(&tx_hash).wrap_err("invalid tx hash")?;
781 self.provider
782 .get_transaction_by_hash(tx_hash)
783 .await?
784 .ok_or_else(|| eyre::eyre!("tx not found: {:?}", tx_hash))?
785 } else if let Some(from) = from {
786 // If nonce is not provided, uses 0.
787 let nonce = U64::from(nonce.unwrap_or_default());
788 let from = from.resolve(self.provider.root()).await?;
789
790 self.provider
791 .raw_request::<_, Option<AnyRpcTransaction>>(
792 "eth_getTransactionBySenderAndNonce".into(),
793 (from, nonce),
794 )
795 .await?
796 .ok_or_else(|| {
797 eyre::eyre!("tx not found for sender {from} and nonce {:?}", nonce.to::<u64>())
798 })?
799 } else {
800 eyre::bail!("tx hash or from address is required")
801 };
802
803 Ok(if raw {
804 // also consider opstack deposit transactions
805 let either_tx = tx.try_into_either::<OpTxEnvelope>()?;
806 let encoded = either_tx.encoded_2718();
807 format!("0x{}", hex::encode(encoded))
808 } else if let Some(field) = field {
809 get_pretty_tx_attr(&tx.inner, field.as_str())
810 .ok_or_else(|| eyre::eyre!("invalid tx field: {}", field.to_string()))?
811 } else if shell::is_json() {
812 // to_value first to sort json object keys
813 serde_json::to_value(&tx)?.to_string()
814 } else {
815 tx.pretty()
816 })
817 }
818
819 /// # Example
820 ///
821 /// ```
822 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
823 /// use cast::Cast;
824 ///
825 /// # async fn foo() -> eyre::Result<()> {
826 /// let provider =
827 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
828 /// let cast = Cast::new(provider);
829 /// let tx_hash = "0xf8d1713ea15a81482958fb7ddf884baee8d3bcc478c5f2f604e008dc788ee4fc";
830 /// let receipt = cast.receipt(tx_hash.to_string(), None, 1, None, false).await?;
831 /// println!("{}", receipt);
832 /// # Ok(())
833 /// # }
834 /// ```
835 pub async fn receipt(
836 &self,
837 tx_hash: String,
838 field: Option<String>,
839 confs: u64,
840 timeout: Option<u64>,
841 cast_async: bool,
842 ) -> Result<String> {
843 let tx_hash = TxHash::from_str(&tx_hash).wrap_err("invalid tx hash")?;
844
845 let mut receipt: TransactionReceiptWithRevertReason =
846 match self.provider.get_transaction_receipt(tx_hash).await? {
847 Some(r) => r,
848 None => {
849 // if the async flag is provided, immediately exit if no tx is found, otherwise
850 // try to poll for it
851 if cast_async {
852 eyre::bail!("tx not found: {:?}", tx_hash)
853 } else {
854 PendingTransactionBuilder::new(self.provider.root().clone(), tx_hash)
855 .with_required_confirmations(confs)
856 .with_timeout(timeout.map(Duration::from_secs))
857 .get_receipt()
858 .await?
859 }
860 }
861 }
862 .into();
863
864 // Allow to fail silently
865 let _ = receipt.update_revert_reason(&self.provider).await;
866
867 Ok(if let Some(ref field) = field {
868 get_pretty_tx_receipt_attr(&receipt, field)
869 .ok_or_else(|| eyre::eyre!("invalid receipt field: {}", field))?
870 } else if shell::is_json() {
871 // to_value first to sort json object keys
872 serde_json::to_value(&receipt)?.to_string()
873 } else {
874 receipt.pretty()
875 })
876 }
877
878 /// Perform a raw JSON-RPC request
879 ///
880 /// # Example
881 ///
882 /// ```
883 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
884 /// use cast::Cast;
885 ///
886 /// # async fn foo() -> eyre::Result<()> {
887 /// let provider =
888 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
889 /// let cast = Cast::new(provider);
890 /// let result = cast
891 /// .rpc("eth_getBalance", &["0xc94770007dda54cF92009BFF0dE90c06F603a09f", "latest"])
892 /// .await?;
893 /// println!("{}", result);
894 /// # Ok(())
895 /// # }
896 /// ```
897 pub async fn rpc<V>(&self, method: &str, params: V) -> Result<String>
898 where
899 V: alloy_json_rpc::RpcSend,
900 {
901 let res = self
902 .provider
903 .raw_request::<V, serde_json::Value>(Cow::Owned(method.to_string()), params)
904 .await?;
905 Ok(serde_json::to_string(&res)?)
906 }
907
908 /// Returns the slot
909 ///
910 /// # Example
911 ///
912 /// ```
913 /// use alloy_primitives::{Address, B256};
914 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
915 /// use cast::Cast;
916 /// use std::str::FromStr;
917 ///
918 /// # async fn foo() -> eyre::Result<()> {
919 /// let provider =
920 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
921 /// let cast = Cast::new(provider);
922 /// let addr = Address::from_str("0x00000000006c3852cbEf3e08E8dF289169EdE581")?;
923 /// let slot = B256::ZERO;
924 /// let storage = cast.storage(addr, slot, None).await?;
925 /// println!("{}", storage);
926 /// # Ok(())
927 /// # }
928 /// ```
929 pub async fn storage(
930 &self,
931 from: Address,
932 slot: B256,
933 block: Option<BlockId>,
934 ) -> Result<String> {
935 Ok(format!(
936 "{:?}",
937 B256::from(
938 self.provider
939 .get_storage_at(from, slot.into())
940 .block_id(block.unwrap_or_default())
941 .await?
942 )
943 ))
944 }
945
946 pub async fn filter_logs(&self, filter: Filter) -> Result<String> {
947 let logs = self.provider.get_logs(&filter).await?;
948
949 let res = if shell::is_json() {
950 serde_json::to_string(&logs)?
951 } else {
952 let mut s = vec![];
953 for log in logs {
954 let pretty = log
955 .pretty()
956 .replacen('\n', "- ", 1) // Remove empty first line
957 .replace('\n', "\n "); // Indent
958 s.push(pretty);
959 }
960 s.join("\n")
961 };
962 Ok(res)
963 }
964
965 /// Converts a block identifier into a block number.
966 ///
967 /// If the block identifier is a block number, then this function returns the block number. If
968 /// the block identifier is a block hash, then this function returns the block number of
969 /// that block hash. If the block identifier is `None`, then this function returns `None`.
970 ///
971 /// # Example
972 ///
973 /// ```
974 /// use alloy_primitives::fixed_bytes;
975 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
976 /// use alloy_rpc_types::{BlockId, BlockNumberOrTag};
977 /// use cast::Cast;
978 /// use std::{convert::TryFrom, str::FromStr};
979 ///
980 /// # async fn foo() -> eyre::Result<()> {
981 /// let provider =
982 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("http://localhost:8545").await?;
983 /// let cast = Cast::new(provider);
984 ///
985 /// let block_number = cast.convert_block_number(Some(BlockId::number(5))).await?;
986 /// assert_eq!(block_number, Some(BlockNumberOrTag::Number(5)));
987 ///
988 /// let block_number = cast
989 /// .convert_block_number(Some(BlockId::hash(fixed_bytes!(
990 /// "0000000000000000000000000000000000000000000000000000000000001234"
991 /// ))))
992 /// .await?;
993 /// assert_eq!(block_number, Some(BlockNumberOrTag::Number(4660)));
994 ///
995 /// let block_number = cast.convert_block_number(None).await?;
996 /// assert_eq!(block_number, None);
997 /// # Ok(())
998 /// # }
999 /// ```
1000 pub async fn convert_block_number(
1001 &self,
1002 block: Option<BlockId>,
1003 ) -> Result<Option<BlockNumberOrTag>, eyre::Error> {
1004 match block {
1005 Some(block) => match block {
1006 BlockId::Number(block_number) => Ok(Some(block_number)),
1007 BlockId::Hash(hash) => {
1008 let block = self.provider.get_block_by_hash(hash.block_hash).await?;
1009 Ok(block.map(|block| block.header.number).map(BlockNumberOrTag::from))
1010 }
1011 },
1012 None => Ok(None),
1013 }
1014 }
1015
1016 /// Sets up a subscription to the given filter and writes the logs to the given output.
1017 ///
1018 /// # Example
1019 ///
1020 /// ```
1021 /// use alloy_primitives::Address;
1022 /// use alloy_provider::{ProviderBuilder, RootProvider, network::AnyNetwork};
1023 /// use alloy_rpc_types::Filter;
1024 /// use alloy_transport::BoxTransport;
1025 /// use cast::Cast;
1026 /// use std::{io, str::FromStr};
1027 ///
1028 /// # async fn foo() -> eyre::Result<()> {
1029 /// let provider =
1030 /// ProviderBuilder::<_, _, AnyNetwork>::default().connect("wss://localhost:8545").await?;
1031 /// let cast = Cast::new(provider);
1032 ///
1033 /// let filter =
1034 /// Filter::new().address(Address::from_str("0x00000000006c3852cbEf3e08E8dF289169EdE581")?);
1035 /// let mut output = io::stdout();
1036 /// cast.subscribe(filter, &mut output).await?;
1037 /// # Ok(())
1038 /// # }
1039 /// ```
1040 pub async fn subscribe(&self, filter: Filter, output: &mut dyn io::Write) -> Result<()> {
1041 // Initialize the subscription stream for logs
1042 let mut subscription = self.provider.subscribe_logs(&filter).await?.into_stream();
1043
1044 // Check if a to_block is specified, if so, subscribe to blocks
1045 let mut block_subscription = if filter.get_to_block().is_some() {
1046 Some(self.provider.subscribe_blocks().await?.into_stream())
1047 } else {
1048 None
1049 };
1050
1051 let format_json = shell::is_json();
1052 let to_block_number = filter.get_to_block();
1053
1054 // If output should be JSON, start with an opening bracket
1055 if format_json {
1056 write!(output, "[")?;
1057 }
1058
1059 let mut first = true;
1060
1061 loop {
1062 tokio::select! {
1063 // If block subscription is present, listen to it to avoid blocking indefinitely past the desired to_block
1064 block = if let Some(bs) = &mut block_subscription {
1065 Either::Left(bs.next().fuse())
1066 } else {
1067 Either::Right(futures::future::pending())
1068 } => {
1069 if let (Some(block), Some(to_block)) = (block, to_block_number)
1070 && block.number > to_block {
1071 break;
1072 }
1073 },
1074 // Process incoming log
1075 log = subscription.next() => {
1076 if format_json {
1077 if !first {
1078 write!(output, ",")?;
1079 }
1080 first = false;
1081 let log_str = serde_json::to_string(&log).unwrap();
1082 write!(output, "{log_str}")?;
1083 } else {
1084 let log_str = log.pretty()
1085 .replacen('\n', "- ", 1) // Remove empty first line
1086 .replace('\n', "\n "); // Indent
1087 writeln!(output, "{log_str}")?;
1088 }
1089 },
1090 // Break on cancel signal, to allow for closing JSON bracket
1091 _ = ctrl_c() => {
1092 break;
1093 },
1094 else => break,
1095 }
1096 }
1097
1098 // If output was JSON, end with a closing bracket
1099 if format_json {
1100 write!(output, "]")?;
1101 }
1102
1103 Ok(())
1104 }
1105
1106 pub async fn erc20_balance(
1107 &self,
1108 token: Address,
1109 owner: Address,
1110 block: Option<BlockId>,
1111 ) -> Result<U256> {
1112 Ok(IERC20::new(token, &self.provider)
1113 .balanceOf(owner)
1114 .block(block.unwrap_or_default())
1115 .call()
1116 .await?)
1117 }
1118}
1119
1120pub struct SimpleCast;
1121
1122impl SimpleCast {
1123 /// Returns the maximum value of the given integer type
1124 ///
1125 /// # Example
1126 ///
1127 /// ```
1128 /// use alloy_primitives::{I256, U256};
1129 /// use cast::SimpleCast;
1130 ///
1131 /// assert_eq!(SimpleCast::max_int("uint256")?, U256::MAX.to_string());
1132 /// assert_eq!(SimpleCast::max_int("int256")?, I256::MAX.to_string());
1133 /// assert_eq!(SimpleCast::max_int("int32")?, i32::MAX.to_string());
1134 /// # Ok::<(), eyre::Report>(())
1135 /// ```
1136 pub fn max_int(s: &str) -> Result<String> {
1137 Self::max_min_int::<true>(s)
1138 }
1139
1140 /// Returns the maximum value of the given integer type
1141 ///
1142 /// # Example
1143 ///
1144 /// ```
1145 /// use alloy_primitives::{I256, U256};
1146 /// use cast::SimpleCast;
1147 ///
1148 /// assert_eq!(SimpleCast::min_int("uint256")?, "0");
1149 /// assert_eq!(SimpleCast::min_int("int256")?, I256::MIN.to_string());
1150 /// assert_eq!(SimpleCast::min_int("int32")?, i32::MIN.to_string());
1151 /// # Ok::<(), eyre::Report>(())
1152 /// ```
1153 pub fn min_int(s: &str) -> Result<String> {
1154 Self::max_min_int::<false>(s)
1155 }
1156
1157 fn max_min_int<const MAX: bool>(s: &str) -> Result<String> {
1158 let ty = DynSolType::parse(s).wrap_err("Invalid type, expected `(u)int<bit size>`")?;
1159 match ty {
1160 DynSolType::Int(n) => {
1161 let mask = U256::from(1).wrapping_shl(n - 1);
1162 let max = (U256::MAX & mask).saturating_sub(U256::from(1));
1163 if MAX {
1164 Ok(max.to_string())
1165 } else {
1166 let min = I256::from_raw(max).wrapping_neg() + I256::MINUS_ONE;
1167 Ok(min.to_string())
1168 }
1169 }
1170 DynSolType::Uint(n) => {
1171 if MAX {
1172 let mut max = U256::MAX;
1173 if n < 255 {
1174 max &= U256::from(1).wrapping_shl(n).wrapping_sub(U256::from(1));
1175 }
1176 Ok(max.to_string())
1177 } else {
1178 Ok("0".to_string())
1179 }
1180 }
1181 _ => Err(eyre::eyre!("Type is not int/uint: {s}")),
1182 }
1183 }
1184
1185 /// Converts UTF-8 text input to hex
1186 ///
1187 /// # Example
1188 ///
1189 /// ```
1190 /// use cast::SimpleCast as Cast;
1191 ///
1192 /// assert_eq!(Cast::from_utf8("yo"), "0x796f");
1193 /// assert_eq!(Cast::from_utf8("Hello, World!"), "0x48656c6c6f2c20576f726c6421");
1194 /// assert_eq!(Cast::from_utf8("TurboDappTools"), "0x547572626f44617070546f6f6c73");
1195 /// # Ok::<_, eyre::Report>(())
1196 /// ```
1197 pub fn from_utf8(s: &str) -> String {
1198 hex::encode_prefixed(s)
1199 }
1200
1201 /// Converts hex input to UTF-8 text
1202 ///
1203 /// # Example
1204 ///
1205 /// ```
1206 /// use cast::SimpleCast as Cast;
1207 ///
1208 /// assert_eq!(Cast::to_utf8("0x796f")?, "yo");
1209 /// assert_eq!(Cast::to_utf8("0x48656c6c6f2c20576f726c6421")?, "Hello, World!");
1210 /// assert_eq!(Cast::to_utf8("0x547572626f44617070546f6f6c73")?, "TurboDappTools");
1211 /// assert_eq!(Cast::to_utf8("0xe4bda0e5a5bd")?, "你好");
1212 /// # Ok::<_, eyre::Report>(())
1213 /// ```
1214 pub fn to_utf8(s: &str) -> Result<String> {
1215 let bytes = hex::decode(s)?;
1216 Ok(String::from_utf8_lossy(bytes.as_ref()).to_string())
1217 }
1218
1219 /// Converts hex data into text data
1220 ///
1221 /// # Example
1222 ///
1223 /// ```
1224 /// use cast::SimpleCast as Cast;
1225 ///
1226 /// assert_eq!(Cast::to_ascii("0x796f")?, "yo");
1227 /// assert_eq!(Cast::to_ascii("48656c6c6f2c20576f726c6421")?, "Hello, World!");
1228 /// assert_eq!(Cast::to_ascii("0x547572626f44617070546f6f6c73")?, "TurboDappTools");
1229 /// # Ok::<_, eyre::Report>(())
1230 /// ```
1231 pub fn to_ascii(hex: &str) -> Result<String> {
1232 let bytes = hex::decode(hex)?;
1233 if !bytes.iter().all(u8::is_ascii) {
1234 return Err(eyre::eyre!("Invalid ASCII bytes"));
1235 }
1236 Ok(String::from_utf8(bytes).unwrap())
1237 }
1238
1239 /// Converts fixed point number into specified number of decimals
1240 /// ```
1241 /// use alloy_primitives::U256;
1242 /// use cast::SimpleCast as Cast;
1243 ///
1244 /// assert_eq!(Cast::from_fixed_point("10", "0")?, "10");
1245 /// assert_eq!(Cast::from_fixed_point("1.0", "1")?, "10");
1246 /// assert_eq!(Cast::from_fixed_point("0.10", "2")?, "10");
1247 /// assert_eq!(Cast::from_fixed_point("0.010", "3")?, "10");
1248 /// # Ok::<_, eyre::Report>(())
1249 /// ```
1250 pub fn from_fixed_point(value: &str, decimals: &str) -> Result<String> {
1251 let units: Unit = Unit::from_str(decimals)?;
1252 let n = ParseUnits::parse_units(value, units)?;
1253 Ok(n.to_string())
1254 }
1255
1256 /// Converts integers with specified decimals into fixed point numbers
1257 ///
1258 /// # Example
1259 ///
1260 /// ```
1261 /// use alloy_primitives::U256;
1262 /// use cast::SimpleCast as Cast;
1263 ///
1264 /// assert_eq!(Cast::to_fixed_point("10", "0")?, "10.");
1265 /// assert_eq!(Cast::to_fixed_point("10", "1")?, "1.0");
1266 /// assert_eq!(Cast::to_fixed_point("10", "2")?, "0.10");
1267 /// assert_eq!(Cast::to_fixed_point("10", "3")?, "0.010");
1268 ///
1269 /// assert_eq!(Cast::to_fixed_point("-10", "0")?, "-10.");
1270 /// assert_eq!(Cast::to_fixed_point("-10", "1")?, "-1.0");
1271 /// assert_eq!(Cast::to_fixed_point("-10", "2")?, "-0.10");
1272 /// assert_eq!(Cast::to_fixed_point("-10", "3")?, "-0.010");
1273 /// # Ok::<_, eyre::Report>(())
1274 /// ```
1275 pub fn to_fixed_point(value: &str, decimals: &str) -> Result<String> {
1276 let (sign, mut value, value_len) = {
1277 let number = NumberWithBase::parse_int(value, None)?;
1278 let sign = if number.is_nonnegative() { "" } else { "-" };
1279 let value = format!("{number:#}");
1280 let value_stripped = value.strip_prefix('-').unwrap_or(&value).to_string();
1281 let value_len = value_stripped.len();
1282 (sign, value_stripped, value_len)
1283 };
1284 let decimals = NumberWithBase::parse_uint(decimals, None)?.number().to::<usize>();
1285
1286 let value = if decimals >= value_len {
1287 // Add "0." and pad with 0s
1288 format!("0.{value:0>decimals$}")
1289 } else {
1290 // Insert decimal at -idx (i.e 1 => decimal idx = -1)
1291 value.insert(value_len - decimals, '.');
1292 value
1293 };
1294
1295 Ok(format!("{sign}{value}"))
1296 }
1297
1298 /// Concatencates hex strings
1299 ///
1300 /// # Example
1301 ///
1302 /// ```
1303 /// use cast::SimpleCast as Cast;
1304 ///
1305 /// assert_eq!(Cast::concat_hex(["0x00", "0x01"]), "0x0001");
1306 /// assert_eq!(Cast::concat_hex(["1", "2"]), "0x12");
1307 /// # Ok::<_, eyre::Report>(())
1308 /// ```
1309 pub fn concat_hex<T: AsRef<str>>(values: impl IntoIterator<Item = T>) -> String {
1310 let mut out = String::new();
1311 for s in values {
1312 let s = s.as_ref();
1313 out.push_str(s.strip_prefix("0x").unwrap_or(s))
1314 }
1315 format!("0x{out}")
1316 }
1317
1318 /// Converts a number into uint256 hex string with 0x prefix
1319 ///
1320 /// # Example
1321 ///
1322 /// ```
1323 /// use cast::SimpleCast as Cast;
1324 ///
1325 /// assert_eq!(
1326 /// Cast::to_uint256("100")?,
1327 /// "0x0000000000000000000000000000000000000000000000000000000000000064"
1328 /// );
1329 /// assert_eq!(
1330 /// Cast::to_uint256("192038293923")?,
1331 /// "0x0000000000000000000000000000000000000000000000000000002cb65fd1a3"
1332 /// );
1333 /// assert_eq!(
1334 /// Cast::to_uint256(
1335 /// "115792089237316195423570985008687907853269984665640564039457584007913129639935"
1336 /// )?,
1337 /// "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
1338 /// );
1339 /// # Ok::<_, eyre::Report>(())
1340 /// ```
1341 pub fn to_uint256(value: &str) -> Result<String> {
1342 let n = NumberWithBase::parse_uint(value, None)?;
1343 Ok(format!("{n:#066x}"))
1344 }
1345
1346 /// Converts a number into int256 hex string with 0x prefix
1347 ///
1348 /// # Example
1349 ///
1350 /// ```
1351 /// use cast::SimpleCast as Cast;
1352 ///
1353 /// assert_eq!(
1354 /// Cast::to_int256("0")?,
1355 /// "0x0000000000000000000000000000000000000000000000000000000000000000"
1356 /// );
1357 /// assert_eq!(
1358 /// Cast::to_int256("100")?,
1359 /// "0x0000000000000000000000000000000000000000000000000000000000000064"
1360 /// );
1361 /// assert_eq!(
1362 /// Cast::to_int256("-100")?,
1363 /// "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9c"
1364 /// );
1365 /// assert_eq!(
1366 /// Cast::to_int256("192038293923")?,
1367 /// "0x0000000000000000000000000000000000000000000000000000002cb65fd1a3"
1368 /// );
1369 /// assert_eq!(
1370 /// Cast::to_int256("-192038293923")?,
1371 /// "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffd349a02e5d"
1372 /// );
1373 /// assert_eq!(
1374 /// Cast::to_int256(
1375 /// "57896044618658097711785492504343953926634992332820282019728792003956564819967"
1376 /// )?,
1377 /// "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
1378 /// );
1379 /// assert_eq!(
1380 /// Cast::to_int256(
1381 /// "-57896044618658097711785492504343953926634992332820282019728792003956564819968"
1382 /// )?,
1383 /// "0x8000000000000000000000000000000000000000000000000000000000000000"
1384 /// );
1385 /// # Ok::<_, eyre::Report>(())
1386 /// ```
1387 pub fn to_int256(value: &str) -> Result<String> {
1388 let n = NumberWithBase::parse_int(value, None)?;
1389 Ok(format!("{n:#066x}"))
1390 }
1391
1392 /// Converts an eth amount into a specified unit
1393 ///
1394 /// # Example
1395 ///
1396 /// ```
1397 /// use cast::SimpleCast as Cast;
1398 ///
1399 /// assert_eq!(Cast::to_unit("1 wei", "wei")?, "1");
1400 /// assert_eq!(Cast::to_unit("1", "wei")?, "1");
1401 /// assert_eq!(Cast::to_unit("1ether", "wei")?, "1000000000000000000");
1402 /// # Ok::<_, eyre::Report>(())
1403 /// ```
1404 pub fn to_unit(value: &str, unit: &str) -> Result<String> {
1405 let value = DynSolType::coerce_str(&DynSolType::Uint(256), value)?
1406 .as_uint()
1407 .wrap_err("Could not convert to uint")?
1408 .0;
1409 let unit = unit.parse().wrap_err("could not parse units")?;
1410 Ok(Self::format_unit_as_string(value, unit))
1411 }
1412
1413 /// Convert a number into a uint with arbitrary decimals.
1414 ///
1415 /// # Example
1416 ///
1417 /// ```
1418 /// use cast::SimpleCast as Cast;
1419 ///
1420 /// # fn main() -> eyre::Result<()> {
1421 /// assert_eq!(Cast::parse_units("1.0", 6)?, "1000000"); // USDC (6 decimals)
1422 /// assert_eq!(Cast::parse_units("2.5", 6)?, "2500000");
1423 /// assert_eq!(Cast::parse_units("1.0", 12)?, "1000000000000"); // 12 decimals
1424 /// assert_eq!(Cast::parse_units("1.23", 3)?, "1230"); // 3 decimals
1425 ///
1426 /// # Ok(())
1427 /// # }
1428 /// ```
1429 pub fn parse_units(value: &str, unit: u8) -> Result<String> {
1430 let unit = Unit::new(unit).ok_or_else(|| eyre::eyre!("invalid unit"))?;
1431
1432 Ok(ParseUnits::parse_units(value, unit)?.to_string())
1433 }
1434
1435 /// Format a number from smallest unit to decimal with arbitrary decimals.
1436 ///
1437 /// # Example
1438 ///
1439 /// ```
1440 /// use cast::SimpleCast as Cast;
1441 ///
1442 /// # fn main() -> eyre::Result<()> {
1443 /// assert_eq!(Cast::format_units("1000000", 6)?, "1"); // USDC (6 decimals)
1444 /// assert_eq!(Cast::format_units("2500000", 6)?, "2.500000");
1445 /// assert_eq!(Cast::format_units("1000000000000", 12)?, "1"); // 12 decimals
1446 /// assert_eq!(Cast::format_units("1230", 3)?, "1.230"); // 3 decimals
1447 ///
1448 /// # Ok(())
1449 /// # }
1450 /// ```
1451 pub fn format_units(value: &str, unit: u8) -> Result<String> {
1452 let value = NumberWithBase::parse_int(value, None)?.number();
1453 let unit = Unit::new(unit).ok_or_else(|| eyre::eyre!("invalid unit"))?;
1454 Ok(Self::format_unit_as_string(value, unit))
1455 }
1456
1457 // Helper function to format units as a string
1458 fn format_unit_as_string(value: U256, unit: Unit) -> String {
1459 let mut formatted = ParseUnits::U256(value).format_units(unit);
1460 // Trim empty fractional part.
1461 if let Some(dot) = formatted.find('.') {
1462 let fractional = &formatted[dot + 1..];
1463 if fractional.chars().all(|c: char| c == '0') {
1464 formatted = formatted[..dot].to_string();
1465 }
1466 }
1467 formatted
1468 }
1469
1470 /// Converts wei into an eth amount
1471 ///
1472 /// # Example
1473 ///
1474 /// ```
1475 /// use cast::SimpleCast as Cast;
1476 ///
1477 /// assert_eq!(Cast::from_wei("1", "gwei")?, "0.000000001");
1478 /// assert_eq!(Cast::from_wei("12340000005", "gwei")?, "12.340000005");
1479 /// assert_eq!(Cast::from_wei("10", "ether")?, "0.000000000000000010");
1480 /// assert_eq!(Cast::from_wei("100", "eth")?, "0.000000000000000100");
1481 /// assert_eq!(Cast::from_wei("17", "ether")?, "0.000000000000000017");
1482 /// # Ok::<_, eyre::Report>(())
1483 /// ```
1484 pub fn from_wei(value: &str, unit: &str) -> Result<String> {
1485 let value = NumberWithBase::parse_int(value, None)?.number();
1486 Ok(ParseUnits::U256(value).format_units(unit.parse()?))
1487 }
1488
1489 /// Converts an eth amount into wei
1490 ///
1491 /// # Example
1492 ///
1493 /// ```
1494 /// use cast::SimpleCast as Cast;
1495 ///
1496 /// assert_eq!(Cast::to_wei("100", "gwei")?, "100000000000");
1497 /// assert_eq!(Cast::to_wei("100", "eth")?, "100000000000000000000");
1498 /// assert_eq!(Cast::to_wei("1000", "ether")?, "1000000000000000000000");
1499 /// # Ok::<_, eyre::Report>(())
1500 /// ```
1501 pub fn to_wei(value: &str, unit: &str) -> Result<String> {
1502 let unit = unit.parse().wrap_err("could not parse units")?;
1503 Ok(ParseUnits::parse_units(value, unit)?.to_string())
1504 }
1505
1506 // Decodes RLP encoded data with validation for canonical integer representation
1507 ///
1508 /// # Examples
1509 /// ```
1510 /// use cast::SimpleCast as Cast;
1511 ///
1512 /// assert_eq!(Cast::from_rlp("0xc0", false).unwrap(), "[]");
1513 /// assert_eq!(Cast::from_rlp("0x0f", false).unwrap(), "\"0x0f\"");
1514 /// assert_eq!(Cast::from_rlp("0x33", false).unwrap(), "\"0x33\"");
1515 /// assert_eq!(Cast::from_rlp("0xc161", false).unwrap(), "[\"0x61\"]");
1516 /// assert_eq!(Cast::from_rlp("820002", true).is_err(), true);
1517 /// assert_eq!(Cast::from_rlp("820002", false).unwrap(), "\"0x0002\"");
1518 /// assert_eq!(Cast::from_rlp("00", true).is_err(), true);
1519 /// assert_eq!(Cast::from_rlp("00", false).unwrap(), "\"0x00\"");
1520 /// # Ok::<_, eyre::Report>(())
1521 /// ```
1522 pub fn from_rlp(value: impl AsRef<str>, as_int: bool) -> Result<String> {
1523 let bytes = hex::decode(value.as_ref()).wrap_err("Could not decode hex")?;
1524
1525 if as_int {
1526 return Ok(U256::decode(&mut &bytes[..])?.to_string());
1527 }
1528
1529 let item = Item::decode(&mut &bytes[..]).wrap_err("Could not decode rlp")?;
1530
1531 Ok(item.to_string())
1532 }
1533
1534 /// Encodes hex data or list of hex data to hexadecimal rlp
1535 ///
1536 /// # Example
1537 ///
1538 /// ```
1539 /// use cast::SimpleCast as Cast;
1540 ///
1541 /// assert_eq!(Cast::to_rlp("[]").unwrap(), "0xc0".to_string());
1542 /// assert_eq!(Cast::to_rlp("0x22").unwrap(), "0x22".to_string());
1543 /// assert_eq!(Cast::to_rlp("[\"0x61\"]",).unwrap(), "0xc161".to_string());
1544 /// assert_eq!(Cast::to_rlp("[\"0xf1\", \"f2\"]").unwrap(), "0xc481f181f2".to_string());
1545 /// # Ok::<_, eyre::Report>(())
1546 /// ```
1547 pub fn to_rlp(value: &str) -> Result<String> {
1548 let val = serde_json::from_str(value)
1549 .unwrap_or_else(|_| serde_json::Value::String(value.to_string()));
1550 let item = Item::value_to_item(&val)?;
1551 Ok(format!("0x{}", hex::encode(alloy_rlp::encode(item))))
1552 }
1553
1554 /// Converts a number of one base to another
1555 ///
1556 /// # Example
1557 ///
1558 /// ```
1559 /// use alloy_primitives::I256;
1560 /// use cast::SimpleCast as Cast;
1561 ///
1562 /// assert_eq!(Cast::to_base("100", Some("10"), "16")?, "0x64");
1563 /// assert_eq!(Cast::to_base("100", Some("10"), "oct")?, "0o144");
1564 /// assert_eq!(Cast::to_base("100", Some("10"), "binary")?, "0b1100100");
1565 ///
1566 /// assert_eq!(Cast::to_base("0xffffffffffffffff", None, "10")?, u64::MAX.to_string());
1567 /// assert_eq!(
1568 /// Cast::to_base("0xffffffffffffffffffffffffffffffff", None, "dec")?,
1569 /// u128::MAX.to_string()
1570 /// );
1571 /// // U256::MAX overflows as internally it is being parsed as I256
1572 /// assert_eq!(
1573 /// Cast::to_base(
1574 /// "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1575 /// None,
1576 /// "decimal"
1577 /// )?,
1578 /// I256::MAX.to_string()
1579 /// );
1580 /// # Ok::<_, eyre::Report>(())
1581 /// ```
1582 pub fn to_base(value: &str, base_in: Option<&str>, base_out: &str) -> Result<String> {
1583 let base_in = Base::unwrap_or_detect(base_in, value)?;
1584 let base_out: Base = base_out.parse()?;
1585 if base_in == base_out {
1586 return Ok(value.to_string());
1587 }
1588
1589 let mut n = NumberWithBase::parse_int(value, Some(&base_in.to_string()))?;
1590 n.set_base(base_out);
1591
1592 // Use Debug fmt
1593 Ok(format!("{n:#?}"))
1594 }
1595
1596 /// Converts hexdata into bytes32 value
1597 ///
1598 /// # Example
1599 ///
1600 /// ```
1601 /// use cast::SimpleCast as Cast;
1602 ///
1603 /// let bytes = Cast::to_bytes32("1234")?;
1604 /// assert_eq!(bytes, "0x1234000000000000000000000000000000000000000000000000000000000000");
1605 ///
1606 /// let bytes = Cast::to_bytes32("0x1234")?;
1607 /// assert_eq!(bytes, "0x1234000000000000000000000000000000000000000000000000000000000000");
1608 ///
1609 /// let err = Cast::to_bytes32("0x123400000000000000000000000000000000000000000000000000000000000011").unwrap_err();
1610 /// assert_eq!(err.to_string(), "string >32 bytes");
1611 /// # Ok::<_, eyre::Report>(())
1612 pub fn to_bytes32(s: &str) -> Result<String> {
1613 let s = strip_0x(s);
1614 if s.len() > 64 {
1615 eyre::bail!("string >32 bytes");
1616 }
1617
1618 let padded = format!("{s:0<64}");
1619 Ok(padded.parse::<B256>()?.to_string())
1620 }
1621
1622 /// Encodes string into bytes32 value
1623 pub fn format_bytes32_string(s: &str) -> Result<String> {
1624 let str_bytes: &[u8] = s.as_bytes();
1625 eyre::ensure!(str_bytes.len() <= 32, "bytes32 strings must not exceed 32 bytes in length");
1626
1627 let mut bytes32: [u8; 32] = [0u8; 32];
1628 bytes32[..str_bytes.len()].copy_from_slice(str_bytes);
1629 Ok(hex::encode_prefixed(bytes32))
1630 }
1631
1632 /// Decodes string from bytes32 value
1633 pub fn parse_bytes32_string(s: &str) -> Result<String> {
1634 let bytes = hex::decode(s)?;
1635 eyre::ensure!(bytes.len() == 32, "expected 32 byte hex-string");
1636 let len = bytes.iter().take_while(|x| **x != 0).count();
1637 Ok(std::str::from_utf8(&bytes[..len])?.into())
1638 }
1639
1640 /// Decodes checksummed address from bytes32 value
1641 pub fn parse_bytes32_address(s: &str) -> Result<String> {
1642 let s = strip_0x(s);
1643 if s.len() != 64 {
1644 eyre::bail!("expected 64 byte hex-string, got {s}");
1645 }
1646
1647 let s = if let Some(stripped) = s.strip_prefix("000000000000000000000000") {
1648 stripped
1649 } else {
1650 return Err(eyre::eyre!("Not convertible to address, there are non-zero bytes"));
1651 };
1652
1653 let lowercase_address_string = format!("0x{s}");
1654 let lowercase_address = Address::from_str(&lowercase_address_string)?;
1655
1656 Ok(lowercase_address.to_checksum(None))
1657 }
1658
1659 /// Decodes abi-encoded hex input or output
1660 ///
1661 /// When `input=true`, `calldata` string MUST not be prefixed with function selector
1662 ///
1663 /// # Example
1664 ///
1665 /// ```
1666 /// use cast::SimpleCast as Cast;
1667 /// use alloy_primitives::hex;
1668 ///
1669 /// // Passing `input = false` will decode the data as the output type.
1670 /// // The input data types and the full function sig are ignored, i.e.
1671 /// // you could also pass `balanceOf()(uint256)` and it'd still work.
1672 /// let data = "0x0000000000000000000000000000000000000000000000000000000000000001";
1673 /// let sig = "balanceOf(address, uint256)(uint256)";
1674 /// let decoded = Cast::abi_decode(sig, data, false)?[0].as_uint().unwrap().0.to_string();
1675 /// assert_eq!(decoded, "1");
1676 ///
1677 /// // Passing `input = true` will decode the data with the input function signature.
1678 /// // We exclude the "prefixed" function selector from the data field (the first 4 bytes).
1679 /// let data = "0x0000000000000000000000008dbd1b711dc621e1404633da156fcc779e1c6f3e000000000000000000000000d9f3c9cc99548bf3b44a43e0a2d07399eb918adc000000000000000000000000000000000000000000000000000000000000002a000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000";
1680 /// let sig = "safeTransferFrom(address, address, uint256, uint256, bytes)";
1681 /// let decoded = Cast::abi_decode(sig, data, true)?;
1682 /// let decoded = [
1683 /// decoded[0].as_address().unwrap().to_string().to_lowercase(),
1684 /// decoded[1].as_address().unwrap().to_string().to_lowercase(),
1685 /// decoded[2].as_uint().unwrap().0.to_string(),
1686 /// decoded[3].as_uint().unwrap().0.to_string(),
1687 /// hex::encode(decoded[4].as_bytes().unwrap())
1688 /// ]
1689 /// .into_iter()
1690 /// .collect::<Vec<_>>();
1691 ///
1692 /// assert_eq!(
1693 /// decoded,
1694 /// vec!["0x8dbd1b711dc621e1404633da156fcc779e1c6f3e", "0xd9f3c9cc99548bf3b44a43e0a2d07399eb918adc", "42", "1", ""]
1695 /// );
1696 /// # Ok::<_, eyre::Report>(())
1697 /// ```
1698 pub fn abi_decode(sig: &str, calldata: &str, input: bool) -> Result<Vec<DynSolValue>> {
1699 foundry_common::abi::abi_decode_calldata(sig, calldata, input, false)
1700 }
1701
1702 /// Decodes calldata-encoded hex input or output
1703 ///
1704 /// Similar to `abi_decode`, but `calldata` string MUST be prefixed with function selector
1705 ///
1706 /// # Example
1707 ///
1708 /// ```
1709 /// use cast::SimpleCast as Cast;
1710 /// use alloy_primitives::hex;
1711 ///
1712 /// // Passing `input = false` will decode the data as the output type.
1713 /// // The input data types and the full function sig are ignored, i.e.
1714 /// // you could also pass `balanceOf()(uint256)` and it'd still work.
1715 /// let data = "0x0000000000000000000000000000000000000000000000000000000000000001";
1716 /// let sig = "balanceOf(address, uint256)(uint256)";
1717 /// let decoded = Cast::calldata_decode(sig, data, false)?[0].as_uint().unwrap().0.to_string();
1718 /// assert_eq!(decoded, "1");
1719 ///
1720 /// // Passing `input = true` will decode the data with the input function signature.
1721 /// let data = "0xf242432a0000000000000000000000008dbd1b711dc621e1404633da156fcc779e1c6f3e000000000000000000000000d9f3c9cc99548bf3b44a43e0a2d07399eb918adc000000000000000000000000000000000000000000000000000000000000002a000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000";
1722 /// let sig = "safeTransferFrom(address, address, uint256, uint256, bytes)";
1723 /// let decoded = Cast::calldata_decode(sig, data, true)?;
1724 /// let decoded = [
1725 /// decoded[0].as_address().unwrap().to_string().to_lowercase(),
1726 /// decoded[1].as_address().unwrap().to_string().to_lowercase(),
1727 /// decoded[2].as_uint().unwrap().0.to_string(),
1728 /// decoded[3].as_uint().unwrap().0.to_string(),
1729 /// hex::encode(decoded[4].as_bytes().unwrap()),
1730 /// ]
1731 /// .into_iter()
1732 /// .collect::<Vec<_>>();
1733 /// assert_eq!(
1734 /// decoded,
1735 /// vec!["0x8dbd1b711dc621e1404633da156fcc779e1c6f3e", "0xd9f3c9cc99548bf3b44a43e0a2d07399eb918adc", "42", "1", ""]
1736 /// );
1737 /// # Ok::<_, eyre::Report>(())
1738 /// ```
1739 pub fn calldata_decode(sig: &str, calldata: &str, input: bool) -> Result<Vec<DynSolValue>> {
1740 foundry_common::abi::abi_decode_calldata(sig, calldata, input, true)
1741 }
1742
1743 /// Performs ABI encoding based off of the function signature. Does not include
1744 /// the function selector in the result.
1745 ///
1746 /// # Example
1747 ///
1748 /// ```
1749 /// use cast::SimpleCast as Cast;
1750 ///
1751 /// assert_eq!(
1752 /// "0x0000000000000000000000000000000000000000000000000000000000000001",
1753 /// Cast::abi_encode("f(uint a)", &["1"]).unwrap().as_str()
1754 /// );
1755 /// assert_eq!(
1756 /// "0x0000000000000000000000000000000000000000000000000000000000000001",
1757 /// Cast::abi_encode("constructor(uint a)", &["1"]).unwrap().as_str()
1758 /// );
1759 /// # Ok::<_, eyre::Report>(())
1760 /// ```
1761 pub fn abi_encode(sig: &str, args: &[impl AsRef<str>]) -> Result<String> {
1762 let func = get_func(sig)?;
1763 match encode_function_args(&func, args) {
1764 Ok(res) => Ok(hex::encode_prefixed(&res[4..])),
1765 Err(e) => eyre::bail!(
1766 "Could not ABI encode the function and arguments. Did you pass in the right types?\nError\n{}",
1767 e
1768 ),
1769 }
1770 }
1771
1772 /// Performs packed ABI encoding based off of the function signature or tuple.
1773 ///
1774 /// # Examplez
1775 ///
1776 /// ```
1777 /// use cast::SimpleCast as Cast;
1778 ///
1779 /// assert_eq!(
1780 /// "0x0000000000000000000000000000000000000000000000000000000000000064000000000000000000000000000000000000000000000000000000000000012c00000000000000c8",
1781 /// Cast::abi_encode_packed("(uint128[] a, uint64 b)", &["[100, 300]", "200"]).unwrap().as_str()
1782 /// );
1783 ///
1784 /// assert_eq!(
1785 /// "0x8dbd1b711dc621e1404633da156fcc779e1c6f3e68656c6c6f20776f726c64",
1786 /// Cast::abi_encode_packed("foo(address a, string b)", &["0x8dbd1b711dc621e1404633da156fcc779e1c6f3e", "hello world"]).unwrap().as_str()
1787 /// );
1788 /// # Ok::<_, eyre::Report>(())
1789 /// ```
1790 pub fn abi_encode_packed(sig: &str, args: &[impl AsRef<str>]) -> Result<String> {
1791 // If the signature is a tuple, we need to prefix it to make it a function
1792 let sig =
1793 if sig.trim_start().starts_with('(') { format!("foo{sig}") } else { sig.to_string() };
1794
1795 let func = get_func(sig.as_str())?;
1796 let encoded = match encode_function_args_packed(&func, args) {
1797 Ok(res) => hex::encode(res),
1798 Err(e) => eyre::bail!(
1799 "Could not ABI encode the function and arguments. Did you pass in the right types?\nError\n{}",
1800 e
1801 ),
1802 };
1803 Ok(format!("0x{encoded}"))
1804 }
1805
1806 /// Performs ABI encoding to produce the hexadecimal calldata with the given arguments.
1807 ///
1808 /// # Example
1809 ///
1810 /// ```
1811 /// use cast::SimpleCast as Cast;
1812 ///
1813 /// assert_eq!(
1814 /// "0xb3de648b0000000000000000000000000000000000000000000000000000000000000001",
1815 /// Cast::calldata_encode("f(uint256 a)", &["1"]).unwrap().as_str()
1816 /// );
1817 /// # Ok::<_, eyre::Report>(())
1818 /// ```
1819 pub fn calldata_encode(sig: impl AsRef<str>, args: &[impl AsRef<str>]) -> Result<String> {
1820 let func = get_func(sig.as_ref())?;
1821 let calldata = encode_function_args(&func, args)?;
1822 Ok(hex::encode_prefixed(calldata))
1823 }
1824
1825 /// Returns the slot number for a given mapping key and slot.
1826 ///
1827 /// Given `mapping(k => v) m`, for a key `k` the slot number of its associated `v` is
1828 /// `keccak256(concat(h(k), p))`, where `h` is the padding function for `k`'s type, and `p`
1829 /// is slot number of the mapping `m`.
1830 ///
1831 /// See [the Solidity documentation](https://docs.soliditylang.org/en/latest/internals/layout_in_storage.html#mappings-and-dynamic-arrays)
1832 /// for more details.
1833 ///
1834 /// # Example
1835 ///
1836 /// ```
1837 /// # use cast::SimpleCast as Cast;
1838 ///
1839 /// // Value types.
1840 /// assert_eq!(
1841 /// Cast::index("address", "0xD0074F4E6490ae3f888d1d4f7E3E43326bD3f0f5", "2").unwrap().as_str(),
1842 /// "0x9525a448a9000053a4d151336329d6563b7e80b24f8e628e95527f218e8ab5fb"
1843 /// );
1844 /// assert_eq!(
1845 /// Cast::index("uint256", "42", "6").unwrap().as_str(),
1846 /// "0xfc808b0f31a1e6b9cf25ff6289feae9b51017b392cc8e25620a94a38dcdafcc1"
1847 /// );
1848 ///
1849 /// // Strings and byte arrays.
1850 /// assert_eq!(
1851 /// Cast::index("string", "hello", "1").unwrap().as_str(),
1852 /// "0x8404bb4d805e9ca2bd5dd5c43a107e935c8ec393caa7851b353b3192cd5379ae"
1853 /// );
1854 /// # Ok::<_, eyre::Report>(())
1855 /// ```
1856 pub fn index(key_type: &str, key: &str, slot_number: &str) -> Result<String> {
1857 let mut hasher = Keccak256::new();
1858
1859 let k_ty = DynSolType::parse(key_type).wrap_err("Could not parse type")?;
1860 let k = k_ty.coerce_str(key).wrap_err("Could not parse value")?;
1861 match k_ty {
1862 // For value types, `h` pads the value to 32 bytes in the same way as when storing the
1863 // value in memory.
1864 DynSolType::Bool
1865 | DynSolType::Int(_)
1866 | DynSolType::Uint(_)
1867 | DynSolType::FixedBytes(_)
1868 | DynSolType::Address
1869 | DynSolType::Function => hasher.update(k.as_word().unwrap()),
1870
1871 // For strings and byte arrays, `h(k)` is just the unpadded data.
1872 DynSolType::String | DynSolType::Bytes => hasher.update(k.as_packed_seq().unwrap()),
1873
1874 DynSolType::Array(..)
1875 | DynSolType::FixedArray(..)
1876 | DynSolType::Tuple(..)
1877 | DynSolType::CustomStruct { .. } => {
1878 eyre::bail!("Type `{k_ty}` is not supported as a mapping key")
1879 }
1880 }
1881
1882 let p = DynSolType::Uint(256)
1883 .coerce_str(slot_number)
1884 .wrap_err("Could not parse slot number")?;
1885 let p = p.as_word().unwrap();
1886 hasher.update(p);
1887
1888 let location = hasher.finalize();
1889 Ok(location.to_string())
1890 }
1891
1892 /// Keccak-256 hashes arbitrary data
1893 ///
1894 /// # Example
1895 ///
1896 /// ```
1897 /// use cast::SimpleCast as Cast;
1898 ///
1899 /// assert_eq!(
1900 /// Cast::keccak("foo")?,
1901 /// "0x41b1a0649752af1b28b3dc29a1556eee781e4a4c3a1f7f53f90fa834de098c4d"
1902 /// );
1903 /// assert_eq!(
1904 /// Cast::keccak("123abc")?,
1905 /// "0xb1f1c74a1ba56f07a892ea1110a39349d40f66ca01d245e704621033cb7046a4"
1906 /// );
1907 /// assert_eq!(
1908 /// Cast::keccak("0x12")?,
1909 /// "0x5fa2358263196dbbf23d1ca7a509451f7a2f64c15837bfbb81298b1e3e24e4fa"
1910 /// );
1911 /// assert_eq!(
1912 /// Cast::keccak("12")?,
1913 /// "0x7f8b6b088b6d74c2852fc86c796dca07b44eed6fb3daf5e6b59f7c364db14528"
1914 /// );
1915 /// # Ok::<_, eyre::Report>(())
1916 /// ```
1917 pub fn keccak(data: &str) -> Result<String> {
1918 // Hex-decode if data starts with 0x.
1919 let hash =
1920 if data.starts_with("0x") { keccak256(hex::decode(data)?) } else { keccak256(data) };
1921 Ok(hash.to_string())
1922 }
1923
1924 /// Performs the left shift operation (<<) on a number
1925 ///
1926 /// # Example
1927 ///
1928 /// ```
1929 /// use cast::SimpleCast as Cast;
1930 ///
1931 /// assert_eq!(Cast::left_shift("16", "10", Some("10"), "hex")?, "0x4000");
1932 /// assert_eq!(Cast::left_shift("255", "16", Some("dec"), "hex")?, "0xff0000");
1933 /// assert_eq!(Cast::left_shift("0xff", "16", None, "hex")?, "0xff0000");
1934 /// # Ok::<_, eyre::Report>(())
1935 /// ```
1936 pub fn left_shift(
1937 value: &str,
1938 bits: &str,
1939 base_in: Option<&str>,
1940 base_out: &str,
1941 ) -> Result<String> {
1942 let base_out: Base = base_out.parse()?;
1943 let value = NumberWithBase::parse_uint(value, base_in)?;
1944 let bits = NumberWithBase::parse_uint(bits, None)?;
1945
1946 let res = value.number() << bits.number();
1947
1948 Ok(res.to_base(base_out, true)?)
1949 }
1950
1951 /// Performs the right shift operation (>>) on a number
1952 ///
1953 /// # Example
1954 ///
1955 /// ```
1956 /// use cast::SimpleCast as Cast;
1957 ///
1958 /// assert_eq!(Cast::right_shift("0x4000", "10", None, "dec")?, "16");
1959 /// assert_eq!(Cast::right_shift("16711680", "16", Some("10"), "hex")?, "0xff");
1960 /// assert_eq!(Cast::right_shift("0xff0000", "16", None, "hex")?, "0xff");
1961 /// # Ok::<(), eyre::Report>(())
1962 /// ```
1963 pub fn right_shift(
1964 value: &str,
1965 bits: &str,
1966 base_in: Option<&str>,
1967 base_out: &str,
1968 ) -> Result<String> {
1969 let base_out: Base = base_out.parse()?;
1970 let value = NumberWithBase::parse_uint(value, base_in)?;
1971 let bits = NumberWithBase::parse_uint(bits, None)?;
1972
1973 let res = value.number().wrapping_shr(bits.number().saturating_to());
1974
1975 Ok(res.to_base(base_out, true)?)
1976 }
1977
1978 /// Fetches source code of verified contracts from etherscan.
1979 ///
1980 /// # Example
1981 ///
1982 /// ```
1983 /// # use cast::SimpleCast as Cast;
1984 /// # use foundry_config::NamedChain;
1985 /// # async fn foo() -> eyre::Result<()> {
1986 /// assert_eq!(
1987 /// "/*
1988 /// - Bytecode Verification performed was compared on second iteration -
1989 /// This file is part of the DAO.....",
1990 /// Cast::etherscan_source(
1991 /// NamedChain::Mainnet.into(),
1992 /// "0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413".to_string(),
1993 /// Some("<etherscan_api_key>".to_string()),
1994 /// None,
1995 /// None
1996 /// )
1997 /// .await
1998 /// .unwrap()
1999 /// .as_str()
2000 /// );
2001 /// # Ok(())
2002 /// # }
2003 /// ```
2004 pub async fn etherscan_source(
2005 chain: Chain,
2006 contract_address: String,
2007 etherscan_api_key: Option<String>,
2008 explorer_api_url: Option<String>,
2009 explorer_url: Option<String>,
2010 ) -> Result<String> {
2011 let client = explorer_client(chain, etherscan_api_key, explorer_api_url, explorer_url)?;
2012 let metadata = client.contract_source_code(contract_address.parse()?).await?;
2013 Ok(metadata.source_code())
2014 }
2015
2016 /// Fetches the source code of verified contracts from etherscan and expands the resulting
2017 /// files to a directory for easy perusal.
2018 ///
2019 /// # Example
2020 ///
2021 /// ```
2022 /// # use cast::SimpleCast as Cast;
2023 /// # use foundry_config::NamedChain;
2024 /// # use std::path::PathBuf;
2025 /// # async fn expand() -> eyre::Result<()> {
2026 /// Cast::expand_etherscan_source_to_directory(
2027 /// NamedChain::Mainnet.into(),
2028 /// "0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413".to_string(),
2029 /// Some("<etherscan_api_key>".to_string()),
2030 /// PathBuf::from("output_dir"),
2031 /// None,
2032 /// None,
2033 /// )
2034 /// .await?;
2035 /// # Ok(())
2036 /// # }
2037 /// ```
2038 pub async fn expand_etherscan_source_to_directory(
2039 chain: Chain,
2040 contract_address: String,
2041 etherscan_api_key: Option<String>,
2042 output_directory: PathBuf,
2043 explorer_api_url: Option<String>,
2044 explorer_url: Option<String>,
2045 ) -> eyre::Result<()> {
2046 let client = explorer_client(chain, etherscan_api_key, explorer_api_url, explorer_url)?;
2047 let meta = client.contract_source_code(contract_address.parse()?).await?;
2048 let source_tree = meta.source_tree();
2049 source_tree.write_to(&output_directory)?;
2050 Ok(())
2051 }
2052
2053 /// Fetches the source code of verified contracts from etherscan, flattens it and writes it to
2054 /// the given path or stdout.
2055 pub async fn etherscan_source_flatten(
2056 chain: Chain,
2057 contract_address: String,
2058 etherscan_api_key: Option<String>,
2059 output_path: Option<PathBuf>,
2060 explorer_api_url: Option<String>,
2061 explorer_url: Option<String>,
2062 ) -> Result<()> {
2063 let client = explorer_client(chain, etherscan_api_key, explorer_api_url, explorer_url)?;
2064 let metadata = client.contract_source_code(contract_address.parse()?).await?;
2065 let Some(metadata) = metadata.items.first() else {
2066 eyre::bail!("Empty contract source code")
2067 };
2068
2069 let tmp = tempfile::tempdir()?;
2070 let project = etherscan_project(metadata, tmp.path())?;
2071 let target_path = project.find_contract_path(&metadata.contract_name)?;
2072
2073 let flattened = Flattener::new(project, &target_path)?.flatten();
2074
2075 if let Some(path) = output_path {
2076 fs::create_dir_all(path.parent().unwrap())?;
2077 fs::write(&path, flattened)?;
2078 sh_println!("Flattened file written at {}", path.display())?
2079 } else {
2080 sh_println!("{flattened}")?
2081 }
2082
2083 Ok(())
2084 }
2085
2086 /// Disassembles hex encoded bytecode into individual / human readable opcodes
2087 ///
2088 /// # Example
2089 ///
2090 /// ```
2091 /// use alloy_primitives::hex;
2092 /// use cast::SimpleCast as Cast;
2093 ///
2094 /// # async fn foo() -> eyre::Result<()> {
2095 /// let bytecode = "0x608060405260043610603f57600035";
2096 /// let opcodes = Cast::disassemble(&hex::decode(bytecode)?)?;
2097 /// println!("{}", opcodes);
2098 /// # Ok(())
2099 /// # }
2100 /// ```
2101 pub fn disassemble(code: &[u8]) -> Result<String> {
2102 let mut output = String::new();
2103
2104 for step in decode_instructions(code)? {
2105 write!(output, "{:08x}: ", step.pc)?;
2106
2107 if let Some(op) = step.op {
2108 write!(output, "{op}")?;
2109 } else {
2110 write!(output, "INVALID")?;
2111 }
2112
2113 if !step.immediate.is_empty() {
2114 write!(output, " {}", hex::encode_prefixed(step.immediate))?;
2115 }
2116
2117 writeln!(output)?;
2118 }
2119
2120 Ok(output)
2121 }
2122
2123 /// Gets the selector for a given function signature
2124 /// Optimizes if the `optimize` parameter is set to a number of leading zeroes
2125 ///
2126 /// # Example
2127 ///
2128 /// ```
2129 /// use cast::SimpleCast as Cast;
2130 ///
2131 /// assert_eq!(Cast::get_selector("foo(address,uint256)", 0)?.0, String::from("0xbd0d639f"));
2132 /// # Ok::<(), eyre::Error>(())
2133 /// ```
2134 pub fn get_selector(signature: &str, optimize: usize) -> Result<(String, String)> {
2135 if optimize > 4 {
2136 eyre::bail!("number of leading zeroes must not be greater than 4");
2137 }
2138 if optimize == 0 {
2139 let selector = get_func(signature)?.selector();
2140 return Ok((selector.to_string(), String::from(signature)));
2141 }
2142 let Some((name, params)) = signature.split_once('(') else {
2143 eyre::bail!("invalid function signature");
2144 };
2145
2146 let num_threads = std::thread::available_parallelism().map_or(1, |n| n.get());
2147 let found = AtomicBool::new(false);
2148
2149 let result: Option<(u32, String, String)> =
2150 (0..num_threads).into_par_iter().find_map_any(|i| {
2151 let nonce_start = i as u32;
2152 let nonce_step = num_threads as u32;
2153
2154 let mut nonce = nonce_start;
2155 while nonce < u32::MAX && !found.load(Ordering::Relaxed) {
2156 let input = format!("{name}{nonce}({params}");
2157 let hash = keccak256(input.as_bytes());
2158 let selector = &hash[..4];
2159
2160 if selector.iter().take_while(|&&byte| byte == 0).count() == optimize {
2161 found.store(true, Ordering::Relaxed);
2162 return Some((nonce, hex::encode_prefixed(selector), input));
2163 }
2164
2165 nonce += nonce_step;
2166 }
2167 None
2168 });
2169
2170 match result {
2171 Some((_nonce, selector, signature)) => Ok((selector, signature)),
2172 None => eyre::bail!("No selector found"),
2173 }
2174 }
2175
2176 /// Extracts function selectors, arguments and state mutability from bytecode
2177 ///
2178 /// # Example
2179 ///
2180 /// ```
2181 /// use alloy_primitives::fixed_bytes;
2182 /// use cast::SimpleCast as Cast;
2183 ///
2184 /// let bytecode = "6080604052348015600e575f80fd5b50600436106026575f3560e01c80632125b65b14602a575b5f80fd5b603a6035366004603c565b505050565b005b5f805f60608486031215604d575f80fd5b833563ffffffff81168114605f575f80fd5b925060208401356001600160a01b03811681146079575f80fd5b915060408401356001600160e01b03811681146093575f80fd5b80915050925092509256";
2185 /// let functions = Cast::extract_functions(bytecode)?;
2186 /// assert_eq!(functions, vec![(fixed_bytes!("0x2125b65b"), "uint32,address,uint224".to_string(), "pure")]);
2187 /// # Ok::<(), eyre::Report>(())
2188 /// ```
2189 pub fn extract_functions(bytecode: &str) -> Result<Vec<(Selector, String, &str)>> {
2190 let code = hex::decode(bytecode)?;
2191 let info = evmole::contract_info(
2192 evmole::ContractInfoArgs::new(&code)
2193 .with_selectors()
2194 .with_arguments()
2195 .with_state_mutability(),
2196 );
2197 Ok(info
2198 .functions
2199 .expect("functions extraction was requested")
2200 .into_iter()
2201 .map(|f| {
2202 (
2203 f.selector.into(),
2204 f.arguments
2205 .expect("arguments extraction was requested")
2206 .into_iter()
2207 .map(|t| t.sol_type_name().to_string())
2208 .collect::<Vec<String>>()
2209 .join(","),
2210 f.state_mutability
2211 .expect("state_mutability extraction was requested")
2212 .as_json_str(),
2213 )
2214 })
2215 .collect())
2216 }
2217
2218 /// Decodes a raw EIP2718 transaction payload
2219 /// Returns details about the typed transaction and ECSDA signature components
2220 ///
2221 /// # Example
2222 ///
2223 /// ```
2224 /// use cast::SimpleCast as Cast;
2225 ///
2226 /// let tx = "0x02f8f582a86a82058d8459682f008508351050808303fd84948e42f2f4101563bf679975178e880fd87d3efd4e80b884659ac74b00000000000000000000000080f0c1c49891dcfdd40b6e0f960f84e6042bcb6f000000000000000000000000b97ef9ef8734c71904d8002f8b6bc66dd9c48a6e00000000000000000000000000000000000000000000000000000000007ff4e20000000000000000000000000000000000000000000000000000000000000064c001a05d429597befe2835396206781b199122f2e8297327ed4a05483339e7a8b2022aa04c23a7f70fb29dda1b4ee342fb10a625e9b8ddc6a603fb4e170d4f6f37700cb8";
2227 /// let tx_envelope = Cast::decode_raw_transaction(&tx)?;
2228 /// # Ok::<(), eyre::Report>(())
2229 pub fn decode_raw_transaction(tx: &str) -> Result<TxEnvelope> {
2230 let tx_hex = hex::decode(tx)?;
2231 let tx = TxEnvelope::decode_2718(&mut tx_hex.as_slice())?;
2232 Ok(tx)
2233 }
2234}
2235
2236fn strip_0x(s: &str) -> &str {
2237 s.strip_prefix("0x").unwrap_or(s)
2238}
2239
2240fn explorer_client(
2241 chain: Chain,
2242 api_key: Option<String>,
2243 api_url: Option<String>,
2244 explorer_url: Option<String>,
2245) -> Result<Client> {
2246 let mut builder = Client::builder().with_chain_id(chain);
2247
2248 let deduced = chain.etherscan_urls();
2249
2250 let explorer_url = explorer_url
2251 .or(deduced.map(|d| d.1.to_string()))
2252 .ok_or_eyre("Please provide the explorer browser URL using `--explorer-url`")?;
2253 builder = builder.with_url(explorer_url)?;
2254
2255 let api_url = api_url
2256 .or(deduced.map(|d| d.0.to_string()))
2257 .ok_or_eyre("Please provide the explorer API URL using `--explorer-api-url`")?;
2258 builder = builder.with_api_url(api_url)?;
2259
2260 if let Some(api_key) = api_key {
2261 builder = builder.with_api_key(api_key);
2262 }
2263
2264 builder.build().map_err(Into::into)
2265}
2266
2267#[cfg(test)]
2268mod tests {
2269 use super::SimpleCast as Cast;
2270 use alloy_primitives::hex;
2271
2272 #[test]
2273 fn simple_selector() {
2274 assert_eq!("0xc2985578", Cast::get_selector("foo()", 0).unwrap().0.as_str())
2275 }
2276
2277 #[test]
2278 fn selector_with_arg() {
2279 assert_eq!("0xbd0d639f", Cast::get_selector("foo(address,uint256)", 0).unwrap().0.as_str())
2280 }
2281
2282 #[test]
2283 fn calldata_uint() {
2284 assert_eq!(
2285 "0xb3de648b0000000000000000000000000000000000000000000000000000000000000001",
2286 Cast::calldata_encode("f(uint256 a)", &["1"]).unwrap().as_str()
2287 );
2288 }
2289
2290 // <https://github.com/foundry-rs/foundry/issues/2681>
2291 #[test]
2292 fn calldata_array() {
2293 assert_eq!(
2294 "0xcde2baba0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000",
2295 Cast::calldata_encode("propose(string[])", &["[\"\"]"]).unwrap().as_str()
2296 );
2297 }
2298
2299 #[test]
2300 fn calldata_bool() {
2301 assert_eq!(
2302 "0x6fae94120000000000000000000000000000000000000000000000000000000000000000",
2303 Cast::calldata_encode("bar(bool)", &["false"]).unwrap().as_str()
2304 );
2305 }
2306
2307 #[test]
2308 fn abi_decode() {
2309 let data = "0x0000000000000000000000000000000000000000000000000000000000000001";
2310 let sig = "balanceOf(address, uint256)(uint256)";
2311 assert_eq!(
2312 "1",
2313 Cast::abi_decode(sig, data, false).unwrap()[0].as_uint().unwrap().0.to_string()
2314 );
2315
2316 let data = "0x0000000000000000000000008dbd1b711dc621e1404633da156fcc779e1c6f3e000000000000000000000000d9f3c9cc99548bf3b44a43e0a2d07399eb918adc000000000000000000000000000000000000000000000000000000000000002a000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000";
2317 let sig = "safeTransferFrom(address,address,uint256,uint256,bytes)";
2318 let decoded = Cast::abi_decode(sig, data, true).unwrap();
2319 let decoded = [
2320 decoded[0]
2321 .as_address()
2322 .unwrap()
2323 .to_string()
2324 .strip_prefix("0x")
2325 .unwrap()
2326 .to_owned()
2327 .to_lowercase(),
2328 decoded[1]
2329 .as_address()
2330 .unwrap()
2331 .to_string()
2332 .strip_prefix("0x")
2333 .unwrap()
2334 .to_owned()
2335 .to_lowercase(),
2336 decoded[2].as_uint().unwrap().0.to_string(),
2337 decoded[3].as_uint().unwrap().0.to_string(),
2338 hex::encode(decoded[4].as_bytes().unwrap()),
2339 ]
2340 .to_vec();
2341 assert_eq!(
2342 decoded,
2343 vec![
2344 "8dbd1b711dc621e1404633da156fcc779e1c6f3e",
2345 "d9f3c9cc99548bf3b44a43e0a2d07399eb918adc",
2346 "42",
2347 "1",
2348 ""
2349 ]
2350 );
2351 }
2352
2353 #[test]
2354 fn calldata_decode() {
2355 let data = "0x0000000000000000000000000000000000000000000000000000000000000001";
2356 let sig = "balanceOf(address, uint256)(uint256)";
2357 let decoded =
2358 Cast::calldata_decode(sig, data, false).unwrap()[0].as_uint().unwrap().0.to_string();
2359 assert_eq!(decoded, "1");
2360
2361 // Passing `input = true` will decode the data with the input function signature.
2362 // We exclude the "prefixed" function selector from the data field (the first 4 bytes).
2363 let data = "0xf242432a0000000000000000000000008dbd1b711dc621e1404633da156fcc779e1c6f3e000000000000000000000000d9f3c9cc99548bf3b44a43e0a2d07399eb918adc000000000000000000000000000000000000000000000000000000000000002a000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000";
2364 let sig = "safeTransferFrom(address, address, uint256, uint256, bytes)";
2365 let decoded = Cast::calldata_decode(sig, data, true).unwrap();
2366 let decoded = [
2367 decoded[0].as_address().unwrap().to_string().to_lowercase(),
2368 decoded[1].as_address().unwrap().to_string().to_lowercase(),
2369 decoded[2].as_uint().unwrap().0.to_string(),
2370 decoded[3].as_uint().unwrap().0.to_string(),
2371 hex::encode(decoded[4].as_bytes().unwrap()),
2372 ]
2373 .into_iter()
2374 .collect::<Vec<_>>();
2375 assert_eq!(
2376 decoded,
2377 vec![
2378 "0x8dbd1b711dc621e1404633da156fcc779e1c6f3e",
2379 "0xd9f3c9cc99548bf3b44a43e0a2d07399eb918adc",
2380 "42",
2381 "1",
2382 ""
2383 ]
2384 );
2385 }
2386
2387 #[test]
2388 fn concat_hex() {
2389 assert_eq!(Cast::concat_hex(["0x00", "0x01"]), "0x0001");
2390 assert_eq!(Cast::concat_hex(["1", "2"]), "0x12");
2391 }
2392
2393 #[test]
2394 fn from_rlp() {
2395 let rlp = "0xf8b1a02b5df5f0757397573e8ff34a8b987b21680357de1f6c8d10273aa528a851eaca8080a02838ac1d2d2721ba883169179b48480b2ba4f43d70fcf806956746bd9e83f90380a0e46fff283b0ab96a32a7cc375cecc3ed7b6303a43d64e0a12eceb0bc6bd8754980a01d818c1c414c665a9c9a0e0c0ef1ef87cacb380b8c1f6223cb2a68a4b2d023f5808080a0236e8f61ecde6abfebc6c529441f782f62469d8a2cc47b7aace2c136bd3b1ff08080808080";
2396 let item = Cast::from_rlp(rlp, false).unwrap();
2397 assert_eq!(
2398 item,
2399 r#"["0x2b5df5f0757397573e8ff34a8b987b21680357de1f6c8d10273aa528a851eaca","0x","0x","0x2838ac1d2d2721ba883169179b48480b2ba4f43d70fcf806956746bd9e83f903","0x","0xe46fff283b0ab96a32a7cc375cecc3ed7b6303a43d64e0a12eceb0bc6bd87549","0x","0x1d818c1c414c665a9c9a0e0c0ef1ef87cacb380b8c1f6223cb2a68a4b2d023f5","0x","0x","0x","0x236e8f61ecde6abfebc6c529441f782f62469d8a2cc47b7aace2c136bd3b1ff0","0x","0x","0x","0x","0x"]"#
2400 )
2401 }
2402
2403 #[test]
2404 fn disassemble_incomplete_sequence() {
2405 let incomplete = &hex!("60"); // PUSH1
2406 let disassembled = Cast::disassemble(incomplete).unwrap();
2407 assert_eq!(disassembled, "00000000: PUSH1 0x00\n");
2408
2409 let complete = &hex!("6000"); // PUSH1 0x00
2410 let disassembled = Cast::disassemble(complete);
2411 assert!(disassembled.is_ok());
2412
2413 let incomplete = &hex!("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); // PUSH32 with 31 bytes
2414
2415 let disassembled = Cast::disassemble(incomplete).unwrap();
2416
2417 assert_eq!(
2418 disassembled,
2419 "00000000: PUSH32 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00\n"
2420 );
2421
2422 let complete = &hex!("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); // PUSH32 with 32 bytes
2423 let disassembled = Cast::disassemble(complete);
2424 assert!(disassembled.is_ok());
2425 }
2426}