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