diff --git a/consensus/config/src/test_committee.rs b/consensus/config/src/test_committee.rs index cd6f3104950..231cb2fbde6 100644 --- a/consensus/config/src/test_committee.rs +++ b/consensus/config/src/test_committee.rs @@ -43,7 +43,7 @@ pub fn local_committee_and_keys( fn get_available_local_address() -> Multiaddr { let host = "127.0.0.1"; let port = get_available_port(host); - format!("/ip4/{}/udp/{}", host, port).parse().unwrap() + format!("/ip4/{host}/udp/{port}").parse().unwrap() } /// Returns an ephemeral, available port. On unix systems, the port returned diff --git a/consensus/core/src/authority_node.rs b/consensus/core/src/authority_node.rs index 27de9a7466e..fbd2dc0c946 100644 --- a/consensus/core/src/authority_node.rs +++ b/consensus/core/src/authority_node.rs @@ -162,8 +162,7 @@ where ) -> Self { assert!( committee.is_valid_index(own_index), - "Invalid own index {}", - own_index + "Invalid own index {own_index}" ); let own_hostname = &committee.authority(own_index).hostname; info!( @@ -545,8 +544,7 @@ mod tests { for txn in b.transactions().iter().map(|t| t.data().to_vec()) { assert!( expected_transactions.remove(&txn), - "Transaction not submitted or already seen: {:?}", - txn + "Transaction not submitted or already seen: {txn:?}" ); } } @@ -644,8 +642,7 @@ mod tests { for txn in b.transactions().iter().map(|t| t.data().to_vec()) { assert!( expected_transactions.remove(&txn), - "Transaction not submitted or already seen: {:?}", - txn + "Transaction not submitted or already seen: {txn:?}" ); } } diff --git a/consensus/core/src/authority_service.rs b/consensus/core/src/authority_service.rs index d850caac657..bb0ad8c6288 100644 --- a/consensus/core/src/authority_service.rs +++ b/consensus/core/src/authority_service.rs @@ -205,8 +205,7 @@ impl NetworkService for AuthorityService { return Err(ConsensusError::BlockRejected { block_ref, reason: format!( - "Last commit index is lagging quorum commit index too much ({} < {})", - last_commit_index, quorum_commit_index, + "Last commit index is lagging quorum commit index too much ({last_commit_index} < {quorum_commit_index})", ), }); } diff --git a/consensus/core/src/base_committer.rs b/consensus/core/src/base_committer.rs index 42299db232f..565a1c13ec5 100644 --- a/consensus/core/src/base_committer.rs +++ b/consensus/core/src/base_committer.rs @@ -208,7 +208,7 @@ impl BaseCommitter { .dag_state .read() .get_block(ancestor) - .unwrap_or_else(|| panic!("Block not found in storage: {:?}", ancestor)); + .unwrap_or_else(|| panic!("Block not found in storage: {ancestor:?}")); if let Some(support) = self.find_supported_block(leader_slot, &ancestor) { return Some(support); } @@ -255,14 +255,13 @@ impl BaseCommitter { } else { assert!( reference.round <= gc_round, - "Block not found in storage: {:?} , and is not below gc_round: {gc_round}", - reference + "Block not found in storage: {reference:?} , and is not below gc_round: {gc_round}" ); false } } else { let potential_vote = potential_vote - .unwrap_or_else(|| panic!("Block not found in storage: {:?}", reference)); + .unwrap_or_else(|| panic!("Block not found in storage: {reference:?}")); self.is_vote(&potential_vote, leader_block) }; diff --git a/consensus/core/src/block.rs b/consensus/core/src/block.rs index fde59339126..0f890e9b414 100644 --- a/consensus/core/src/block.rs +++ b/consensus/core/src/block.rs @@ -308,7 +308,7 @@ impl fmt::Display for Slot { impl fmt::Debug for Slot { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self) + write!(f, "{self}") } } diff --git a/consensus/core/src/block_manager.rs b/consensus/core/src/block_manager.rs index a3a730ed312..6b5c9604674 100644 --- a/consensus/core/src/block_manager.rs +++ b/consensus/core/src/block_manager.rs @@ -160,8 +160,7 @@ impl BlockManager { } TryAcceptResult::Processed => continue, TryAcceptResult::Suspended(_) | TryAcceptResult::Skipped => panic!( - "Did not expect to suspend or skip a committed block: {:?}", - block_ref + "Did not expect to suspend or skip a committed block: {block_ref:?}" ), }; } else { @@ -351,8 +350,7 @@ impl BlockManager { ancestor_blocks.push(None); } else { panic!( - "Unsuspended block {:?} has a missing ancestor! Ancestor not found in DagState: {:?}", - b, ancestor_ref + "Unsuspended block {b:?} has a missing ancestor! Ancestor not found in DagState: {ancestor_ref:?}" ); } } @@ -1104,8 +1102,7 @@ mod tests { assert_eq!( all_accepted_blocks, all_blocks, - "Failed acceptance sequence for seed {}", - seed + "Failed acceptance sequence for seed {seed}" ); assert!(block_manager.is_empty()); } diff --git a/consensus/core/src/commit_consumer.rs b/consensus/core/src/commit_consumer.rs index 6c9846b80a8..f3717ab23f6 100644 --- a/consensus/core/src/commit_consumer.rs +++ b/consensus/core/src/commit_consumer.rs @@ -75,9 +75,7 @@ impl CommitConsumerMonitor { let highest_handled_commit = self.highest_handled_commit(); assert!( highest_observed_commit_at_startup >= highest_handled_commit, - "we cannot have handled a commit that we do not know about: {} < {}", - highest_observed_commit_at_startup, - highest_handled_commit, + "we cannot have handled a commit that we do not know about: {highest_observed_commit_at_startup} < {highest_handled_commit}", ); let mut commit = self.highest_observed_commit_at_startup.write().unwrap(); diff --git a/consensus/core/src/commit_observer.rs b/consensus/core/src/commit_observer.rs index f438810e5bb..4e362d3677a 100644 --- a/consensus/core/src/commit_observer.rs +++ b/consensus/core/src/commit_observer.rs @@ -166,8 +166,7 @@ impl CommitObserver { load_committed_subdag_from_store(self.store.as_ref(), commit, reputation_scores); self.sender.send(committed_sub_dag).unwrap_or_else(|e| { panic!( - "Failed to send commit during recovery, probably due to shutdown: {:?}", - e + "Failed to send commit during recovery, probably due to shutdown: {e:?}" ) }); diff --git a/consensus/core/src/core.rs b/consensus/core/src/core.rs index 44d1904a9d4..db63268df42 100644 --- a/consensus/core/src/core.rs +++ b/consensus/core/src/core.rs @@ -2439,7 +2439,7 @@ mod test { .try_propose(true) .unwrap() .unwrap_or_else(|| { - panic!("Block should have been proposed for round {}", round) + panic!("Block should have been proposed for round {round}") }); } } @@ -2544,7 +2544,7 @@ mod test { .try_propose(true) .unwrap() .unwrap_or_else(|| { - panic!("Block should have been proposed for round {}", round) + panic!("Block should have been proposed for round {round}") }); } } @@ -2579,7 +2579,7 @@ mod test { .try_propose(true) .unwrap() .unwrap_or_else(|| { - panic!("Block should have been proposed for round {}", round) + panic!("Block should have been proposed for round {round}") }); } } @@ -3425,7 +3425,7 @@ mod test { expected_commit_index: 5, commit_index: 6, } => (), - _ => panic!("Unexpected error: {:?}", err), + _ => panic!("Unexpected error: {err:?}"), } } diff --git a/consensus/core/src/dag_state.rs b/consensus/core/src/dag_state.rs index b13c25264b1..4c9ca918cc7 100644 --- a/consensus/core/src/dag_state.rs +++ b/consensus/core/src/dag_state.rs @@ -127,11 +127,11 @@ impl DagState { let last_commit = store .read_last_commit() - .unwrap_or_else(|e| panic!("Failed to read from storage: {:?}", e)); + .unwrap_or_else(|e| panic!("Failed to read from storage: {e:?}")); let commit_info = store .read_last_commit_info() - .unwrap_or_else(|e| panic!("Failed to read from storage: {:?}", e)); + .unwrap_or_else(|e| panic!("Failed to read from storage: {e:?}")); let (mut last_committed_rounds, commit_recovery_start_index) = if let Some((commit_ref, commit_info)) = commit_info { tracing::info!("Recovering committed state from {commit_ref} {commit_info:?}"); @@ -147,7 +147,7 @@ impl DagState { if let Some(last_commit) = last_commit.as_ref() { store .scan_commits((commit_recovery_start_index..=last_commit.index()).into()) - .unwrap_or_else(|e| panic!("Failed to read from storage: {:?}", e)) + .unwrap_or_else(|e| panic!("Failed to read from storage: {e:?}")) .iter() .for_each(|commit| { for block_ref in commit.blocks() { @@ -258,7 +258,7 @@ impl DagState { loop { let commits = store .scan_commits((index..=index).into()) - .unwrap_or_else(|e| panic!("Failed to read from storage: {:?}", e)); + .unwrap_or_else(|e| panic!("Failed to read from storage: {e:?}")); let Some(commit) = commits.first() else { info!( "Recovering finished up to index {index}, no more commits to recover" @@ -283,7 +283,7 @@ impl DagState { block_ref, commit.index() ); - assert!(state.set_committed(block_ref), "Attempted to set again a block {:?} as committed when recovering commit {:?}", block_ref, commit); + assert!(state.set_committed(block_ref), "Attempted to set again a block {block_ref:?} as committed when recovering commit {commit:?}"); }); // All commits are indexed starting from 1, so one reach zero exit. @@ -425,7 +425,7 @@ impl DagState { let store_results = self .store .read_blocks(&missing_refs) - .unwrap_or_else(|e| panic!("Failed to read from storage: {:?}", e)); + .unwrap_or_else(|e| panic!("Failed to read from storage: {e:?}")); self.context .metrics .node_metrics @@ -452,8 +452,7 @@ impl DagState { false } else { panic!( - "Block {:?} not found in cache to set as committed.", - block_ref + "Block {block_ref:?} not found in cache to set as committed." ); } } @@ -488,7 +487,7 @@ impl DagState { /// checked. pub(crate) fn get_uncommitted_blocks_at_round(&self, round: Round) -> Vec { if round <= self.last_commit_round() { - panic!("Round {} have committed blocks!", round); + panic!("Round {round} have committed blocks!"); } let mut blocks = vec![]; @@ -521,7 +520,7 @@ impl DagState { } let block_ref = linked.pop_last().unwrap(); let Some(block) = self.get_block(&block_ref) else { - panic!("Block {:?} should exist in DAG!", block_ref); + panic!("Block {block_ref:?} should exist in DAG!"); }; linked.extend(block.ancestors().iter().cloned()); } @@ -536,7 +535,7 @@ impl DagState { )) .map(|r| { self.get_block(r) - .unwrap_or_else(|| panic!("Block {:?} should exist in DAG!", r)) + .unwrap_or_else(|| panic!("Block {r:?} should exist in DAG!")) .clone() }) .collect() @@ -757,7 +756,7 @@ impl DagState { let store_results = self .store .contains_blocks(&missing_refs) - .unwrap_or_else(|e| panic!("Failed to read from storage: {:?}", e)); + .unwrap_or_else(|e| panic!("Failed to read from storage: {e:?}")); self.context .metrics .node_metrics @@ -805,8 +804,7 @@ impl DagState { if commit.timestamp_ms() < last_commit.timestamp_ms() { panic!( - "Commit timestamps do not monotonically increment, prev commit {:?}, new commit {:?}", - last_commit, commit + "Commit timestamps do not monotonically increment, prev commit {last_commit:?}, new commit {commit:?}" ); } } else { @@ -994,7 +992,7 @@ impl DagState { ); self.store .write(WriteBatch::new(blocks, commits, commit_info_to_write)) - .unwrap_or_else(|e| panic!("Failed to write to storage: {:?}", e)); + .unwrap_or_else(|e| panic!("Failed to write to storage: {e:?}")); self.context .metrics .node_metrics @@ -1031,7 +1029,7 @@ impl DagState { pub(crate) fn recover_last_commit_info(&self) -> Option<(CommitRef, CommitInfo)> { self.store .read_last_commit_info() - .unwrap_or_else(|e| panic!("Failed to read from storage: {:?}", e)) + .unwrap_or_else(|e| panic!("Failed to read from storage: {e:?}")) } // TODO: Remove four methods below this when DistributedVoteScoring is enabled. @@ -1448,8 +1446,7 @@ mod test { // & 2) might not be in right lexicographical order. assert_eq!( ancestors_refs, expected_refs, - "Expected round 11 ancestors: {:?}. Got: {:?}", - expected_refs, ancestors_refs + "Expected round 11 ancestors: {expected_refs:?}. Got: {ancestors_refs:?}" ); } @@ -1558,7 +1555,7 @@ mod test { for block_ref in block_refs.clone() { let slot = block_ref.into(); let found = dag_state.contains_cached_block_at_slot(slot); - assert!(found, "A block should be found at slot {}", slot); + assert!(found, "A block should be found at slot {slot}"); } // Now try to ask also for one block ref that is not in cache @@ -2144,8 +2141,7 @@ mod test { if block_ref.round > gc_round && all_committed_blocks.contains(block_ref) { assert!( block_info.committed, - "Block {:?} should be committed", - block_ref + "Block {block_ref:?} should be committed" ); }; }); diff --git a/consensus/core/src/linearizer.rs b/consensus/core/src/linearizer.rs index dfe30d912f7..d67d42c8e9e 100644 --- a/consensus/core/src/linearizer.rs +++ b/consensus/core/src/linearizer.rs @@ -124,7 +124,7 @@ impl Linearizer { ); let serialized = commit .serialize() - .unwrap_or_else(|e| panic!("Failed to serialize commit: {}", e)); + .unwrap_or_else(|e| panic!("Failed to serialize commit: {e}")); let commit = TrustedCommit::new_trusted(commit, serialized); // Create the corresponding committed sub dag @@ -165,8 +165,7 @@ impl Linearizer { if context.protocol_config.consensus_linearize_subdag_v2() { assert!( dag_state.set_committed(&leader_block_ref), - "Leader block with reference {:?} attempted to be committed twice", - leader_block_ref + "Leader block with reference {leader_block_ref:?} attempted to be committed twice" ); while let Some(x) = buffer.pop() { @@ -247,8 +246,7 @@ impl Linearizer { if gc_enabled { assert!( to_commit.iter().all(|block| block.round() > gc_round), - "No blocks <= {gc_round} should be committed. Leader round {}, blocks {to_commit:?}.", - leader_block_ref + "No blocks <= {gc_round} should be committed. Leader round {leader_block_ref}, blocks {to_commit:?}." ); } @@ -899,7 +897,7 @@ mod tests { "Block D1 should have been committed." ); } else { - panic!("Unexpected subdag with index {:?}", idx); + panic!("Unexpected subdag with index {idx:?}"); } for block in subdag.blocks.iter() { diff --git a/consensus/core/src/network/tonic_network.rs b/consensus/core/src/network/tonic_network.rs index acf14d7f452..c1268286ba1 100644 --- a/consensus/core/src/network/tonic_network.rs +++ b/consensus/core/src/network/tonic_network.rs @@ -886,13 +886,13 @@ fn to_host_port_str(addr: &Multiaddr) -> Result { match (iter.next(), iter.next()) { (Some(Protocol::Ip4(ipaddr)), Some(Protocol::Udp(port))) => { - Ok(format!("{}:{}", ipaddr, port)) + Ok(format!("{ipaddr}:{port}")) } (Some(Protocol::Ip6(ipaddr)), Some(Protocol::Udp(port))) => { - Ok(format!("{}:{}", ipaddr, port)) + Ok(format!("{ipaddr}:{port}")) } (Some(Protocol::Dns(hostname)), Some(Protocol::Udp(port))) => { - Ok(format!("{}:{}", hostname, port)) + Ok(format!("{hostname}:{port}")) } _ => Err(format!("unsupported multiaddr: {addr}")), diff --git a/consensus/core/src/network/tonic_tls.rs b/consensus/core/src/network/tonic_tls.rs index 458a359ddda..662084bda46 100644 --- a/consensus/core/src/network/tonic_tls.rs +++ b/consensus/core/src/network/tonic_tls.rs @@ -29,7 +29,7 @@ pub(crate) fn create_rustls_server_config( let tls_private_key = self_signed_cert.rustls_private_key(); let mut tls_config = verifier .rustls_server_config(vec![tls_cert], tls_private_key) - .unwrap_or_else(|e| panic!("Failed to create TLS server config: {:?}", e)); + .unwrap_or_else(|e| panic!("Failed to create TLS server config: {e:?}")); tls_config.alpn_protocols = vec![b"h2".to_vec()]; tls_config } @@ -54,7 +54,7 @@ pub(crate) fn create_rustls_client_config( let mut tls_config = iota_tls::ServerCertVerifier::new(target_public_key, certificate_server_name(context)) .rustls_client_config(vec![tls_cert], tls_private_key) - .unwrap_or_else(|e| panic!("Failed to create TLS client config: {:?}", e)); + .unwrap_or_else(|e| panic!("Failed to create TLS client config: {e:?}")); // ServerCertVerifier sets alpn for completeness, but alpn cannot be predefined // when using HttpsConnector from hyper-rustls, as in TonicManager. tls_config.alpn_protocols = vec![]; diff --git a/consensus/core/src/storage/mem_store.rs b/consensus/core/src/storage/mem_store.rs index 602fd2ba4f9..631d9d9c4f5 100644 --- a/consensus/core/src/storage/mem_store.rs +++ b/consensus/core/src/storage/mem_store.rs @@ -121,7 +121,7 @@ impl Store for MemStore { if let Some(block) = block { blocks.push(block); } else { - panic!("Block {:?} not found!", r); + panic!("Block {r:?} not found!"); } } Ok(blocks) @@ -165,7 +165,7 @@ impl Store for MemStore { let mut blocks = vec![]; for (r, block) in refs.into_iter().zip(results.into_iter()) { blocks.push( - block.unwrap_or_else(|| panic!("Storage inconsistency: block {:?} not found!", r)), + block.unwrap_or_else(|| panic!("Storage inconsistency: block {r:?} not found!")), ); } Ok(blocks) diff --git a/consensus/core/src/storage/rocksdb_store.rs b/consensus/core/src/storage/rocksdb_store.rs index 26ef65cf564..a74d694109d 100644 --- a/consensus/core/src/storage/rocksdb_store.rs +++ b/consensus/core/src/storage/rocksdb_store.rs @@ -207,7 +207,7 @@ impl Store for RocksDBStore { let mut blocks = Vec::with_capacity(refs.len()); for (r, block) in refs.into_iter().zip(results.into_iter()) { blocks.push( - block.unwrap_or_else(|| panic!("Storage inconsistency: block {:?} not found!", r)), + block.unwrap_or_else(|| panic!("Storage inconsistency: block {r:?} not found!")), ); } Ok(blocks) @@ -242,7 +242,7 @@ impl Store for RocksDBStore { let mut blocks = vec![]; for (r, block) in refs.into_iter().zip(results.into_iter()) { blocks.push( - block.unwrap_or_else(|| panic!("Storage inconsistency: block {:?} not found!", r)), + block.unwrap_or_else(|| panic!("Storage inconsistency: block {r:?} not found!")), ); } Ok(blocks) diff --git a/consensus/core/src/storage/store_tests.rs b/consensus/core/src/storage/store_tests.rs index b6a68b5e265..14523bdefe7 100644 --- a/consensus/core/src/storage/store_tests.rs +++ b/consensus/core/src/storage/store_tests.rs @@ -143,14 +143,14 @@ async fn scan_blocks( let scanned_blocks = store .scan_blocks_by_author(AuthorityIndex::new_for_test(1), 20) .expect("Scan blocks should not fail"); - assert!(scanned_blocks.is_empty(), "{:?}", scanned_blocks); + assert!(scanned_blocks.is_empty(), "{scanned_blocks:?}"); } { let scanned_blocks = store .scan_blocks_by_author(AuthorityIndex::new_for_test(1), 12) .expect("Scan blocks should not fail"); - assert_eq!(scanned_blocks.len(), 2, "{:?}", scanned_blocks); + assert_eq!(scanned_blocks.len(), 2, "{scanned_blocks:?}"); assert_eq!( scanned_blocks, vec![written_blocks[5].clone(), written_blocks[7].clone()] @@ -171,7 +171,7 @@ async fn scan_blocks( let scanned_blocks = store .scan_blocks_by_author(AuthorityIndex::new_for_test(1), 10) .expect("Scan blocks should not fail"); - assert_eq!(scanned_blocks.len(), 5, "{:?}", scanned_blocks); + assert_eq!(scanned_blocks.len(), 5, "{scanned_blocks:?}"); assert_eq!( scanned_blocks, vec![ @@ -188,7 +188,7 @@ async fn scan_blocks( let scanned_blocks = store .scan_last_blocks_by_author(AuthorityIndex::new_for_test(1), 2, None) .expect("Scan blocks should not fail"); - assert_eq!(scanned_blocks.len(), 2, "{:?}", scanned_blocks); + assert_eq!(scanned_blocks.len(), 2, "{scanned_blocks:?}"); assert_eq!( scanned_blocks, vec![written_blocks[7].clone(), additional_blocks[2].clone()] @@ -212,7 +212,7 @@ async fn read_and_scan_commits( let last_commit = store .read_last_commit() .expect("Read last commit should not fail"); - assert!(last_commit.is_none(), "{:?}", last_commit); + assert!(last_commit.is_none(), "{last_commit:?}"); } let written_commits = vec![ @@ -256,8 +256,7 @@ async fn read_and_scan_commits( assert_eq!( last_commit.as_ref(), written_commits.last(), - "{:?}", - last_commit + "{last_commit:?}" ); } @@ -265,14 +264,14 @@ async fn read_and_scan_commits( let scanned_commits = store .scan_commits((20..=24).into()) .expect("Scan commits should not fail"); - assert!(scanned_commits.is_empty(), "{:?}", scanned_commits); + assert!(scanned_commits.is_empty(), "{scanned_commits:?}"); } { let scanned_commits = store .scan_commits((3..=4).into()) .expect("Scan commits should not fail"); - assert_eq!(scanned_commits.len(), 2, "{:?}", scanned_commits); + assert_eq!(scanned_commits.len(), 2, "{scanned_commits:?}"); assert_eq!( scanned_commits, vec![written_commits[2].clone(), written_commits[3].clone()] @@ -283,7 +282,7 @@ async fn read_and_scan_commits( let scanned_commits = store .scan_commits((0..=2).into()) .expect("Scan commits should not fail"); - assert_eq!(scanned_commits.len(), 2, "{:?}", scanned_commits); + assert_eq!(scanned_commits.len(), 2, "{scanned_commits:?}"); assert_eq!( scanned_commits, vec![written_commits[0].clone(), written_commits[1].clone()] @@ -294,7 +293,7 @@ async fn read_and_scan_commits( let scanned_commits = store .scan_commits((0..=4).into()) .expect("Scan commits should not fail"); - assert_eq!(scanned_commits.len(), 4, "{:?}", scanned_commits); + assert_eq!(scanned_commits.len(), 4, "{scanned_commits:?}"); assert_eq!(scanned_commits, written_commits,); } } diff --git a/consensus/core/src/test_dag_builder.rs b/consensus/core/src/test_dag_builder.rs index 2bd73f43547..a0ef759660d 100644 --- a/consensus/core/src/test_dag_builder.rs +++ b/consensus/core/src/test_dag_builder.rs @@ -181,7 +181,7 @@ impl DagBuilder { fn set_committed(&mut self, block_ref: &BlockRef) -> bool { let Some((_block, committed)) = self.blocks.get_mut(block_ref) else { - panic!("Block {:?} should be found in store", block_ref); + panic!("Block {block_ref:?} should be found in store"); }; if !*committed { *committed = true; diff --git a/consensus/core/src/tests/base_committer_tests.rs b/consensus/core/src/tests/base_committer_tests.rs index 9ae553fb00b..61517af1fdc 100644 --- a/consensus/core/src/tests/base_committer_tests.rs +++ b/consensus/core/src/tests/base_committer_tests.rs @@ -58,7 +58,7 @@ async fn try_direct_commit() { if let LeaderStatus::Commit(ref committed_block) = leader_status { assert_eq!(committed_block.author(), leader.authority) } else { - panic!("Expected a committed leader at round {}", round) + panic!("Expected a committed leader at round {round}") }; } else { // The base committer should mark the potential leader in r6 as undecided diff --git a/consensus/core/src/transaction.rs b/consensus/core/src/transaction.rs index 7948c83d20d..1e38f28398d 100644 --- a/consensus/core/src/transaction.rs +++ b/consensus/core/src/transaction.rs @@ -730,7 +730,7 @@ mod tests { assert_eq!(transactions.len(), 10); for (i, transaction) in transactions.iter().enumerate() { let t: String = bcs::from_bytes(transaction.data()).unwrap(); - assert_eq!(format!("transaction {}", i).to_string(), t); + assert_eq!(format!("transaction {i}").to_string(), t); } // second batch will contain the soft bundle and the additional last // transaction. diff --git a/crates/iota-analytics-indexer-derive/src/lib.rs b/crates/iota-analytics-indexer-derive/src/lib.rs index 537d5ebc2b6..ea7129217c5 100644 --- a/crates/iota-analytics-indexer-derive/src/lib.rs +++ b/crates/iota-analytics-indexer-derive/src/lib.rs @@ -20,10 +20,9 @@ pub fn schema_derive(input: TokenStream) -> TokenStream { .map(|(idx, field)| { let field_name = field.ident.as_ref().unwrap().to_string(); ( - format!("\"{}\".to_string()", field_name), + format!("\"{field_name}\".to_string()"), format!( - "if idx == {} {{ return self.{}.clone().into(); }}", - idx, field_name + "if idx == {idx} {{ return self.{field_name}.clone().into(); }}" ), ) }) diff --git a/crates/iota-analytics-indexer/src/handlers/mod.rs b/crates/iota-analytics-indexer/src/handlers/mod.rs index 7df97bcde03..75862ff04fe 100644 --- a/crates/iota-analytics-indexer/src/handlers/mod.rs +++ b/crates/iota-analytics-indexer/src/handlers/mod.rs @@ -250,7 +250,7 @@ fn parse_struct_field( if let Some(MoveValue::Vector(vec_values)) = values.get("vec").cloned() { if let Some(first_value) = vec_values.first() { parse_struct_field( - &format!("{}[0]", path), + &format!("{path}[0]"), first_value.clone(), curr_struct, all_structs, @@ -265,7 +265,7 @@ fn parse_struct_field( MoveValue::Variant(v) => { for (k, field) in v.fields.iter() { parse_struct_field( - &format!("{}.{}", path, k), + &format!("{path}.{k}"), field.clone(), curr_struct, all_structs, diff --git a/crates/iota-analytics-indexer/src/lib.rs b/crates/iota-analytics-indexer/src/lib.rs index 39852c92d01..fb3361fa7d3 100644 --- a/crates/iota-analytics-indexer/src/lib.rs +++ b/crates/iota-analytics-indexer/src/lib.rs @@ -188,7 +188,7 @@ impl SnowflakeMaxCheckpointReader { ) .expect("Failed to build sf api client"); Ok(SnowflakeMaxCheckpointReader { - query: format!("SELECT max({}) from {}", col_id, table_id), + query: format!("SELECT max({col_id}) from {table_id}"), api, }) } @@ -233,8 +233,7 @@ impl BQMaxCheckpointReader { ) -> anyhow::Result { Ok(BQMaxCheckpointReader { query: format!( - "SELECT max({}) from `{}.{}.{}`", - col_id, project_id, dataset_id, table_id + "SELECT max({col_id}) from `{project_id}.{dataset_id}.{table_id}`" ), client: Client::from_service_account_key_file(key_path).await?, project_id: project_id.to_string(), @@ -346,7 +345,7 @@ impl FileType { checkpoint_range: Range, ) -> Path { self.dir_prefix() - .child(format!("{}{}", EPOCH_DIR_PREFIX, epoch_num)) + .child(format!("{EPOCH_DIR_PREFIX}{epoch_num}")) .child(format!( "{}_{}.{}", checkpoint_range.start, @@ -549,7 +548,7 @@ pub async fn read_store_for_checkpoint( let prefix = join_paths(dir_prefix, &file_type_prefix); let epoch_dirs = find_all_dirs_with_epoch_prefix(&remote_object_store, Some(&prefix)).await?; let epoch = epoch_dirs.last_key_value().map(|(k, _v)| *k).unwrap_or(0); - let epoch_prefix = prefix.child(format!("epoch_{}", epoch)); + let epoch_prefix = prefix.child(format!("epoch_{epoch}")); let checkpoints = find_all_files_with_epoch_prefix(&remote_object_store, Some(&epoch_prefix)).await?; let next_checkpoint_seq_num = checkpoints diff --git a/crates/iota-archival/src/lib.rs b/crates/iota-archival/src/lib.rs index 21938964cc6..f20c1a7e407 100644 --- a/crates/iota-archival/src/lib.rs +++ b/crates/iota-archival/src/lib.rs @@ -524,8 +524,7 @@ where cloned_counter.load(Ordering::Relaxed) as f64 / instant.elapsed().as_secs_f64(); cloned_progress_bar.set_position(latest_checkpoint + total_checkpoints_loaded); cloned_progress_bar.set_message(format!( - "checkpoints/s: {}, txns/s: {}", - total_checkpoints_per_sec, total_txns_per_sec + "checkpoints/s: {total_checkpoints_per_sec}, txns/s: {total_txns_per_sec}" )); tokio::time::sleep(Duration::from_secs(1)).await; } diff --git a/crates/iota-archival/src/reader.rs b/crates/iota-archival/src/reader.rs index 0678f41954b..5519af80f8a 100644 --- a/crates/iota-archival/src/reader.rs +++ b/crates/iota-archival/src/reader.rs @@ -569,8 +569,7 @@ impl ArchiveReader { .get_checkpoint_by_sequence_number(prev_checkpoint_seq_num) .map_err(|e| anyhow!("Store op failed: {e}"))? .context(format!( - "Missing previous checkpoint {} in store", - prev_checkpoint_seq_num + "Missing previous checkpoint {prev_checkpoint_seq_num} in store" ))?; verify_checkpoint(&prev_checkpoint, store, certified_checkpoint) diff --git a/crates/iota-archival/src/writer.rs b/crates/iota-archival/src/writer.rs index 9b1bedf81c7..e54a85ce274 100644 --- a/crates/iota-archival/src/writer.rs +++ b/crates/iota-archival/src/writer.rs @@ -96,7 +96,7 @@ impl CheckpointWriter { ) -> Result { let epoch_num = manifest.epoch_num(); let checkpoint_sequence_num = manifest.next_checkpoint_seq_num(); - let epoch_dir = root_dir_path.join(format!("{}{epoch_num}", EPOCH_DIR_PREFIX)); + let epoch_dir = root_dir_path.join(format!("{EPOCH_DIR_PREFIX}{epoch_num}")); if epoch_dir.exists() { fs::remove_dir_all(&epoch_dir)?; } diff --git a/crates/iota-aws-orchestrator/src/monitor.rs b/crates/iota-aws-orchestrator/src/monitor.rs index 335960f8b96..0b0c83bdb00 100644 --- a/crates/iota-aws-orchestrator/src/monitor.rs +++ b/crates/iota-aws-orchestrator/src/monitor.rs @@ -252,7 +252,7 @@ impl LocalGrafana { // Create the new datasources. for (i, instance) in instances.into_iter().enumerate() { let mut file = path.clone(); - file.push(format!("instance-{}.yml", i)); + file.push(format!("instance-{i}.yml")); fs::write(&file, Self::datasource(&instance, i)).map_err(|e| { MonitorError::Grafana(format!("Failed to write grafana datasource ({e})")) })?; diff --git a/crates/iota-aws-orchestrator/src/settings.rs b/crates/iota-aws-orchestrator/src/settings.rs index 85eef212b51..8f4d27c827a 100644 --- a/crates/iota-aws-orchestrator/src/settings.rs +++ b/crates/iota-aws-orchestrator/src/settings.rs @@ -208,10 +208,10 @@ impl Settings { fn resolve_env(s: &str) -> String { let mut s = s.to_string(); for (name, value) in env::vars() { - s = s.replace(&format!("${{{}}}", name), &value); + s = s.replace(&format!("${{{name}}}"), &value); } if s.contains("${") { - eprintln!("settings.json:\n{}\n", s); + eprintln!("settings.json:\n{s}\n"); panic!("Unresolved env variables in the settings.json"); } s diff --git a/crates/iota-benchmark/src/bin/stress.rs b/crates/iota-benchmark/src/bin/stress.rs index 4c9d241ee10..d1f23b0135f 100644 --- a/crates/iota-benchmark/src/bin/stress.rs +++ b/crates/iota-benchmark/src/bin/stress.rs @@ -167,12 +167,12 @@ async fn main() -> Result<()> { Ok((benchmark_stats, stress_stats)) => { let benchmark_table = benchmark_stats.to_table(); eprintln!("Benchmark Report:"); - eprintln!("{}", benchmark_table); + eprintln!("{benchmark_table}"); if stress_stat_collection { eprintln!("Stress Performance Report:"); let stress_stats_table = stress_stats.to_table(); - eprintln!("{}", stress_stats_table); + eprintln!("{stress_stats_table}"); } if !prev_benchmark_stats_path.is_empty() { @@ -184,10 +184,9 @@ async fn main() -> Result<()> { }; let cmp_table = cmp.to_table(); eprintln!( - "Benchmark Comparison Report[{}]:", - prev_benchmark_stats_path + "Benchmark Comparison Report[{prev_benchmark_stats_path}]:" ); - eprintln!("{}", cmp_table); + eprintln!("{cmp_table}"); } if !curr_benchmark_stats_path.is_empty() { let serialized = serde_json::to_string(&benchmark_stats)?; diff --git a/crates/iota-benchmark/src/drivers/bench_driver.rs b/crates/iota-benchmark/src/drivers/bench_driver.rs index e51b0627808..6f0984bd67a 100644 --- a/crates/iota-benchmark/src/drivers/bench_driver.rs +++ b/crates/iota-benchmark/src/drivers/bench_driver.rs @@ -470,7 +470,7 @@ impl Driver<(BenchmarkStats, StressStats)> for BenchDriver { num_in_flight ); if show_progress { - eprintln!("{}", stat); + eprintln!("{stat}"); } } } @@ -513,7 +513,7 @@ impl Driver<(BenchmarkStats, StressStats)> for BenchDriver { cpu_usage_histogram.value_at_quantile(0.99) ); if show_progress { - eprintln!("{}", stat); + eprintln!("{stat}"); } } } diff --git a/crates/iota-benchmark/src/drivers/mod.rs b/crates/iota-benchmark/src/drivers/mod.rs index f442d30a3b8..32f505f79d4 100644 --- a/crates/iota-benchmark/src/drivers/mod.rs +++ b/crates/iota-benchmark/src/drivers/mod.rs @@ -42,7 +42,7 @@ impl FromStr for Interval { impl std::fmt::Display for Interval { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - Interval::Count(count) => f.write_str(format!("{}", count).as_str()), + Interval::Count(count) => f.write_str(format!("{count}").as_str()), Interval::Time(d) => { if *d == Duration::MAX { f.write_str("unbounded") @@ -255,8 +255,8 @@ impl BenchmarkCmp<'_> { let speedup = 1.0 + diff_ratio; Comparison { name: "tps".to_string(), - old_value: format!("{:.2}", old_tps), - new_value: format!("{:.2}", new_tps), + old_value: format!("{old_tps:.2}"), + new_value: format!("{new_tps:.2}"), diff, diff_ratio, speedup, @@ -272,8 +272,8 @@ impl BenchmarkCmp<'_> { let speedup = 1.0 / (1.0 + diff_ratio); Comparison { name: "error_rate".to_string(), - old_value: format!("{:.2}", old_error_rate), - new_value: format!("{:.2}", new_error_rate), + old_value: format!("{old_error_rate:.2}"), + new_value: format!("{new_error_rate:.2}"), diff, diff_ratio, speedup, @@ -287,8 +287,8 @@ impl BenchmarkCmp<'_> { let speedup = 1.0 / (1.0 + diff_ratio); Comparison { name: "min_latency".to_string(), - old_value: format!("{:.2}", old), - new_value: format!("{:.2}", new), + old_value: format!("{old:.2}"), + new_value: format!("{new:.2}"), diff, diff_ratio, speedup, @@ -302,8 +302,8 @@ impl BenchmarkCmp<'_> { let speedup = 1.0 / (1.0 + diff_ratio); Comparison { name: "p25_latency".to_string(), - old_value: format!("{:.2}", old), - new_value: format!("{:.2}", new), + old_value: format!("{old:.2}"), + new_value: format!("{new:.2}"), diff, diff_ratio, speedup, @@ -317,8 +317,8 @@ impl BenchmarkCmp<'_> { let speedup = 1.0 / (1.0 + diff_ratio); Comparison { name: "p50_latency".to_string(), - old_value: format!("{:.2}", old), - new_value: format!("{:.2}", new), + old_value: format!("{old:.2}"), + new_value: format!("{new:.2}"), diff, diff_ratio, speedup, @@ -332,8 +332,8 @@ impl BenchmarkCmp<'_> { let speedup = 1.0 / (1.0 + diff_ratio); Comparison { name: "p75_latency".to_string(), - old_value: format!("{:.2}", old), - new_value: format!("{:.2}", new), + old_value: format!("{old:.2}"), + new_value: format!("{new:.2}"), diff, diff_ratio, speedup, @@ -347,8 +347,8 @@ impl BenchmarkCmp<'_> { let speedup = 1.0 / (1.0 + diff_ratio); Comparison { name: "p90_latency".to_string(), - old_value: format!("{:.2}", old), - new_value: format!("{:.2}", new), + old_value: format!("{old:.2}"), + new_value: format!("{new:.2}"), diff, diff_ratio, speedup, @@ -362,8 +362,8 @@ impl BenchmarkCmp<'_> { let speedup = 1.0 / (1.0 + diff_ratio); Comparison { name: "p99_latency".to_string(), - old_value: format!("{:.2}", old), - new_value: format!("{:.2}", new), + old_value: format!("{old:.2}"), + new_value: format!("{new:.2}"), diff, diff_ratio, speedup, @@ -377,8 +377,8 @@ impl BenchmarkCmp<'_> { let speedup = 1.0 / (1.0 + diff_ratio); Comparison { name: "p999_latency".to_string(), - old_value: format!("{:.2}", old), - new_value: format!("{:.2}", new), + old_value: format!("{old:.2}"), + new_value: format!("{new:.2}"), diff, diff_ratio, speedup, @@ -392,8 +392,8 @@ impl BenchmarkCmp<'_> { let speedup = 1.0 / (1.0 + diff_ratio); Comparison { name: "max_latency".to_string(), - old_value: format!("{:.2}", old), - new_value: format!("{:.2}", new), + old_value: format!("{old:.2}"), + new_value: format!("{new:.2}"), diff, diff_ratio, speedup, diff --git a/crates/iota-benchmark/src/fullnode_reconfig_observer.rs b/crates/iota-benchmark/src/fullnode_reconfig_observer.rs index e9537c19f7e..19fad64f121 100644 --- a/crates/iota-benchmark/src/fullnode_reconfig_observer.rs +++ b/crates/iota-benchmark/src/fullnode_reconfig_observer.rs @@ -42,8 +42,7 @@ impl FullNodeReconfigObserver { .await .unwrap_or_else(|e| { panic!( - "Can't create IotaClient with rpc url {fullnode_rpc_url}: {:?}", - e + "Can't create IotaClient with rpc url {fullnode_rpc_url}: {e:?}" ) }), committee_store, diff --git a/crates/iota-benchmark/src/workloads/adversarial.rs b/crates/iota-benchmark/src/workloads/adversarial.rs index c96697b0fa4..c8b7ba5f02a 100644 --- a/crates/iota-benchmark/src/workloads/adversarial.rs +++ b/crates/iota-benchmark/src/workloads/adversarial.rs @@ -178,8 +178,7 @@ impl Payload for AdversarialTestPayload { debug_assert!( effects.is_ok(), - "Adversarial transactions should never abort: {:?}", - stat + "Adversarial transactions should never abort: {stat:?}" ); self.state.update(effects); diff --git a/crates/iota-bridge-cli/src/lib.rs b/crates/iota-bridge-cli/src/lib.rs index 3e3264f153a..505ca9eec12 100644 --- a/crates/iota-bridge-cli/src/lib.rs +++ b/crates/iota-bridge-cli/src/lib.rs @@ -453,9 +453,9 @@ impl LoadedBridgeCliConfig { let eth_address = eth_signer.address(); let eth_chain_id = provider.get_chainid().await?; let iota_address = IotaAddress::from(&iota_key.public()); - println!("Using IOTA address: {:?}", iota_address); - println!("Using Eth address: {:?}", eth_address); - println!("Using Eth chain: {:?}", eth_chain_id); + println!("Using IOTA address: {iota_address:?}"); + println!("Using Eth address: {eth_address:?}"); + println!("Using Eth chain: {eth_chain_id:?}"); Ok(Self { iota_rpc_url: cli_config.iota_rpc_url, diff --git a/crates/iota-bridge-cli/src/main.rs b/crates/iota-bridge-cli/src/main.rs index cd6d90fb8ec..390b82dc3d9 100644 --- a/crates/iota-bridge-cli/src/main.rs +++ b/crates/iota-bridge-cli/src/main.rs @@ -78,7 +78,7 @@ async fn main() -> anyhow::Result<()> { dry_run, } => { let chain_id = BridgeChainId::try_from(chain_id).expect("Invalid chain id"); - println!("Chain ID: {:?}", chain_id); + println!("Chain ID: {chain_id:?}"); let config = BridgeCliConfig::load(config_path).expect("Couldn't load BridgeCliConfig"); let config = LoadedBridgeCliConfig::load(config).await?; let iota_bridge_client = IotaClient::::new(&config.iota_rpc_url).await?; @@ -104,12 +104,11 @@ async fn main() -> anyhow::Result<()> { let iota_chain_id = BridgeChainId::try_from(bridge_summary.chain_id).unwrap(); assert_eq!( iota_chain_id, chain_id, - "Chain ID mismatch, expected: {:?}, got from url: {:?}", - chain_id, iota_chain_id + "Chain ID mismatch, expected: {chain_id:?}, got from url: {iota_chain_id:?}" ); // Create BridgeAction let iota_action = make_action(iota_chain_id, &cmd); - println!("Action to execute on IOTA: {:?}", iota_action); + println!("Action to execute on IOTA: {iota_action:?}"); let certified_action = agg .request_committee_signatures(iota_action) .await @@ -159,7 +158,7 @@ async fn main() -> anyhow::Result<()> { let eth_signer_client = config.eth_signer(); // Create BridgeAction let eth_action = make_action(chain_id, &cmd); - println!("Action to execute on Eth: {:?}", eth_action); + println!("Action to execute on Eth: {eth_action:?}"); // Create Eth Signer Client // TODO if a validator is blocklisted on eth, ignore their signatures? let certified_action = agg @@ -178,14 +177,14 @@ async fn main() -> anyhow::Result<()> { ) .await .expect("Failed to build eth transaction"); - println!("sending Eth tx: {:?}", tx); + println!("sending Eth tx: {tx:?}"); match tx.send().await { Ok(tx_hash) => { - println!("Transaction sent with hash: {:?}", tx_hash); + println!("Transaction sent with hash: {tx_hash:?}"); } Err(err) => { let revert = err.as_revert(); - println!("Transaction reverted: {:?}", revert); + println!("Transaction reverted: {revert:?}"); } }; @@ -313,16 +312,14 @@ async fn main() -> anyhow::Result<()> { } = member; let Ok(pubkey) = BridgeAuthorityPublicKey::from_bytes(&bridge_pubkey_bytes) else { output_wrapper.add_error(format!( - "Invalid bridge pubkey for committee member {}: {:?}", - iota_address, bridge_pubkey_bytes + "Invalid bridge pubkey for committee member {iota_address}: {bridge_pubkey_bytes:?}" )); continue; }; let eth_address = BridgeAuthorityPublicKeyBytes::from(&pubkey).to_eth_address(); let Ok(url) = from_utf8(&http_rest_url) else { output_wrapper.add_error(format!( - "Invalid bridge http url for committee member {}: {:?}", - iota_address, http_rest_url + "Invalid bridge http url for committee member {iota_address}: {http_rest_url:?}" )); continue; }; @@ -396,16 +393,14 @@ async fn main() -> anyhow::Result<()> { } = member; let Ok(pubkey) = BridgeAuthorityPublicKey::from_bytes(&bridge_pubkey_bytes) else { output_wrapper.add_error(format!( - "Invalid bridge pubkey for bridge authority {}: {:?}", - iota_address, bridge_pubkey_bytes + "Invalid bridge pubkey for bridge authority {iota_address}: {bridge_pubkey_bytes:?}" )); continue; }; let eth_address = BridgeAuthorityPublicKeyBytes::from(&pubkey).to_eth_address(); let Ok(url) = from_utf8(&http_rest_url) else { output_wrapper.add_error(format!( - "Invalid bridge http url for bridge authority: {}: {:?}", - iota_address, http_rest_url + "Invalid bridge http url for bridge authority: {iota_address}: {http_rest_url:?}" )); continue; }; diff --git a/crates/iota-bridge-indexer/src/main.rs b/crates/iota-bridge-indexer/src/main.rs index 7fe337d82b3..d9ac48ffc17 100644 --- a/crates/iota-bridge-indexer/src/main.rs +++ b/crates/iota-bridge-indexer/src/main.rs @@ -59,7 +59,7 @@ async fn main() -> Result<()> { let registry_service = start_prometheus_server( format!("{}:{}", config.metric_url, config.metric_port,) .parse() - .unwrap_or_else(|err| panic!("Failed to parse metric address: {}", err)), + .unwrap_or_else(|err| panic!("Failed to parse metric address: {err}")), ); let registry = registry_service.default_registry(); diff --git a/crates/iota-bridge/src/abi.rs b/crates/iota-bridge/src/abi.rs index 85fc4cdb09d..62cd3ce2d15 100644 --- a/crates/iota-bridge/src/abi.rs +++ b/crates/iota-bridge/src/abi.rs @@ -107,8 +107,7 @@ impl EthBridgeEvent { Ok(bridge_event) => { if bridge_event.iota_adjusted_amount == 0 { return Err(BridgeError::ZeroValueBridgeTransfer(format!( - "Manual intervention is required: {}", - eth_tx_hash + "Manual intervention is required: {eth_tx_hash}" ))); } bridge_event @@ -119,8 +118,7 @@ impl EthBridgeEvent { // TODO: add metrics and alert Err(e) => { return Err(BridgeError::Generic(format!( - "Manual intervention is required. Failed to convert TokensDepositedFilter log to EthToIotaTokenBridgeV1. This indicates incorrect parameters or a bug in the code: {:?}. Err: {:?}", - event, e + "Manual intervention is required. Failed to convert TokensDepositedFilter log to EthToIotaTokenBridgeV1. This indicates incorrect parameters or a bug in the code: {event:?}. Err: {e:?}" ))); } }; @@ -558,7 +556,7 @@ mod tests { )); match e.try_into_bridge_action(TxHash::random(), 0).unwrap_err() { BridgeError::ZeroValueBridgeTransfer(_) => {} - e => panic!("Unexpected error: {:?}", e), + e => panic!("Unexpected error: {e:?}"), } } } diff --git a/crates/iota-bridge/src/action_executor.rs b/crates/iota-bridge/src/action_executor.rs index d98e551456a..996275fc1e7 100644 --- a/crates/iota-bridge/src/action_executor.rs +++ b/crates/iota-bridge/src/action_executor.rs @@ -308,7 +308,7 @@ where store .remove_pending_actions(&[action.digest()]) .unwrap_or_else(|e| { - panic!("Write to DB should not fail: {:?}", e); + panic!("Write to DB should not fail: {e:?}"); }); true } @@ -367,7 +367,7 @@ where .send(CertifiedBridgeActionExecutionWrapper(certificate, 0)) .await .unwrap_or_else(|e| { - panic!("Sending to execution queue should not fail: {:?}", e); + panic!("Sending to execution queue should not fail: {e:?}"); }); } Err(e) => { @@ -387,7 +387,7 @@ where .send(BridgeActionExecutionWrapper(action, attempt_times + 1)) .await .unwrap_or_else(|e| { - panic!("Sending to signing queue should not fail: {:?}", e); + panic!("Sending to signing queue should not fail: {e:?}"); }); } } @@ -564,7 +564,7 @@ where )) .await .unwrap_or_else(|e| { - panic!("Sending to execution queue should not fail: {:?}", e); + panic!("Sending to execution queue should not fail: {e:?}"); }); info!("Re-enqueued certificate for execution"); }.instrument(tracing::debug_span!("reenqueue_execution_task", action_key=?action_key))); @@ -596,14 +596,13 @@ where || e.type_ == *TokenTransferClaimed.get().unwrap() || e.type_ == *TokenTransferApproved.get().unwrap() || e.type_ == *TokenTransferAlreadyApproved.get().unwrap()), - "Expected TokenTransferAlreadyClaimed, TokenTransferClaimed, TokenTransferApproved or TokenTransferAlreadyApproved event but got: {:?}", - events, + "Expected TokenTransferAlreadyClaimed, TokenTransferClaimed, TokenTransferApproved or TokenTransferAlreadyApproved event but got: {events:?}", ); info!(?tx_digest, "IOTA transaction executed successfully"); store .remove_pending_actions(&[action.digest()]) .unwrap_or_else(|e| { - panic!("Write to DB should not fail: {:?}", e); + panic!("Write to DB should not fail: {e:?}"); }) } IotaExecutionStatus::Failure { error } => { @@ -638,9 +637,7 @@ where assert_eq!( owner, Owner::AddressOwner(iota_address), - "Gas object {:?} is no longer owned by address {}", - gas_object_id, - iota_address + "Gas object {gas_object_id:?} is no longer owned by address {iota_address}" ); (gas_coin, gas_obj_ref) } diff --git a/crates/iota-bridge/src/client/bridge_client.rs b/crates/iota-bridge/src/client/bridge_client.rs index cd65afb4891..8bb812e8151 100644 --- a/crates/iota-bridge/src/client/bridge_client.rs +++ b/crates/iota-bridge/src/client/bridge_client.rs @@ -112,7 +112,7 @@ impl BridgeClient { path } else { let call_data = Hex::encode(a.call_data.clone()); - format!("{}/{}", path, call_data) + format!("{path}/{call_data}") } } BridgeAction::AddTokensOnIotaAction(a) => { @@ -154,7 +154,7 @@ impl BridgeClient { let token_addresses = a .token_addresses .iter() - .map(|name| format!("{:?}", name)) + .map(|name| format!("{name:?}")) .collect::>() .join(","); let token_iota_decimals = a @@ -462,8 +462,7 @@ mod tests { assert_eq!( BridgeClient::bridge_action_to_path(&action), format!( - "sign/bridge_tx/iota/eth/{}/{}", - iota_tx_digest, iota_tx_event_index + "sign/bridge_tx/iota/eth/{iota_tx_digest}/{iota_tx_event_index}" ) ); diff --git a/crates/iota-bridge/src/crypto.rs b/crates/iota-bridge/src/crypto.rs index 2264f418739..489f148a58e 100644 --- a/crates/iota-bridge/src/crypto.rs +++ b/crates/iota-bridge/src/crypto.rs @@ -71,7 +71,7 @@ impl std::str::FromStr for BridgeAuthorityPublicKeyBytes { type Err = FastCryptoError; fn from_str(s: &str) -> Result { let bytes = Hex::decode(s).map_err(|e| { - FastCryptoError::GeneralError(format!("Failed to decode hex string: {}", e)) + FastCryptoError::GeneralError(format!("Failed to decode hex string: {e}")) })?; Self::from_bytes(&bytes) } @@ -82,7 +82,7 @@ pub struct ConciseBridgeAuthorityPublicKeyBytesRef<'a>(&'a BridgeAuthorityPublic impl Debug for ConciseBridgeAuthorityPublicKeyBytesRef<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { let s = Hex::encode(self.0.0.0.get(0..4).ok_or(std::fmt::Error)?); - write!(f, "k#{}..", s) + write!(f, "k#{s}..") } } diff --git a/crates/iota-bridge/src/e2e_tests/test_utils.rs b/crates/iota-bridge/src/e2e_tests/test_utils.rs index a836ae9888f..cb1a4b5e05a 100644 --- a/crates/iota-bridge/src/e2e_tests/test_utils.rs +++ b/crates/iota-bridge/src/e2e_tests/test_utils.rs @@ -450,7 +450,7 @@ pub struct DeployedSolContracts { impl DeployedSolContracts { pub fn eth_address_to_hex(addr: EthAddress) -> String { - format!("{:x}", addr) + format!("{addr:x}") } pub fn iota_bridge_address_hex(&self) -> String { @@ -580,8 +580,8 @@ pub(crate) async fn deploy_sol_contract( status.code() ); } - println!("Stdout: {}", s); - println!("Stdout: {}", e); + println!("Stdout: {s}"); + println!("Stdout: {e}"); let mut deployed_contracts = BTreeMap::new(); // Process the stdout to parse contract addresses diff --git a/crates/iota-bridge/src/eth_client.rs b/crates/iota-bridge/src/eth_client.rs index f70d5d138f0..d563ee7dec5 100644 --- a/crates/iota-bridge/src/eth_client.rs +++ b/crates/iota-bridge/src/eth_client.rs @@ -154,8 +154,7 @@ where // Safeguard check that all events are emitted from requested contract address if logs.iter().any(|log| log.address != address) { return Err(BridgeError::Provider(format!( - "Provider returns logs from different contract address (expected: {:?}): {:?}", - address, logs + "Provider returns logs from different contract address (expected: {address:?}): {logs:?}" ))); } if logs.is_empty() { @@ -204,7 +203,7 @@ where logs.into_iter().map( |log| { if log.address != address { - return Err(BridgeError::Provider(format!("Provider returns logs from different contract address (expected: {:?}): {:?}", address, log))); + return Err(BridgeError::Provider(format!("Provider returns logs from different contract address (expected: {address:?}): {log:?}"))); } Ok(RawEthLog { block_number: log.block_number.ok_or(BridgeError::Provider("Provider returns log without block_number".into()))?.as_u64(), @@ -242,8 +241,7 @@ where .await .map_err(BridgeError::from)? .ok_or(BridgeError::Provider(format!( - "Provide cannot find eth transaction for log: {:?})", - log + "Provide cannot find eth transaction for log: {log:?})" )))?; let receipt_block_num = receipt.block_number.ok_or(BridgeError::Provider( @@ -251,8 +249,7 @@ where ))?; if receipt_block_num.as_u64() != block_number { return Err(BridgeError::Provider(format!( - "Provider returns receipt with different block number from log. Receipt: {:?}, Log: {:?}", - receipt, log + "Provider returns receipt with different block number from log. Receipt: {receipt:?}, Log: {log:?}" ))); } @@ -264,16 +261,14 @@ where // make sure the topics and data match if receipt_log.topics != log.topics || receipt_log.data != log.data { return Err(BridgeError::Provider(format!( - "Provider returns receipt with different log from log. Receipt: {:?}, Log: {:?}", - receipt, log + "Provider returns receipt with different log from log. Receipt: {receipt:?}, Log: {log:?}" ))); } log_index_in_tx = Some(idx); } } let log_index_in_tx = log_index_in_tx.ok_or(BridgeError::Provider(format!( - "Couldn't find matching log: {:?} in transaction {}", - log, tx_hash + "Couldn't find matching log: {log:?} in transaction {tx_hash}" )))?; Ok(EthLog { diff --git a/crates/iota-bridge/src/eth_syncer.rs b/crates/iota-bridge/src/eth_syncer.rs index 027cf75d41a..3a8b68d0d75 100644 --- a/crates/iota-bridge/src/eth_syncer.rs +++ b/crates/iota-bridge/src/eth_syncer.rs @@ -414,10 +414,10 @@ mod tests { assert_eq!(*finalized_block_rx.borrow(), 400); let mut logs_set = HashSet::new(); logs_rx.recv().await.unwrap().2.into_iter().for_each(|log| { - logs_set.insert(format!("{:?}", log)); + logs_set.insert(format!("{log:?}")); }); logs_rx.recv().await.unwrap().2.into_iter().for_each(|log| { - logs_set.insert(format!("{:?}", log)); + logs_set.insert(format!("{log:?}")); }); assert_eq!( logs_set, diff --git a/crates/iota-bridge/src/events.rs b/crates/iota-bridge/src/events.rs index a1335db0cc3..b7f2fe771ab 100644 --- a/crates/iota-bridge/src/events.rs +++ b/crates/iota-bridge/src/events.rs @@ -262,7 +262,7 @@ impl TryFrom for BlocklistValidatorEvent { fn try_from(event: MoveBlocklistValidatorEvent) -> BridgeResult { let public_keys = event.public_keys.into_iter().map(|bytes| BridgeAuthorityPublicKey::from_bytes(&bytes).map_err(|e| - BridgeError::Generic(format!("Failed to convert MoveBlocklistValidatorEvent to BlocklistValidatorEvent. Failed to convert public key to BridgeAuthorityPublicKey: {:?}", e)) + BridgeError::Generic(format!("Failed to convert MoveBlocklistValidatorEvent to BlocklistValidatorEvent. Failed to convert public key to BridgeAuthorityPublicKey: {e:?}")) ) ).collect::>>()?; Ok(Self { @@ -284,10 +284,10 @@ impl TryFrom for CommitteeMemberUrlUpdateEven fn try_from(event: MoveCommitteeMemberUrlUpdateEvent) -> BridgeResult { let member = BridgeAuthorityPublicKey::from_bytes(&event.member).map_err(|e| - BridgeError::Generic(format!("Failed to convert MoveBlocklistValidatorEvent to BlocklistValidatorEvent. Failed to convert public key to BridgeAuthorityPublicKey: {:?}", e)) + BridgeError::Generic(format!("Failed to convert MoveBlocklistValidatorEvent to BlocklistValidatorEvent. Failed to convert public key to BridgeAuthorityPublicKey: {e:?}")) )?; let new_url = String::from_utf8(event.new_url).map_err(|e| - BridgeError::Generic(format!("Failed to convert MoveBlocklistValidatorEvent to BlocklistValidatorEvent. Failed to convert new_url to String: {:?}", e)) + BridgeError::Generic(format!("Failed to convert MoveBlocklistValidatorEvent to BlocklistValidatorEvent. Failed to convert new_url to String: {e:?}")) )?; Ok(Self { member, new_url }) } @@ -299,8 +299,7 @@ impl TryFrom for EmittedIotaToEthTokenBridgeV1 { fn try_from(event: MoveTokenDepositedEvent) -> BridgeResult { if event.amount_iota_adjusted == 0 { return Err(BridgeError::ZeroValueBridgeTransfer(format!( - "Failed to convert MoveTokenDepositedEvent to EmittedIotaToEthTokenBridgeV1. Manual intervention is required. 0 value transfer should not be allowed in Move: {:?}", - event, + "Failed to convert MoveTokenDepositedEvent to EmittedIotaToEthTokenBridgeV1. Manual intervention is required. 0 value transfer should not be allowed in Move: {event:?}", ))); } @@ -331,7 +330,7 @@ impl TryFrom for EmittedIotaToEthTokenBridgeV1 { } let iota_address = IotaAddress::from_bytes(event.sender_address) - .map_err(|e| BridgeError::Generic(format!("Failed to convert MoveTokenDepositedEvent to EmittedIotaToEthTokenBridgeV1. Failed to convert sender_address to IotaAddress: {:?}", e)))?; + .map_err(|e| BridgeError::Generic(format!("Failed to convert MoveTokenDepositedEvent to EmittedIotaToEthTokenBridgeV1. Failed to convert sender_address to IotaAddress: {e:?}")))?; let eth_address = EthAddress::from_str(&Hex::encode(&event.target_address))?; Ok(Self { @@ -537,7 +536,7 @@ pub mod tests { IotaBridgeEvent::CommitteeUpdateEvent(_event) => mask |= 0x2, IotaBridgeEvent::TokenRegistrationEvent(_event) => mask |= 0x4, IotaBridgeEvent::NewTokenEvent(_event) => mask |= 0x8, - _ => panic!("Got unexpected event: {:?}", event), + _ => panic!("Got unexpected event: {event:?}"), } } // assert all the above events are emitted @@ -589,7 +588,7 @@ pub mod tests { }; match EmittedIotaToEthTokenBridgeV1::try_from(emitted_event).unwrap_err() { BridgeError::ZeroValueBridgeTransfer(_) => (), - other => panic!("Expected Generic error, got: {:?}", other), + other => panic!("Expected Generic error, got: {other:?}"), } } } diff --git a/crates/iota-bridge/src/iota_client.rs b/crates/iota-bridge/src/iota_client.rs index 02e1562d02a..67d359705f9 100644 --- a/crates/iota-bridge/src/iota_client.rs +++ b/crates/iota-bridge/src/iota_client.rs @@ -593,25 +593,21 @@ where } = resp; let Some(results) = results else { return Err(BridgeError::Generic(format!( - "No results returned for '{}', effects: {:?}", - function_name, effects + "No results returned for '{function_name}', effects: {effects:?}" ))); }; let return_values = &results .first() .ok_or(BridgeError::Generic(format!( - "No return values for '{}', results: {:?}", - function_name, results + "No return values for '{function_name}', results: {results:?}" )))? .return_values; let (value_bytes, _type_tag) = return_values.first().ok_or(BridgeError::Generic(format!( - "No first return value for '{}', results: {:?}", - function_name, results + "No first return value for '{function_name}', results: {results:?}" )))?; bcs::from_bytes::(value_bytes).map_err(|e| { BridgeError::Generic(format!( - "Failed to parse return value for '{}', error: {:?}, results: {:?}", - function_name, e, results + "Failed to parse return value for '{function_name}', error: {e:?}, results: {results:?}" )) }) } diff --git a/crates/iota-bridge/src/iota_mock_client.rs b/crates/iota-bridge/src/iota_mock_client.rs index c7738276cda..d851303a1e1 100644 --- a/crates/iota-bridge/src/iota_mock_client.rs +++ b/crates/iota-bridge/src/iota_mock_client.rs @@ -169,8 +169,7 @@ impl IotaClientInner for IotaMockClient { .cloned() .unwrap_or_else(|| { panic!( - "No preset events found for package: {:?}, module: {:?}, cursor: {:?}", - package, module, cursor + "No preset events found for package: {package:?}, module: {module:?}, cursor: {cursor:?}" ) })) } @@ -186,7 +185,7 @@ impl IotaClientInner for IotaMockClient { match events .get(&tx_digest) - .unwrap_or_else(|| panic!("No preset events found for tx_digest: {:?}", tx_digest)) + .unwrap_or_else(|| panic!("No preset events found for tx_digest: {tx_digest:?}")) { Ok(events) => Ok(events.clone()), // iota_sdk::error::Error is not Clone @@ -274,7 +273,7 @@ impl IotaClientInner for IotaMockClient { .lock() .unwrap() .clone() - .unwrap_or_else(|| panic!("No preset transaction response found for tx: {:?}", tx)), + .unwrap_or_else(|| panic!("No preset transaction response found for tx: {tx:?}")), } } @@ -289,8 +288,7 @@ impl IotaClientInner for IotaMockClient { .cloned() .unwrap_or_else(|| { panic!( - "No preset gas object info found for gas_object_id: {:?}", - gas_object_id + "No preset gas object info found for gas_object_id: {gas_object_id:?}" ) }) } diff --git a/crates/iota-bridge/src/iota_syncer.rs b/crates/iota-bridge/src/iota_syncer.rs index fbfaa506cdf..3d389046400 100644 --- a/crates/iota-bridge/src/iota_syncer.rs +++ b/crates/iota-bridge/src/iota_syncer.rs @@ -213,7 +213,7 @@ mod tests { ) { match timeout(interval * 2, events_rx.recv()).await { Err(_e) => (), - other => panic!("Should have timed out, but got: {:?}", other), + other => panic!("Should have timed out, but got: {other:?}"), }; } diff --git a/crates/iota-bridge/src/iota_transaction_builder.rs b/crates/iota-bridge/src/iota_transaction_builder.rs index 396f1d1bd0f..dc1df53f9bd 100644 --- a/crates/iota-bridge/src/iota_transaction_builder.rs +++ b/crates/iota-bridge/src/iota_transaction_builder.rs @@ -142,15 +142,13 @@ fn build_token_bridge_approve_transaction( let seq_num = builder.pure(seq_num).unwrap(); let sender = builder.pure(sender.clone()).map_err(|e| { BridgeError::BridgeSerialization(format!( - "Failed to serialize sender: {:?}. Err: {:?}", - sender, e + "Failed to serialize sender: {sender:?}. Err: {e:?}" )) })?; let target_chain = builder.pure(target_chain as u8).unwrap(); let target = builder.pure(target.clone()).map_err(|e| { BridgeError::BridgeSerialization(format!( - "Failed to serialize target: {:?}. Err: {:?}", - target, e + "Failed to serialize target: {target:?}. Err: {e:?}" )) })?; let arg_token_type = builder.pure(token_type).unwrap(); @@ -182,8 +180,7 @@ fn build_token_bridge_approve_transaction( } let arg_signatures = builder.pure(sig_bytes.clone()).map_err(|e| { BridgeError::BridgeSerialization(format!( - "Failed to serialize signatures: {:?}. Err: {:?}", - sig_bytes, e + "Failed to serialize signatures: {sig_bytes:?}. Err: {e:?}" )) })?; @@ -257,8 +254,7 @@ fn build_emergency_op_approve_transaction( } let arg_signatures = builder.pure(sig_bytes.clone()).map_err(|e| { BridgeError::BridgeSerialization(format!( - "Failed to serialize signatures: {:?}. Err: {:?}", - sig_bytes, e + "Failed to serialize signatures: {sig_bytes:?}. Err: {e:?}" )) })?; @@ -324,8 +320,7 @@ fn build_committee_blocklist_approve_transaction( } let arg_signatures = builder.pure(sig_bytes.clone()).map_err(|e| { BridgeError::BridgeSerialization(format!( - "Failed to serialize signatures: {:?}. Err: {:?}", - sig_bytes, e + "Failed to serialize signatures: {sig_bytes:?}. Err: {e:?}" )) })?; @@ -387,8 +382,7 @@ fn build_limit_update_approve_transaction( } let arg_signatures = builder.pure(sig_bytes.clone()).map_err(|e| { BridgeError::BridgeSerialization(format!( - "Failed to serialize signatures: {:?}. Err: {:?}", - sig_bytes, e + "Failed to serialize signatures: {sig_bytes:?}. Err: {e:?}" )) })?; @@ -450,8 +444,7 @@ fn build_asset_price_update_approve_transaction( } let arg_signatures = builder.pure(sig_bytes.clone()).map_err(|e| { BridgeError::BridgeSerialization(format!( - "Failed to serialize signatures: {:?}. Err: {:?}", - sig_bytes, e + "Failed to serialize signatures: {sig_bytes:?}. Err: {e:?}" )) })?; diff --git a/crates/iota-bridge/src/node.rs b/crates/iota-bridge/src/node.rs index d103e8c9e18..cd8f113baad 100644 --- a/crates/iota-bridge/src/node.rs +++ b/crates/iota-bridge/src/node.rs @@ -448,7 +448,7 @@ mod tests { .await .unwrap(); - let server_url = format!("http://127.0.0.1:{}", server_listen_port); + let server_url = format!("http://127.0.0.1:{server_listen_port}"); // Now we expect to see the server to be up and running. let res = wait_for_server_to_be_up(server_url, 5).await; res.unwrap(); @@ -512,7 +512,7 @@ mod tests { .await .unwrap(); - let server_url = format!("http://127.0.0.1:{}", server_listen_port); + let server_url = format!("http://127.0.0.1:{server_listen_port}"); // Now we expect to see the server to be up and running. // client components are spawned earlier than server, so as long as the server // is up, we know the client components are already running. @@ -587,7 +587,7 @@ mod tests { .await .unwrap(); - let server_url = format!("http://127.0.0.1:{}", server_listen_port); + let server_url = format!("http://127.0.0.1:{server_listen_port}"); // Now we expect to see the server to be up and running. // client components are spawned earlier than server, so as long as the server // is up, we know the client components are already running. diff --git a/crates/iota-bridge/src/orchestrator.rs b/crates/iota-bridge/src/orchestrator.rs index 16b1639db62..18ece1417a5 100644 --- a/crates/iota-bridge/src/orchestrator.rs +++ b/crates/iota-bridge/src/orchestrator.rs @@ -134,8 +134,7 @@ where } Err(e) => { panic!( - "IOTA Event could not be deserialized to IotaBridgeEvent: {:?}", - e + "IOTA Event could not be deserialized to IotaBridgeEvent: {e:?}" ); } } diff --git a/crates/iota-bridge/src/server/mock_handler.rs b/crates/iota-bridge/src/server/mock_handler.rs index 39505eba88f..a9c3d831194 100644 --- a/crates/iota-bridge/src/server/mock_handler.rs +++ b/crates/iota-bridge/src/server/mock_handler.rs @@ -101,8 +101,7 @@ impl BridgeRequestHandlerTrait for BridgeRequestMockHandler { if !preset.contains_key(&(tx_digest, event_idx)) { // Ok to panic in test panic!( - "No preset handle_iota_tx_digest result for tx_digest: {}, event_idx: {}", - tx_digest, event_idx + "No preset handle_iota_tx_digest result for tx_digest: {tx_digest}, event_idx: {event_idx}" ); } let mut requested = self.iota_token_events_requested.lock().unwrap(); diff --git a/crates/iota-bridge/src/server/mod.rs b/crates/iota-bridge/src/server/mod.rs index a6affca3caf..c7e61f9c961 100644 --- a/crates/iota-bridge/src/server/mod.rs +++ b/crates/iota-bridge/src/server/mod.rs @@ -133,7 +133,7 @@ impl axum::response::IntoResponse for BridgeError { fn into_response(self) -> axum::response::Response { ( StatusCode::INTERNAL_SERVER_ERROR, - format!("Something went wrong: {:?}", self), + format!("Something went wrong: {self:?}"), ) .into_response() } @@ -207,12 +207,11 @@ async fn handle_update_committee_blocklist_action( ) -> Result, BridgeError> { let future = async { let chain_id = BridgeChainId::try_from(chain_id).map_err(|err| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {:?}", err)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {err:?}")) })?; let blocklist_type = BlocklistType::try_from(blocklist_type).map_err(|err| { BridgeError::InvalidBridgeClientRequest(format!( - "Invalid blocklist action type: {:?}", - err + "Invalid blocklist action type: {err:?}" )) })?; let members_to_update = keys @@ -223,7 +222,7 @@ async fn handle_update_committee_blocklist_action( .map_err(|e| anyhow::anyhow!("{:?}", e)) }) .collect::, _>>() - .map_err(|e| BridgeError::InvalidBridgeClientRequest(format!("{:?}", e)))?; + .map_err(|e| BridgeError::InvalidBridgeClientRequest(format!("{e:?}")))?; let action = BridgeAction::BlocklistCommitteeAction(BlocklistCommitteeAction { chain_id, nonce, @@ -253,12 +252,11 @@ async fn handle_emergency_action( ) -> Result, BridgeError> { let future = async { let chain_id = BridgeChainId::try_from(chain_id).map_err(|err| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {:?}", err)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {err:?}")) })?; let action_type = EmergencyActionType::try_from(action_type).map_err(|err| { BridgeError::InvalidBridgeClientRequest(format!( - "Invalid emergency action type: {:?}", - err + "Invalid emergency action type: {err:?}" )) })?; let action = BridgeAction::EmergencyAction(EmergencyAction { @@ -283,10 +281,10 @@ async fn handle_limit_update_action( ) -> Result, BridgeError> { let future = async { let chain_id = BridgeChainId::try_from(chain_id).map_err(|err| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {:?}", err)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {err:?}")) })?; let sending_chain_id = BridgeChainId::try_from(sending_chain_id).map_err(|err| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {:?}", err)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {err:?}")) })?; let action = BridgeAction::LimitUpdateAction(LimitUpdateAction { chain_id, @@ -311,7 +309,7 @@ async fn handle_asset_price_update_action( ) -> Result, BridgeError> { let future = async { let chain_id = BridgeChainId::try_from(chain_id).map_err(|err| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {:?}", err)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {err:?}")) })?; let action = BridgeAction::AssetPriceUpdateAction(AssetPriceUpdateAction { chain_id, @@ -342,10 +340,10 @@ async fn handle_evm_contract_upgrade_with_calldata( ) -> Result, BridgeError> { let future = async { let chain_id = BridgeChainId::try_from(chain_id).map_err(|err| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {:?}", err)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {err:?}")) })?; let call_data = Hex::decode(&calldata).map_err(|e| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid call data: {:?}", e)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid call data: {e:?}")) })?; let action = BridgeAction::EvmContractUpgradeAction(EvmContractUpgradeAction { chain_id, @@ -385,7 +383,7 @@ async fn handle_evm_contract_upgrade( ) -> Result, BridgeError> { let future = async { let chain_id = BridgeChainId::try_from(chain_id).map_err(|err| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {:?}", err)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {err:?}")) })?; let action = BridgeAction::EvmContractUpgradeAction(EvmContractUpgradeAction { chain_id, @@ -419,7 +417,7 @@ async fn handle_add_tokens_on_iota( ) -> Result, BridgeError> { let future = async { let chain_id = BridgeChainId::try_from(chain_id).map_err(|err| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {:?}", err)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {err:?}")) })?; if !chain_id.is_iota_chain() { @@ -433,8 +431,7 @@ async fn handle_add_tokens_on_iota( 0 => false, _ => { return Err(BridgeError::InvalidBridgeClientRequest(format!( - "Invalid native flag: {}", - native + "Invalid native flag: {native}" ))); } }; @@ -442,7 +439,7 @@ async fn handle_add_tokens_on_iota( .split(',') .map(|s| { s.parse::().map_err(|err| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid token id: {:?}", err)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid token id: {err:?}")) }) }) .collect::, _>>()?; @@ -451,8 +448,7 @@ async fn handle_add_tokens_on_iota( .map(|s| { TypeTag::from_str(s).map_err(|err| { BridgeError::InvalidBridgeClientRequest(format!( - "Invalid token type name: {:?}", - err + "Invalid token type name: {err:?}" )) }) }) @@ -462,8 +458,7 @@ async fn handle_add_tokens_on_iota( .map(|s| { s.parse::().map_err(|err| { BridgeError::InvalidBridgeClientRequest(format!( - "Invalid token price: {:?}", - err + "Invalid token price: {err:?}" )) }) }) @@ -501,7 +496,7 @@ async fn handle_add_tokens_on_evm( ) -> Result, BridgeError> { let future = async { let chain_id = BridgeChainId::try_from(chain_id).map_err(|err| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {:?}", err)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid chain id: {err:?}")) })?; if chain_id.is_iota_chain() { return Err(BridgeError::InvalidBridgeClientRequest( @@ -514,8 +509,7 @@ async fn handle_add_tokens_on_evm( 0 => false, _ => { return Err(BridgeError::InvalidBridgeClientRequest(format!( - "Invalid native flag: {}", - native + "Invalid native flag: {native}" ))); } }; @@ -523,7 +517,7 @@ async fn handle_add_tokens_on_evm( .split(',') .map(|s| { s.parse::().map_err(|err| { - BridgeError::InvalidBridgeClientRequest(format!("Invalid token id: {:?}", err)) + BridgeError::InvalidBridgeClientRequest(format!("Invalid token id: {err:?}")) }) }) .collect::, _>>()?; @@ -532,8 +526,7 @@ async fn handle_add_tokens_on_evm( .map(|s| { EthAddress::from_str(s).map_err(|err| { BridgeError::InvalidBridgeClientRequest(format!( - "Invalid token address: {:?}", - err + "Invalid token address: {err:?}" )) }) }) @@ -543,8 +536,7 @@ async fn handle_add_tokens_on_evm( .map(|s| { s.parse::().map_err(|err| { BridgeError::InvalidBridgeClientRequest(format!( - "Invalid token iota decimals: {:?}", - err + "Invalid token iota decimals: {err:?}" )) }) }) @@ -554,8 +546,7 @@ async fn handle_add_tokens_on_evm( .map(|s| { s.parse::().map_err(|err| { BridgeError::InvalidBridgeClientRequest(format!( - "Invalid token price: {:?}", - err + "Invalid token price: {err:?}" )) }) }) diff --git a/crates/iota-bridge/src/storage.rs b/crates/iota-bridge/src/storage.rs index 13a4e4c9b20..aa3131a2166 100644 --- a/crates/iota-bridge/src/storage.rs +++ b/crates/iota-bridge/src/storage.rs @@ -44,11 +44,11 @@ impl BridgeOrchestratorTables { actions.iter().map(|a| (a.digest(), a)), ) .map_err(|e| { - BridgeError::Storage(format!("Couldn't insert into pending_actions: {:?}", e)) + BridgeError::Storage(format!("Couldn't insert into pending_actions: {e:?}")) })?; batch .write() - .map_err(|e| BridgeError::Storage(format!("Couldn't write batch: {:?}", e))) + .map_err(|e| BridgeError::Storage(format!("Couldn't write batch: {e:?}"))) } pub(crate) fn remove_pending_actions( @@ -59,11 +59,11 @@ impl BridgeOrchestratorTables { batch .delete_batch(&self.pending_actions, actions) .map_err(|e| { - BridgeError::Storage(format!("Couldn't delete from pending_actions: {:?}", e)) + BridgeError::Storage(format!("Couldn't delete from pending_actions: {e:?}")) })?; batch .write() - .map_err(|e| BridgeError::Storage(format!("Couldn't write batch: {:?}", e))) + .map_err(|e| BridgeError::Storage(format!("Couldn't write batch: {e:?}"))) } pub(crate) fn update_iota_event_cursor( @@ -76,11 +76,11 @@ impl BridgeOrchestratorTables { batch .insert_batch(&self.iota_syncer_cursors, [(module, cursor)]) .map_err(|e| { - BridgeError::Storage(format!("Couldn't insert into iota_syncer_cursors: {:?}", e)) + BridgeError::Storage(format!("Couldn't insert into iota_syncer_cursors: {e:?}")) })?; batch .write() - .map_err(|e| BridgeError::Storage(format!("Couldn't write batch: {:?}", e))) + .map_err(|e| BridgeError::Storage(format!("Couldn't write batch: {e:?}"))) } pub(crate) fn update_eth_event_cursor( @@ -93,11 +93,11 @@ impl BridgeOrchestratorTables { batch .insert_batch(&self.eth_syncer_cursors, [(contract_address, cursor)]) .map_err(|e| { - BridgeError::Storage(format!("Couldn't insert into eth_syncer_cursors: {:?}", e)) + BridgeError::Storage(format!("Couldn't insert into eth_syncer_cursors: {e:?}")) })?; batch .write() - .map_err(|e| BridgeError::Storage(format!("Couldn't write batch: {:?}", e))) + .map_err(|e| BridgeError::Storage(format!("Couldn't write batch: {e:?}"))) } pub fn get_all_pending_actions(&self) -> HashMap { @@ -110,7 +110,7 @@ impl BridgeOrchestratorTables { ) -> BridgeResult>> { self.iota_syncer_cursors .multi_get(identifiers) - .map_err(|e| BridgeError::Storage(format!("Couldn't get iota_syncer_cursors: {:?}", e))) + .map_err(|e| BridgeError::Storage(format!("Couldn't get iota_syncer_cursors: {e:?}"))) } pub fn get_eth_event_cursors( @@ -119,7 +119,7 @@ impl BridgeOrchestratorTables { ) -> BridgeResult>> { self.eth_syncer_cursors .multi_get(contract_addresses) - .map_err(|e| BridgeError::Storage(format!("Couldn't get iota_syncer_cursors: {:?}", e))) + .map_err(|e| BridgeError::Storage(format!("Couldn't get iota_syncer_cursors: {e:?}"))) } } diff --git a/crates/iota-bridge/src/test_utils.rs b/crates/iota-bridge/src/test_utils.rs index 145386c27ff..3e2d9f20d8e 100644 --- a/crates/iota-bridge/src/test_utils.rs +++ b/crates/iota-bridge/src/test_utils.rs @@ -68,7 +68,7 @@ pub fn get_test_authority_and_key( let authority = BridgeAuthority { pubkey: pubkey.clone(), voting_power, - base_url: format!("http://127.0.0.1:{}", port), + base_url: format!("http://127.0.0.1:{port}"), is_blocklisted: false, }; @@ -393,8 +393,7 @@ pub async fn approve_action_with_validator_secrets( } } panic!( - "Didn't find the created object owned by {}", - expected_token_receiver + "Didn't find the created object owned by {expected_token_receiver}" ); } diff --git a/crates/iota-bridge/src/utils.rs b/crates/iota-bridge/src/utils.rs index 4f342e6c4ff..5579fcd99e4 100644 --- a/crates/iota-bridge/src/utils.rs +++ b/crates/iota-bridge/src/utils.rs @@ -62,13 +62,11 @@ pub fn generate_bridge_authority_key_and_write_to_file( let (_, kp): (_, BridgeAuthorityKeyPair) = get_key_pair(); let eth_address = BridgeAuthorityPublicKeyBytes::from(&kp.public).to_eth_address(); println!( - "Corresponding Ethereum address by this ecdsa key: {:?}", - eth_address + "Corresponding Ethereum address by this ecdsa key: {eth_address:?}" ); let iota_address = IotaAddress::from(&kp.public); println!( - "Corresponding IOTA address by this ecdsa key: {:?}", - iota_address + "Corresponding IOTA address by this ecdsa key: {iota_address:?}" ); let base64_encoded = kp.encode_base64(); std::fs::write(path, base64_encoded) @@ -85,8 +83,7 @@ pub fn generate_bridge_client_key_and_write_to_file( let (_, kp): (_, Secp256k1KeyPair) = get_key_pair(); let eth_address = BridgeAuthorityPublicKeyBytes::from(&kp.public).to_eth_address(); println!( - "Corresponding Ethereum address by this ecdsa key: {:?}", - eth_address + "Corresponding Ethereum address by this ecdsa key: {eth_address:?}" ); IotaKeyPair::from(kp) } else { @@ -94,7 +91,7 @@ pub fn generate_bridge_client_key_and_write_to_file( IotaKeyPair::from(kp) }; let iota_address = IotaAddress::from(&kp.public()); - println!("Corresponding IOTA address by this key: {:?}", iota_address); + println!("Corresponding IOTA address by this key: {iota_address:?}"); let contents = kp.encode_base64(); std::fs::write(path, contents) @@ -156,7 +153,7 @@ pub fn examine_key(path: &PathBuf, is_validator_key: bool) -> Result<(), anyhow: IotaKeyPair::Secp256k1(kp) => { println!("Secp256k1 key:"); let eth_address = BridgeAuthorityPublicKeyBytes::from(&kp.public).to_eth_address(); - println!("Corresponding Ethereum address: {:x}", eth_address); + println!("Corresponding Ethereum address: {eth_address:x}"); kp.public.as_bytes().to_vec() } IotaKeyPair::Ed25519(kp) => { @@ -168,7 +165,7 @@ pub fn examine_key(path: &PathBuf, is_validator_key: bool) -> Result<(), anyhow: kp.public().as_bytes().to_vec() } }; - println!("Corresponding IOTA address: {:?}", iota_address); + println!("Corresponding IOTA address: {iota_address:?}"); println!("Corresponding PublicKey: {:?}", Hex::encode(pubkey)); Ok(()) } diff --git a/crates/iota-cluster-test/src/cluster.rs b/crates/iota-cluster-test/src/cluster.rs index aac92a227f4..e4dcb9221b1 100644 --- a/crates/iota-cluster-test/src/cluster.rs +++ b/crates/iota-cluster-test/src/cluster.rs @@ -185,8 +185,7 @@ impl Cluster for LocalNewCluster { committee_with_network: _, } = PersistedConfig::read(&network_config_path).map_err(|err| { err.context(format!( - "Cannot open IOTA network config file at {:?}", - network_config_path + "Cannot open IOTA network config file at {network_config_path:?}" )) })?; @@ -384,8 +383,7 @@ pub fn new_wallet_context_from_cluster( WalletContext::new(&wallet_config_path, None, None).unwrap_or_else(|e| { panic!( - "Failed to init wallet context from path {:?}, error: {e}", - wallet_config_path + "Failed to init wallet context from path {wallet_config_path:?}, error: {e}" ) }) } diff --git a/crates/iota-cluster-test/src/faucet.rs b/crates/iota-cluster-test/src/faucet.rs index a3874c53020..4aa6c0769cb 100644 --- a/crates/iota-cluster-test/src/faucet.rs +++ b/crates/iota-cluster-test/src/faucet.rs @@ -91,14 +91,14 @@ impl FaucetClient for RemoteFaucetClient { .json(&map) .send() .await - .unwrap_or_else(|e| panic!("Failed to talk to remote faucet {:?}: {:?}", gas_url, e)); + .unwrap_or_else(|e| panic!("Failed to talk to remote faucet {gas_url:?}: {e:?}")); let full_bytes = response.bytes().await.unwrap(); let faucet_response: FaucetResponse = serde_json::from_slice(&full_bytes) .map_err(|e| anyhow::anyhow!("json deser failed with bytes {:?}: {e}", full_bytes)) .unwrap(); if let Some(error) = faucet_response.error { - panic!("Failed to get gas tokens with error: {}", error) + panic!("Failed to get gas tokens with error: {error}") }; faucet_response @@ -120,14 +120,14 @@ impl FaucetClient for RemoteFaucetClient { .json(&map) .send() .await - .unwrap_or_else(|e| panic!("Failed to talk to remote faucet {:?}: {:?}", gas_url, e)); + .unwrap_or_else(|e| panic!("Failed to talk to remote faucet {gas_url:?}: {e:?}")); let full_bytes = response.bytes().await.unwrap(); let faucet_response: BatchFaucetResponse = serde_json::from_slice(&full_bytes) .map_err(|e| anyhow::anyhow!("json deser failed with bytes {:?}: {e}", full_bytes)) .unwrap(); if let Some(error) = faucet_response.error { - panic!("Failed to get gas tokens with error: {}", error) + panic!("Failed to get gas tokens with error: {error}") }; faucet_response @@ -151,7 +151,7 @@ impl FaucetClient for RemoteFaucetClient { .send() .await .unwrap_or_else(|e| { - panic!("Failed to talk to remote faucet {:?}: {:?}", status_url, e) + panic!("Failed to talk to remote faucet {status_url:?}: {e:?}") }); let full_bytes = response.bytes().await.unwrap(); let faucet_response: BatchStatusFaucetResponse = serde_json::from_slice(&full_bytes) @@ -180,7 +180,7 @@ impl FaucetClient for LocalFaucetClient { .simple_faucet .send(Uuid::new_v4(), request_address, &[200_000_000_000; 5]) .await - .unwrap_or_else(|err| panic!("Failed to get gas tokens with error: {}", err)); + .unwrap_or_else(|err| panic!("Failed to get gas tokens with error: {err}")); receipt.into() } @@ -189,7 +189,7 @@ impl FaucetClient for LocalFaucetClient { .simple_faucet .batch_send(Uuid::new_v4(), request_address, &[200_000_000_000; 5]) .await - .unwrap_or_else(|err| panic!("Failed to get gas tokens with error: {}", err)); + .unwrap_or_else(|err| panic!("Failed to get gas tokens with error: {err}")); receipt.into() } @@ -198,7 +198,7 @@ impl FaucetClient for LocalFaucetClient { .simple_faucet .get_batch_send_status(task_id) .await - .unwrap_or_else(|err| panic!("Failed to get gas tokens with error: {}", err)); + .unwrap_or_else(|err| panic!("Failed to get gas tokens with error: {err}")); status.into() } diff --git a/crates/iota-cluster-test/src/helper.rs b/crates/iota-cluster-test/src/helper.rs index 2d60b4683f3..95707b3a714 100644 --- a/crates/iota-cluster-test/src/helper.rs +++ b/crates/iota-cluster-test/src/helper.rs @@ -114,31 +114,30 @@ impl ObjectChecker { }), ) => { if !self.is_deleted { - panic!("Gas object {} was deleted", object_id); + panic!("Gas object {object_id} was deleted"); } Ok(CheckerResultObject::new(None, None)) } (Some(object), _) => { if self.is_deleted { - panic!("Expect Gas object {} deleted, but it is not", object_id); + panic!("Expect Gas object {object_id} deleted, but it is not"); } if let Some(owner) = self.owner { let object_owner = object .owner - .unwrap_or_else(|| panic!("Object {} does not have owner", object_id)); + .unwrap_or_else(|| panic!("Object {object_id} does not have owner")); assert_eq!( object_owner, owner, - "Gas coin {} does not belong to {}, but {}", - object_id, owner, object_owner + "Gas coin {object_id} does not belong to {owner}, but {object_owner}" ); } if self.is_iota_coin == Some(true) { let move_obj = object .bcs .as_ref() - .unwrap_or_else(|| panic!("Object {} does not have bcs data", object_id)) + .unwrap_or_else(|| panic!("Object {object_id} does not have bcs data")) .try_as_move() - .unwrap_or_else(|| panic!("Object {} is not a move object", object_id)); + .unwrap_or_else(|| panic!("Object {object_id} is not a move object")); let gas_coin = move_obj.deserialize()?; return Ok(CheckerResultObject::new(Some(gas_coin), Some(object))); diff --git a/crates/iota-cluster-test/src/lib.rs b/crates/iota-cluster-test/src/lib.rs index 89a55318af0..5977f5679d2 100644 --- a/crates/iota-cluster-test/src/lib.rs +++ b/crates/iota-cluster-test/src/lib.rs @@ -166,14 +166,13 @@ impl TestContext { Some(ExecuteTransactionRequestType::WaitForLocalExecution), ) .await - .unwrap_or_else(|e| panic!("Failed to execute transaction for {}. {}", desc, e)); + .unwrap_or_else(|e| panic!("Failed to execute transaction for {desc}. {e}")); assert!( matches!( resp.effects.as_ref().unwrap().status(), IotaExecutionStatus::Success ), - "Failed to execute transaction for {desc}: {:?}", - resp + "Failed to execute transaction for {desc}: {resp:?}" ); resp } @@ -203,7 +202,7 @@ impl TestContext { loop { tokio::select! { _ = &mut sleep => { - panic!("Fullnode does not know all of {:?} after {} secs.", digests, timeout_sec); + panic!("Fullnode does not know all of {digests:?} after {timeout_sec} secs."); } res = futures.next() => { match res { diff --git a/crates/iota-cluster-test/src/test_case/fullnode_execute_transaction_test.rs b/crates/iota-cluster-test/src/test_case/fullnode_execute_transaction_test.rs index 6562f96575e..d21b9cb53fe 100644 --- a/crates/iota-cluster-test/src/test_case/fullnode_execute_transaction_test.rs +++ b/crates/iota-cluster-test/src/test_case/fullnode_execute_transaction_test.rs @@ -24,8 +24,7 @@ impl FullNodeExecuteTransactionTest { .await .unwrap_or_else(|e| { panic!( - "Failed get transaction {:?} from fullnode: {:?}", - tx_digest, e + "Failed get transaction {tx_digest:?} from fullnode: {e:?}" ) }); } diff --git a/crates/iota-cluster-test/src/wallet_client.rs b/crates/iota-cluster-test/src/wallet_client.rs index 1221395ec79..be52ea6451e 100644 --- a/crates/iota-cluster-test/src/wallet_client.rs +++ b/crates/iota-cluster-test/src/wallet_client.rs @@ -61,6 +61,6 @@ impl WalletClient { .config() .keystore() .sign_secure(&self.address, txn_data, Intent::iota_transaction()) - .unwrap_or_else(|e| panic!("Failed to sign transaction for {}. {}", desc, e)) + .unwrap_or_else(|e| panic!("Failed to sign transaction for {desc}. {e}")) } } diff --git a/crates/iota-cluster-test/tests/local_cluster_test.rs b/crates/iota-cluster-test/tests/local_cluster_test.rs index 2124fb6365d..11357190d8a 100644 --- a/crates/iota-cluster-test/tests/local_cluster_test.rs +++ b/crates/iota-cluster-test/tests/local_cluster_test.rs @@ -29,9 +29,9 @@ async fn test_iota_cluster() { let opts = ClusterTestOpt { env: Env::NewLocal, faucet_address: None, - fullnode_address: Some(format!("127.0.0.1:{}", fullnode_rpc_port)), + fullnode_address: Some(format!("127.0.0.1:{fullnode_rpc_port}")), epoch_duration_ms: Some(60000), - indexer_address: Some(format!("127.0.0.1:{}", indexer_rpc_port)), + indexer_address: Some(format!("127.0.0.1:{indexer_rpc_port}")), pg_address: Some(pg_address), config_dir: None, graphql_address: Some(graphql_address), diff --git a/crates/iota-config/src/lib.rs b/crates/iota-config/src/lib.rs index f07a427f145..0483f2850c1 100644 --- a/crates/iota-config/src/lib.rs +++ b/crates/iota-config/src/lib.rs @@ -76,17 +76,17 @@ pub fn genesis_blob_exists(config_dir: Option) -> bool { } pub fn validator_config_file(address: Multiaddr, i: usize) -> String { - multiaddr_to_filename(address).unwrap_or(format!("validator-config-{}.yaml", i)) + multiaddr_to_filename(address).unwrap_or(format!("validator-config-{i}.yaml")) } pub fn ssfn_config_file(address: Multiaddr, i: usize) -> String { - multiaddr_to_filename(address).unwrap_or(format!("ssfn-config-{}.yaml", i)) + multiaddr_to_filename(address).unwrap_or(format!("ssfn-config-{i}.yaml")) } fn multiaddr_to_filename(address: Multiaddr) -> Option { if let Some(hostname) = address.hostname() { if let Some(port) = address.port() { - return Some(format!("{}-{}.yaml", hostname, port)); + return Some(format!("{hostname}-{port}.yaml")); } } None diff --git a/crates/iota-config/src/node.rs b/crates/iota-config/src/node.rs index 2e216825a21..b997b233db2 100644 --- a/crates/iota-config/src/node.rs +++ b/crates/iota-config/src/node.rs @@ -378,8 +378,7 @@ impl NodeConfig { match self.protocol_key_pair.keypair() { IotaKeyPair::Ed25519(kp) => kp, other => panic!( - "invalid keypair type: {:?}, only Ed25519 is allowed for protocol key", - other + "invalid keypair type: {other:?}, only Ed25519 is allowed for protocol key" ), } } @@ -388,8 +387,7 @@ impl NodeConfig { match self.network_key_pair.keypair() { IotaKeyPair::Ed25519(kp) => kp, other => panic!( - "invalid keypair type: {:?}, only Ed25519 is allowed for network key", - other + "invalid keypair type: {other:?}, only Ed25519 is allowed for network key" ), } } @@ -1056,7 +1054,7 @@ impl KeyPairWithPath { // loaded. Arc::new( read_keypair_from_file(path).unwrap_or_else(|e| { - panic!("invalid keypair file at path {:?}: {e}", path) + panic!("invalid keypair file at path {path:?}: {e}") }), ) } diff --git a/crates/iota-core/benches/batch_verification_bench.rs b/crates/iota-core/benches/batch_verification_bench.rs index 7ff02f03a6b..6173cee83d4 100644 --- a/crates/iota-core/benches/batch_verification_bench.rs +++ b/crates/iota-core/benches/batch_verification_bench.rs @@ -128,7 +128,7 @@ fn batch_verification_bench(c: &mut Criterion) { group.throughput(Throughput::Elements(batch_size)); group.bench_with_input( - BenchmarkId::from_parameter(format!("size={} errors={}", batch_size, num_errors)), + BenchmarkId::from_parameter(format!("size={batch_size} errors={num_errors}")), &batch_size, |b, batch_size| { assert_eq!(certs.len() as u64, *batch_size); diff --git a/crates/iota-core/src/authority.rs b/crates/iota-core/src/authority.rs index 35e934ef18e..3b925195226 100644 --- a/crates/iota-core/src/authority.rs +++ b/crates/iota-core/src/authority.rs @@ -2202,7 +2202,7 @@ impl AuthorityState { // When we process the index, the latest object hasn't been written yet so // the old object must be present. match self.get_owner_at_version(&id, *old_version).unwrap_or_else( - |e| panic!("tx_digest={:?}, error processing object owner index, cannot find owner for object {:?} at version {:?}. Err: {:?}", tx_digest, id, old_version, e), + |e| panic!("tx_digest={tx_digest:?}, error processing object owner index, cannot find owner for object {id:?} at version {old_version:?}. Err: {e:?}"), ) { Owner::AddressOwner(addr) => deleted_owners.push((addr, id)), Owner::ObjectOwner(object_id) => { @@ -2222,8 +2222,7 @@ impl AuthorityState { if let WriteKind::Mutate = kind { let Some(old_version) = modified_at_version.get(id) else { panic!( - "tx_digest={:?}, error processing object owner index, cannot find modified at version for mutated object [{id}].", - tx_digest + "tx_digest={tx_digest:?}, error processing object owner index, cannot find modified at version for mutated object [{id}]." ); }; // When we process the index, the latest object hasn't been written yet so @@ -2233,8 +2232,7 @@ impl AuthorityState { .get_object_by_key(id, *old_version)? else { panic!( - "tx_digest={:?}, error processing object owner index, cannot find owner for object {:?} at version {:?}", - tx_digest, id, old_version + "tx_digest={tx_digest:?}, error processing object owner index, cannot find owner for object {id:?} at version {old_version:?}" ); }; if old_object.owner != owner { @@ -2255,7 +2253,7 @@ impl AuthorityState { // TODO: We can remove the object fetching after we added ObjectType to // TransactionEffects let new_object = written.get(id).unwrap_or_else( - || panic!("tx_digest={:?}, error processing object owner index, written does not contain object {:?}", tx_digest, id) + || panic!("tx_digest={tx_digest:?}, error processing object owner index, written does not contain object {id:?}") ); assert_eq!( new_object.version(), @@ -2286,7 +2284,7 @@ impl AuthorityState { } Owner::ObjectOwner(owner) => { let new_object = written.get(id).unwrap_or_else( - || panic!("tx_digest={:?}, error processing object owner index, written does not contain object {:?}", tx_digest, id) + || panic!("tx_digest={tx_digest:?}, error processing object owner index, written does not contain object {id:?}") ); assert_eq!( new_object.version(), @@ -2642,12 +2640,11 @@ impl AuthorityState { info!("supported versions are: {:?}", supported_protocol_versions); if !supported_protocol_versions.is_version_supported(current_version) { let msg = format!( - "Unsupported protocol version. The network is at {:?}, but this IotaNode only supports: {:?}. Shutting down.", - current_version, supported_protocol_versions, + "Unsupported protocol version. The network is at {current_version:?}, but this IotaNode only supports: {supported_protocol_versions:?}. Shutting down.", ); error!("{}", msg); - eprintln!("{}", msg); + eprintln!("{msg}"); #[cfg(not(msim))] std::process::exit(1); @@ -2977,7 +2974,7 @@ impl AuthorityState { .unwrap_or(false); let current_epoch = cur_epoch_store.epoch(); let epoch_checkpoint_path = - checkpoint_path.join(format!("epoch_{}", current_epoch)); + checkpoint_path.join(format!("epoch_{current_epoch}")); self.checkpoint_all_dbs( &epoch_checkpoint_path, cur_epoch_store, @@ -3101,8 +3098,7 @@ impl AuthorityState { if is_inconsistent { if panic { panic!( - "Inconsistent state detected: root state hash: {:?}, live object set hash: {:?}", - root_state_hash, live_object_set_hash + "Inconsistent state detected: root state hash: {root_state_hash:?}, live object set hash: {live_object_set_hash:?}" ); } else { error!( diff --git a/crates/iota-core/src/authority/authority_per_epoch_store.rs b/crates/iota-core/src/authority/authority_per_epoch_store.rs index 7e3ccc525d6..3f83c7bca3a 100644 --- a/crates/iota-core/src/authority/authority_per_epoch_store.rs +++ b/crates/iota-core/src/authority/authority_per_epoch_store.rs @@ -706,7 +706,7 @@ impl AuthorityEpochTables { } pub fn path(epoch: EpochId, parent_path: &Path) -> PathBuf { - parent_path.join(format!("{}{}", EPOCH_DB_PREFIX, epoch)) + parent_path.join(format!("{EPOCH_DB_PREFIX}{epoch}")) } fn load_reconfig_state(&self) -> IotaResult { @@ -3990,15 +3990,13 @@ impl AuthorityPerEpochStore { (Some((left, ())), Some((right, _))) => { if left != right { panic!( - "Executed transactions and checkpointed transactions do not match: {:?} {:?}", - left, right + "Executed transactions and checkpointed transactions do not match: {left:?} {right:?}" ); } } (None, None) => break, (left, right) => panic!( - "Executed transactions and checkpointed transactions do not match: {:?} {:?}", - left, right + "Executed transactions and checkpointed transactions do not match: {left:?} {right:?}" ), } } diff --git a/crates/iota-core/src/authority/authority_store_pruner.rs b/crates/iota-core/src/authority/authority_store_pruner.rs index 03197df2390..f55a7e5a429 100644 --- a/crates/iota-core/src/authority/authority_store_pruner.rs +++ b/crates/iota-core/src/authority/authority_store_pruner.rs @@ -899,7 +899,7 @@ mod tests { // Adding a tombstone for deleted object. if num_object_versions_to_retain == 0 { let tombstone_key = ObjectKey(id, SequenceNumber::from(num_versions_per_object)); - println!("Adding tombstone object {:?}", tombstone_key); + println!("Adding tombstone object {tombstone_key:?}"); batch.insert_batch( &db.objects, [(tombstone_key, StoreObjectWrapper::V1(StoreObject::Deleted))], diff --git a/crates/iota-core/src/authority/shared_object_version_manager.rs b/crates/iota-core/src/authority/shared_object_version_manager.rs index 3876480c15a..8a4f650086c 100644 --- a/crates/iota-core/src/authority/shared_object_version_manager.rs +++ b/crates/iota-core/src/authority/shared_object_version_manager.rs @@ -201,8 +201,7 @@ impl SharedObjVerManager { SequenceNumber::lamport_increment(input_object_keys.iter().map(|obj| obj.1)); assert!( next_version.is_valid(), - "Assigned version must be valid. Got {:?}", - next_version + "Assigned version must be valid. Got {next_version:?}" ); if !txn_cancelled { diff --git a/crates/iota-core/src/checkpoints/checkpoint_executor/data_ingestion_handler.rs b/crates/iota-core/src/checkpoints/checkpoint_executor/data_ingestion_handler.rs index 457e8ae211f..1ede6c4e14f 100644 --- a/crates/iota-core/src/checkpoints/checkpoint_executor/data_ingestion_handler.rs +++ b/crates/iota-core/src/checkpoints/checkpoint_executor/data_ingestion_handler.rs @@ -133,8 +133,7 @@ pub(crate) fn store_checkpoint_locally( std::fs::create_dir_all(&path).map_err(|err| { IotaError::FileIO(format!( - "failed to save full checkpoint content locally {:?}", - err + "failed to save full checkpoint content locally {err:?}" )) })?; diff --git a/crates/iota-core/src/checkpoints/checkpoint_executor/mod.rs b/crates/iota-core/src/checkpoints/checkpoint_executor/mod.rs index fb38e942d64..96d26257516 100644 --- a/crates/iota-core/src/checkpoints/checkpoint_executor/mod.rs +++ b/crates/iota-core/src/checkpoints/checkpoint_executor/mod.rs @@ -873,7 +873,7 @@ async fn handle_execution_effects( } periods += 1; } - Ok(Err(err)) => panic!("Failed to notify_read_executed_effects: {:?}", err), + Ok(Err(err)) => panic!("Failed to notify_read_executed_effects: {err:?}"), Ok(Ok(effects)) => { for (tx_digest, expected_digest, actual_effects) in izip!(&all_tx_digests, &execution_digests, &effects) @@ -1228,8 +1228,7 @@ async fn execute_transactions( .map(|(fx, fx_digest)| { if fx.is_none() { panic!( - "Transaction effects for effects digest {:?} do not exist in effects table", - fx_digest + "Transaction effects for effects digest {fx_digest:?} do not exist in effects table" ); } let fx = fx.unwrap(); diff --git a/crates/iota-core/src/checkpoints/mod.rs b/crates/iota-core/src/checkpoints/mod.rs index 536dd4251ae..1e0af4ac4ab 100644 --- a/crates/iota-core/src/checkpoints/mod.rs +++ b/crates/iota-core/src/checkpoints/mod.rs @@ -414,7 +414,7 @@ impl CheckpointStore { .get_checkpoint_contents(&verified_checkpoint.content_digest) .map(|opt_contents| { opt_contents - .map(|contents| format!("{:?}", contents)) + .map(|contents| format!("{contents:?}")) .unwrap_or_else(|| { format!( "Verified checkpoint contents not found, digest: {:?}", @@ -434,7 +434,7 @@ impl CheckpointStore { .get_checkpoint_contents(&local_checkpoint.content_digest) .map(|opt_contents| { opt_contents - .map(|contents| format!("{:?}", contents)) + .map(|contents| format!("{contents:?}")) .unwrap_or_else(|| { format!( "Local checkpoint contents not found, digest: {:?}", @@ -761,7 +761,7 @@ impl CheckpointStore { .get_locally_computed_checkpoint(seq) .expect("get_locally_computed_checkpoint should not fail") else { - panic!("locally computed checkpoint {:?} not found", seq); + panic!("locally computed checkpoint {seq:?} not found"); }; let Some(contents) = self @@ -783,7 +783,7 @@ impl CheckpointStore { .expect("multi_get_transaction_blocks should not fail"); for (tx, digest) in txns.iter().zip(tx_digests.iter()) { if tx.is_none() { - panic!("transaction {:?} not found", digest); + panic!("transaction {digest:?} not found"); } } @@ -1335,7 +1335,7 @@ impl CheckpointBuilder { .zip(transactions_and_sizes.into_iter()) { let (transaction, size) = transaction_and_size - .unwrap_or_else(|| panic!("Could not find executed transaction {:?}", effects)); + .unwrap_or_else(|| panic!("Could not find executed transaction {effects:?}")); match transaction.inner().transaction_data().kind() { TransactionKind::ConsensusCommitPrologueV1(_) | TransactionKind::AuthenticatorStateUpdateV1(_) => { @@ -1648,8 +1648,7 @@ impl CheckpointBuilder { .map(|(opt, digest)| match opt { Some(x) => x, None => panic!( - "Can not find effect for transaction {:?}, however transaction that depend on it was already executed", - digest + "Can not find effect for transaction {digest:?}, however transaction that depend on it was already executed" ), }) .collect::>(); @@ -1966,7 +1965,7 @@ impl CheckpointSignatureAggregator { .into_iter() .sorted_by_key(|(_, (_, stake))| -(*stake as i64)) .map(|(digest, (_authorities, total_stake))| { - format!("{:?} (total stake: {})", digest, total_stake) + format!("{digest:?} (total stake: {total_stake})") }) .collect::>(); error!( @@ -2164,7 +2163,7 @@ async fn diagnose_split_brain( .into_path() .join(Path::new("checkpoint_fork_dump.txt")); let mut file = File::create(path).unwrap(); - write!(file, "{}", fork_logs_text).unwrap(); + write!(file, "{fork_logs_text}").unwrap(); debug!("{}", fork_logs_text); fail_point!("split_brain_reached"); diff --git a/crates/iota-core/src/connection_monitor.rs b/crates/iota-core/src/connection_monitor.rs index 33224315332..7e2f698309b 100644 --- a/crates/iota-core/src/connection_monitor.rs +++ b/crates/iota-core/src/connection_monitor.rs @@ -473,8 +473,7 @@ mod tests { .await .unwrap_or_else(|_| { panic!( - "Timeout while waiting for connectivity results for value {}", - value + "Timeout while waiting for connectivity results for value {value}" ) }); diff --git a/crates/iota-core/src/consensus_manager/mod.rs b/crates/iota-core/src/consensus_manager/mod.rs index 53676b81dd2..db7e9487332 100644 --- a/crates/iota-core/src/consensus_manager/mod.rs +++ b/crates/iota-core/src/consensus_manager/mod.rs @@ -204,8 +204,7 @@ impl UpdatableConsensusClient { } panic!( - "Timed out after {:?} waiting for Consensus to start!", - START_TIMEOUT, + "Timed out after {START_TIMEOUT:?} waiting for Consensus to start!", ); } diff --git a/crates/iota-core/src/consensus_manager/mysticeti_manager.rs b/crates/iota-core/src/consensus_manager/mysticeti_manager.rs index b0da91f6e40..b8d28d62d41 100644 --- a/crates/iota-core/src/consensus_manager/mysticeti_manager.rs +++ b/crates/iota-core/src/consensus_manager/mysticeti_manager.rs @@ -81,7 +81,7 @@ impl MysticetiManager { fn get_store_path(&self, epoch: EpochId) -> PathBuf { let mut store_path = self.storage_base_path.clone(); - store_path.push(format!("{}", epoch)); + store_path.push(format!("{epoch}")); store_path } diff --git a/crates/iota-core/src/db_checkpoint_handler.rs b/crates/iota-core/src/db_checkpoint_handler.rs index 42f8f5ded66..a7b1e391648 100644 --- a/crates/iota-core/src/db_checkpoint_handler.rs +++ b/crates/iota-core/src/db_checkpoint_handler.rs @@ -365,7 +365,7 @@ impl DBCheckpointHandler { // This writes a single "MANIFEST" file which contains a list of all files that // make up a db snapshot - write_snapshot_manifest(db_path, &object_store, format!("epoch_{}/", epoch)) + write_snapshot_manifest(db_path, &object_store, format!("epoch_{epoch}/")) .await?; // Drop marker in the output directory that upload completed successfully let bytes = Bytes::from_static(b"success"); diff --git a/crates/iota-core/src/execution_cache.rs b/crates/iota-core/src/execution_cache.rs index 2ea779f3d9e..fe074cc4c94 100644 --- a/crates/iota-core/src/execution_cache.rs +++ b/crates/iota-core/src/execution_cache.rs @@ -311,8 +311,7 @@ pub trait ObjectCacheRead: Send + Sync { assert!( input_key.version().is_none() || input_key.version().unwrap().is_valid(), "Shared objects in cancelled transaction should always be available immediately, - but it appears that transaction manager is waiting for {:?} to become available", - input_key + but it appears that transaction manager is waiting for {input_key:?} to become available" ); // If the key exists at the specified version, then the object is available. if has_key { diff --git a/crates/iota-core/src/execution_cache/cache_types.rs b/crates/iota-core/src/execution_cache/cache_types.rs index 8247fe7159e..2fd71e56351 100644 --- a/crates/iota-core/src/execution_cache/cache_types.rs +++ b/crates/iota-core/src/execution_cache/cache_types.rs @@ -40,9 +40,7 @@ impl CachedVersionMap { let back = self.values.back().unwrap().0; assert!( back < version, - "version must be monotonically increasing ({} < {})", - back, - version + "version must be monotonically increasing ({back} < {version})" ); } self.values.push_back((version, value)); @@ -317,7 +315,7 @@ mod tests { fn truncate_map_to_smaller_size() { let mut map = CachedVersionMap::default(); for i in 1..=5 { - map.insert(seq(i), format!("Item {}", i)); + map.insert(seq(i), format!("Item {i}")); } map.truncate_to(3); assert_eq!(map.values.len(), 3); diff --git a/crates/iota-core/src/execution_cache/unit_tests/writeback_cache_tests.rs b/crates/iota-core/src/execution_cache/unit_tests/writeback_cache_tests.rs index 24d14676e83..afb42cb60c8 100644 --- a/crates/iota-core/src/execution_cache/unit_tests/writeback_cache_tests.rs +++ b/crates/iota-core/src/execution_cache/unit_tests/writeback_cache_tests.rs @@ -123,7 +123,7 @@ impl Scenario { }; for i in 0..num_steps { - println!("running with cache eviction after step {}", i); + println!("running with cache eviction after step {i}"); let count = Arc::new(AtomicU32::new(0)); let action = Box::new(|s: &mut Scenario| { println!("evict_caches()"); @@ -1044,7 +1044,7 @@ async fn test_concurrent_readers() { for (_, _, parent_ref, child_id) in txns { barrier.wait().await; - println!("parent: {:?}", parent_ref); + println!("parent: {parent_ref:?}"); loop { let parent = cache .get_object_by_key(&parent_ref.0, parent_ref.1) diff --git a/crates/iota-core/src/execution_cache/writeback_cache.rs b/crates/iota-core/src/execution_cache/writeback_cache.rs index e27a634a80e..0a9c9c42f6d 100644 --- a/crates/iota-core/src/execution_cache/writeback_cache.rs +++ b/crates/iota-core/src/execution_cache/writeback_cache.rs @@ -654,7 +654,7 @@ impl WritebackCache { "object_by_id cache is incoherent for {:?}", object_id ); - panic!("object_by_id cache is incoherent for {:?}", object_id); + panic!("object_by_id cache is incoherent for {object_id:?}"); } } } @@ -1206,8 +1206,7 @@ impl ObjectCacheRead for WritebackCache { assert_eq!( store_package.digest(), p.object().digest(), - "Package object cache is inconsistent for package {:?}", - package_id + "Package object cache is inconsistent for package {package_id:?}" ); } } diff --git a/crates/iota-core/src/generate_format.rs b/crates/iota-core/src/generate_format.rs index 454bc760eb0..87a91a2968c 100644 --- a/crates/iota-core/src/generate_format.rs +++ b/crates/iota-core/src/generate_format.rs @@ -221,7 +221,7 @@ fn main() { Action::Record => { let content = serde_yaml::to_string(®istry).unwrap(); let mut f = File::create(FILE_PATH).unwrap(); - writeln!(f, "{}", content).unwrap(); + writeln!(f, "{content}").unwrap(); } Action::Test => { let reference = std::fs::read_to_string(FILE_PATH).unwrap(); diff --git a/crates/iota-core/src/mysticeti_adapter.rs b/crates/iota-core/src/mysticeti_adapter.rs index 2b88f8e9d45..048ad19fdd8 100644 --- a/crates/iota-core/src/mysticeti_adapter.rs +++ b/crates/iota-core/src/mysticeti_adapter.rs @@ -96,7 +96,7 @@ impl ConsensusClient for LazyMysticetiClient { .await .tap_err(|err| { // Will be logged by caller as well. - let msg = format!("Transaction submission failed with: {:?}", err); + let msg = format!("Transaction submission failed with: {err:?}"); match err { ClientError::ConsensusShuttingDown(_) => { info!("{}", msg); diff --git a/crates/iota-core/src/quorum_driver/mod.rs b/crates/iota-core/src/quorum_driver/mod.rs index 8dc0a6112fb..16511969d10 100644 --- a/crates/iota-core/src/quorum_driver/mod.rs +++ b/crates/iota-core/src/quorum_driver/mod.rs @@ -77,7 +77,7 @@ impl Debug for QuorumDriverTask { write!(writer, "has_tx_cert={} ", self.tx_cert.is_some())?; write!(writer, "retry_times={} ", self.retry_times)?; write!(writer, "next_retry_after={:?} ", self.next_retry_after)?; - write!(f, "{}", writer) + write!(f, "{writer}") } } diff --git a/crates/iota-core/src/quorum_driver/tests.rs b/crates/iota-core/src/quorum_driver/tests.rs index bde1350c36f..a27474e6e2f 100644 --- a/crates/iota-core/src/quorum_driver/tests.rs +++ b/crates/iota-core/src/quorum_driver/tests.rs @@ -326,8 +326,7 @@ async fn test_quorum_driver_object_locked() -> Result<(), anyhow::Error> { assert_eq!(conflicting_txes.iter().next().unwrap().0, tx.digest()); } else { panic!( - "expect Err(QuorumDriverError::ObjectsDoubleUsed) but got {:?}", - res + "expect Err(QuorumDriverError::ObjectsDoubleUsed) but got {res:?}" ); } @@ -374,8 +373,7 @@ async fn test_quorum_driver_object_locked() -> Result<(), anyhow::Error> { assert_eq!(conflicting_txes.iter().next().unwrap().0, tx.digest()); } else { panic!( - "expect Err(QuorumDriverError::ObjectsDoubleUsed) but got {:?}", - res + "expect Err(QuorumDriverError::ObjectsDoubleUsed) but got {res:?}" ) } @@ -451,8 +449,7 @@ async fn test_quorum_driver_object_locked() -> Result<(), anyhow::Error> { assert_eq!(conflicting_txes.get(tx2.digest()).unwrap().1, 2500); } else { panic!( - "expect Err(QuorumDriverError::ObjectsDoubleUsed) but got {:?}", - res + "expect Err(QuorumDriverError::ObjectsDoubleUsed) but got {res:?}" ) } @@ -498,8 +495,7 @@ async fn test_quorum_driver_object_locked() -> Result<(), anyhow::Error> { assert_eq!(conflicting_txes.get(tx.digest()).unwrap().1, 5000); } else { panic!( - "expect Err(QuorumDriverError::ObjectsDoubleUsed) but got {:?}", - res + "expect Err(QuorumDriverError::ObjectsDoubleUsed) but got {res:?}" ) } @@ -588,8 +584,7 @@ async fn test_quorum_driver_object_locked() -> Result<(), anyhow::Error> { ); } else { panic!( - "expect Err(QuorumDriverError::ObjectsDoubleUsed) but got {:?}", - res + "expect Err(QuorumDriverError::ObjectsDoubleUsed) but got {res:?}" ) } @@ -663,7 +658,7 @@ async fn test_quorum_driver_handling_overload_and_retry() { .await .unwrap(); match timeout(Duration::from_secs(300), ticket).await { - Ok(result) => panic!("Process transaction should timeout! {:?}", result), + Ok(result) => panic!("Process transaction should timeout! {result:?}"), Err(_) => { assert_eq!(retry_count.load(Ordering::SeqCst), 10); println!("Waiting for txn timed out! This is desired behavior.") diff --git a/crates/iota-core/src/scoring_decision.rs b/crates/iota-core/src/scoring_decision.rs index e3ae21cede5..5269fbd2c18 100644 --- a/crates/iota-core/src/scoring_decision.rs +++ b/crates/iota-core/src/scoring_decision.rs @@ -30,8 +30,7 @@ pub(crate) fn update_low_scoring_authorities( ) { assert!( (0..=33).contains(&consensus_bad_nodes_stake_threshold), - "The bad_nodes_stake_threshold should be in range [0 - 33], out of bounds parameter detected {}", - consensus_bad_nodes_stake_threshold + "The bad_nodes_stake_threshold should be in range [0 - 33], out of bounds parameter detected {consensus_bad_nodes_stake_threshold}" ); let Some(reputation_scores) = reputation_score_sorted_desc else { diff --git a/crates/iota-core/src/streamer.rs b/crates/iota-core/src/streamer.rs index 4fff745f6d1..667a766e341 100644 --- a/crates/iota-core/src/streamer.rs +++ b/crates/iota-core/src/streamer.rs @@ -37,7 +37,7 @@ where metrics: Arc, metrics_label: &'static str, ) -> Self { - let channel_label = format!("streamer_{}", metrics_label); + let channel_label = format!("streamer_{metrics_label}"); let gauge = if let Some(metrics) = iota_metrics::get_metrics() { metrics .channel_inflight diff --git a/crates/iota-core/src/traffic_controller/mod.rs b/crates/iota-core/src/traffic_controller/mod.rs index 01e262db1a4..9e03f421c91 100644 --- a/crates/iota-core/src/traffic_controller/mod.rs +++ b/crates/iota-core/src/traffic_controller/mod.rs @@ -626,9 +626,9 @@ impl TrafficSim { "Running naive traffic simulation for {} seconds", duration.as_secs() ); - println!("Policy: {:#?}", policy); - println!("Num clients: {}", num_clients); - println!("TPS per client: {}", per_client_tps); + println!("Policy: {policy:#?}"); + println!("Num clients: {num_clients}"); + println!("TPS per client: {per_client_tps}"); println!( "Target total TPS: {}", per_client_tps * num_clients as usize @@ -766,7 +766,7 @@ impl TrafficSim { let avg_first_block_time = metrics .time_to_first_block .map(|ttf| ttf / num_clients as u32); - println!("Average time to first block: {:?}", avg_first_block_time); + println!("Average time to first block: {avg_first_block_time:?}"); // This is the time it took for the first request to be blocked across all // clients, and is instead more useful for understanding false positives // in terms of rate and magnitude. diff --git a/crates/iota-core/src/traffic_controller/policies.rs b/crates/iota-core/src/traffic_controller/policies.rs index e9531cbef88..5874879f361 100644 --- a/crates/iota-core/src/traffic_controller/policies.rs +++ b/crates/iota-core/src/traffic_controller/policies.rs @@ -608,7 +608,7 @@ mod tests { tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; for i in 0..5 { let response = policy.handle_tally(alice.clone()); - assert_eq!(response.block_client, None, "Blocked at i = {}", i); + assert_eq!(response.block_client, None, "Blocked at i = {i}"); assert_eq!(response.block_proxied_client, None); } @@ -628,7 +628,7 @@ mod tests { // spam through charlie to block connection for i in 0..2 { let response = policy.handle_tally(charlie.clone()); - assert_eq!(response.block_client, None, "Blocked at i = {}", i); + assert_eq!(response.block_client, None, "Blocked at i = {i}"); assert_eq!(response.block_proxied_client, None); } // Now we block connection IP @@ -642,7 +642,7 @@ mod tests { tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; for i in 0..3 { let response = policy.handle_tally(charlie.clone()); - assert_eq!(response.block_client, None, "Blocked at i = {}", i); + assert_eq!(response.block_client, None, "Blocked at i = {i}"); assert_eq!(response.block_proxied_client, None); } diff --git a/crates/iota-core/src/transaction_manager.rs b/crates/iota-core/src/transaction_manager.rs index 65f974ec815..805fbc73951 100644 --- a/crates/iota-core/src/transaction_manager.rs +++ b/crates/iota-core/src/transaction_manager.rs @@ -525,7 +525,7 @@ impl TransactionManager { receiving_objects, epoch_store.epoch(), ) - .unwrap_or_else(|err| panic!("Checking object existence cannot fail: {:?}", err)) + .unwrap_or_else(|err| panic!("Checking object existence cannot fail: {err:?}")) .into_iter() .zip(input_object_cache_misses); @@ -640,9 +640,7 @@ impl TransactionManager { assert!( inner.missing_inputs.entry(key).or_default().insert(digest), - "Duplicated certificate {:?} for missing object {:?}", - digest, - key + "Duplicated certificate {digest:?} for missing object {key:?}" ); let input_txns = inner.input_objects.entry(key.id()).or_default(); input_txns.insert(digest, pending_cert_enqueue_time); @@ -666,8 +664,7 @@ impl TransactionManager { .pending_certificates .insert(digest, pending_cert) .is_none(), - "Duplicated pending certificate {:?}", - digest + "Duplicated pending certificate {digest:?}" ); self.metrics diff --git a/crates/iota-core/src/unit_tests/authority_tests.rs b/crates/iota-core/src/unit_tests/authority_tests.rs index 2226c26a1ba..6e2dd0e2590 100644 --- a/crates/iota-core/src/unit_tests/authority_tests.rs +++ b/crates/iota-core/src/unit_tests/authority_tests.rs @@ -588,8 +588,7 @@ async fn test_dev_inspect_dynamic_field() { let err = error.unwrap(); assert!( err.contains("kind: CircularObjectOwnership"), - "unexpected error: {}", - err + "unexpected error: {err}" ); // add a dynamic field to an object @@ -1935,7 +1934,7 @@ async fn test_package_size_limit() { let mut module = file_format::empty_module(); // generate unique name module.identifiers[0] = - Identifier::new(format!("TestModule{:0>21000?}", modules_size)).unwrap(); + Identifier::new(format!("TestModule{modules_size:0>21000?}")).unwrap(); let module_bytes = { let mut bytes = Vec::new(); module @@ -3210,8 +3209,7 @@ async fn test_invalid_object_ownership() { UserInputError::try_from(e).unwrap(), UserInputError::IncorrectUserSignature { error: format!( - "Object {:?} is owned by account address {:?}, but given owner/signer address is {:?}", - invalid_ownership_object_id, invalid_owner, sender + "Object {invalid_ownership_object_id:?} is owned by account address {invalid_owner:?}, but given owner/signer address is {sender:?}" ) } ); @@ -3629,8 +3627,7 @@ async fn create_and_retrieve_df_info(function: &IdentStr) -> (IotaAddress, Vec { panic!( - "Expected ConsensusRound, got RandomnessDkg: {:?}", - deferred_from_round + "Expected ConsensusRound, got RandomnessDkg: {deferred_from_round:?}" ); } } @@ -6024,8 +6020,7 @@ async fn test_consensus_handler_per_object_congestion_control( deferred_from_round, } => { panic!( - "Expected ConsensusRound, got RandomnessDkg: {:?}", - deferred_from_round + "Expected ConsensusRound, got RandomnessDkg: {deferred_from_round:?}" ); } } diff --git a/crates/iota-core/src/unit_tests/coin_deny_list_tests.rs b/crates/iota-core/src/unit_tests/coin_deny_list_tests.rs index 76defb6232b..e98734220fd 100644 --- a/crates/iota-core/src/unit_tests/coin_deny_list_tests.rs +++ b/crates/iota-core/src/unit_tests/coin_deny_list_tests.rs @@ -197,7 +197,7 @@ async fn test_regulated_coin_v1_types() { if effects.status().is_err() { panic!("Failed to enable global pause: {:?}", effects.status()); } - println!("Effects: {:?}", effects); + println!("Effects: {effects:?}"); assert!(check_global_pause( &coin_deny_config, &env.authority.get_object_store(), diff --git a/crates/iota-core/src/unit_tests/execution_driver_tests.rs b/crates/iota-core/src/unit_tests/execution_driver_tests.rs index 863ac7bc0c6..fbf9d729945 100644 --- a/crates/iota-core/src/unit_tests/execution_driver_tests.rs +++ b/crates/iota-core/src/unit_tests/execution_driver_tests.rs @@ -365,7 +365,7 @@ async fn test_execution_with_dependencies() { assert_eq!(initial_shared_version.value(), 3); initial_shared_version } else { - panic!("Not a shared object! {:?} {:?}", shared_counter_ref, owner); + panic!("Not a shared object! {shared_counter_ref:?} {owner:?}"); }; // ---- Execute transactions with dependencies on first 3 nodes in the @@ -542,7 +542,7 @@ async fn test_per_object_overload() { initial_shared_version: shared_counter_initial_version, } = owner else { - panic!("Not a shared object! {:?} {:?}", shared_counter_ref, owner); + panic!("Not a shared object! {shared_counter_ref:?} {owner:?}"); }; // Stop execution on the last authority, to simulate having a backlog. @@ -672,7 +672,7 @@ async fn test_txn_age_overload() { initial_shared_version: shared_counter_initial_version, } = owner else { - panic!("Not a shared object! {:?} {:?}", shared_counter_ref, owner); + panic!("Not a shared object! {shared_counter_ref:?} {owner:?}"); }; // Stop execution on the last authority, to simulate having a backlog. diff --git a/crates/iota-core/src/unit_tests/move_package_upgrade_tests.rs b/crates/iota-core/src/unit_tests/move_package_upgrade_tests.rs index b414ef7d7c4..35c7f00b727 100644 --- a/crates/iota-core/src/unit_tests/move_package_upgrade_tests.rs +++ b/crates/iota-core/src/unit_tests/move_package_upgrade_tests.rs @@ -81,14 +81,14 @@ fn build_upgrade_test_modules_with_overlay( match overlay { FileOverlay::Remove(file_name) => { - let file_path = tmp_dir_path.join(format!("sources/{}", file_name)); + let file_path = tmp_dir_path.join(format!("sources/{file_name}")); std::fs::remove_file(file_path).unwrap(); } FileOverlay::Add { file_name, contents, } => { - let new_file_path = tmp_dir_path.join(format!("sources/{}", file_name)); + let new_file_path = tmp_dir_path.join(format!("sources/{file_name}")); std::fs::write(new_file_path, contents).unwrap(); } } @@ -313,7 +313,7 @@ async fn test_upgrade_package_happy_path() { match effects.into_status().unwrap_err().0 { ExecutionFailureStatus::MoveAbort(_, 42) => { /* nop */ } - err => panic!("Unexpected error: {:#?}", err), + err => panic!("Unexpected error: {err:#?}"), }; let (digest, modules) = build_upgrade_test_modules("stage1_basic_compatibility_valid"); @@ -1083,7 +1083,7 @@ async fn test_publish_transitive_happy_path() { match call_effects.into_status().unwrap_err().0 { ExecutionFailureStatus::MoveAbort(_, 42) => { /* nop */ } - err => panic!("Unexpected error: {:#?}", err), + err => panic!("Unexpected error: {err:#?}"), }; } @@ -1406,7 +1406,7 @@ async fn test_conflicting_versions_across_calls() { // verify that execution aborts match call_error.0 { ExecutionFailureStatus::MoveAbort(_, 42) => { /* nop */ } - err => panic!("Unexpected error: {:#?}", err), + err => panic!("Unexpected error: {err:#?}"), }; // verify that execution aborts in the second (counting from 0) command diff --git a/crates/iota-core/src/unit_tests/transfer_to_object_tests.rs b/crates/iota-core/src/unit_tests/transfer_to_object_tests.rs index 61795f7bbf5..1987dad7def 100644 --- a/crates/iota-core/src/unit_tests/transfer_to_object_tests.rs +++ b/crates/iota-core/src/unit_tests/transfer_to_object_tests.rs @@ -490,12 +490,11 @@ async fn test_tto_invalid_receiving_arguments() { builder.finish() }) .await else { - panic!("failed on iteration {}", i); + panic!("failed on iteration {i}"); }; assert!( expect(error), - "failed to match expected error on iteration {}", - i + "failed to match expected error on iteration {i}" ); } } diff --git a/crates/iota-data-ingestion-core/src/reader.rs b/crates/iota-data-ingestion-core/src/reader.rs index 47d052ed5d3..5643c36c2cb 100644 --- a/crates/iota-data-ingestion-core/src/reader.rs +++ b/crates/iota-data-ingestion-core/src/reader.rs @@ -127,7 +127,7 @@ impl CheckpointReader { store: &dyn ObjectStore, checkpoint_number: CheckpointSequenceNumber, ) -> IngestionResult<(Arc, usize)> { - let path = Path::from(format!("{}.chk", checkpoint_number)); + let path = Path::from(format!("{checkpoint_number}.chk")); let response = store.get(&path).await?; let bytes = response.bytes().await?; Ok(( @@ -378,7 +378,7 @@ impl CheckpointReader { std::fs::create_dir_all(self.path.clone()).expect("failed to create a directory"); let mut watcher = notify::recommended_watcher(move |res| { if let Err(err) = res { - eprintln!("watch error: {:?}", err); + eprintln!("watch error: {err:?}"); } inotify_sender .blocking_send(()) diff --git a/crates/iota-data-ingestion-core/src/tests.rs b/crates/iota-data-ingestion-core/src/tests.rs index d3ddfe5eab7..eaf49ac06e3 100644 --- a/crates/iota-data-ingestion-core/src/tests.rs +++ b/crates/iota-data-ingestion-core/src/tests.rs @@ -193,7 +193,7 @@ async fn basic_flow() { let path = temp_dir(); for checkpoint_number in 0..20 { let bytes = mock_checkpoint_data_bytes(checkpoint_number); - std::fs::write(path.join(format!("{}.chk", checkpoint_number)), bytes).unwrap(); + std::fs::write(path.join(format!("{checkpoint_number}.chk")), bytes).unwrap(); } let result = run( bundle.executor, @@ -229,7 +229,7 @@ async fn graceful_shutdown_faulty_worker() { let path = temp_dir(); for checkpoint_number in 0..20 { let bytes = mock_checkpoint_data_bytes(checkpoint_number); - std::fs::write(path.join(format!("{}.chk", checkpoint_number)), bytes).unwrap(); + std::fs::write(path.join(format!("{checkpoint_number}.chk")), bytes).unwrap(); } let result = run( bundle.executor, @@ -268,7 +268,7 @@ async fn worker_pool_with_reducer() { let path = temp_dir(); for checkpoint_number in 0..20 { let bytes = mock_checkpoint_data_bytes(checkpoint_number); - std::fs::write(path.join(format!("{}.chk", checkpoint_number)), bytes).unwrap(); + std::fs::write(path.join(format!("{checkpoint_number}.chk")), bytes).unwrap(); } let result = run( bundle.executor, @@ -315,7 +315,7 @@ async fn graceful_shutdown_faulty_reducer() { let path = temp_dir(); for checkpoint_number in 0..20 { let bytes = mock_checkpoint_data_bytes(checkpoint_number); - std::fs::write(path.join(format!("{}.chk", checkpoint_number)), bytes).unwrap(); + std::fs::write(path.join(format!("{checkpoint_number}.chk")), bytes).unwrap(); } let result = run( bundle.executor, diff --git a/crates/iota-data-ingestion/src/workers/archival.rs b/crates/iota-data-ingestion/src/workers/archival.rs index e485e1af19a..6ddb9a53641 100644 --- a/crates/iota-data-ingestion/src/workers/archival.rs +++ b/crates/iota-data-ingestion/src/workers/archival.rs @@ -60,7 +60,7 @@ impl ArchivalReducer { summary_buffer: Vec, buffer: Vec, ) -> anyhow::Result<()> { - let checkpoint_file_path = format!("epoch_{}/{}.chk", epoch, start); + let checkpoint_file_path = format!("epoch_{epoch}/{start}.chk"); let chk_bytes = self .upload_file( Path::from(checkpoint_file_path.clone()), @@ -68,7 +68,7 @@ impl ArchivalReducer { &buffer, ) .await?; - let summary_file_path = format!("epoch_{}/{}.sum", epoch, start); + let summary_file_path = format!("epoch_{epoch}/{start}.sum"); let sum_bytes = self .upload_file( Path::from(summary_file_path.clone()), diff --git a/crates/iota-e2e-tests/tests/full_node_tests.rs b/crates/iota-e2e-tests/tests/full_node_tests.rs index dc63ad139e9..2fa02de79a2 100644 --- a/crates/iota-e2e-tests/tests/full_node_tests.rs +++ b/crates/iota-e2e-tests/tests/full_node_tests.rs @@ -720,8 +720,7 @@ async fn test_full_node_transaction_orchestrator_basic() -> Result<(), anyhow::E let mut txns = batch_make_transfer_transactions(context, txn_count).await; assert!( txns.len() >= txn_count, - "Expect at least {} txns. Do we generate enough gas objects during genesis?", - txn_count, + "Expect at least {txn_count} txns. Do we generate enough gas objects during genesis?", ); // Test WaitForLocalExecution @@ -734,7 +733,7 @@ async fn test_full_node_transaction_orchestrator_basic() -> Result<(), anyhow::E None, ) .await - .unwrap_or_else(|e| panic!("Failed to execute transaction {:?}: {:?}", digest, e)); + .unwrap_or_else(|e| panic!("Failed to execute transaction {digest:?}: {e:?}")); let ( tx, @@ -757,7 +756,7 @@ async fn test_full_node_transaction_orchestrator_basic() -> Result<(), anyhow::E ); // verify that the node has sequenced and executed the txn fullnode.state().get_executed_transaction_and_effects(digest, kv_store.clone()).await - .unwrap_or_else(|e| panic!("Fullnode does not know about the txn {:?} that was executed with WaitForLocalExecution: {:?}", digest, e)); + .unwrap_or_else(|e| panic!("Fullnode does not know about the txn {digest:?} that was executed with WaitForLocalExecution: {e:?}")); // Test WaitForEffectsCert let txn = txns.swap_remove(0); @@ -769,7 +768,7 @@ async fn test_full_node_transaction_orchestrator_basic() -> Result<(), anyhow::E None, ) .await - .unwrap_or_else(|e| panic!("Failed to execute transaction {:?}: {:?}", digest, e)); + .unwrap_or_else(|e| panic!("Failed to execute transaction {digest:?}: {e:?}")); let ( tx, @@ -797,7 +796,7 @@ async fn test_full_node_transaction_orchestrator_basic() -> Result<(), anyhow::E .await .unwrap(); fullnode.state().get_executed_transaction_and_effects(digest, kv_store).await - .unwrap_or_else(|e| panic!("Fullnode does not know about the txn {:?} that was executed with WaitForEffectsCert: {:?}", digest, e)); + .unwrap_or_else(|e| panic!("Fullnode does not know about the txn {digest:?} that was executed with WaitForEffectsCert: {e:?}")); Ok(()) } @@ -871,8 +870,7 @@ async fn test_full_node_transaction_orchestrator_rpc_ok() -> Result<(), anyhow:: let mut txns = batch_make_transfer_transactions(context, txn_count).await; assert!( txns.len() >= txn_count, - "Expect at least {} txns. Do we generate enough gas objects during genesis?", - txn_count, + "Expect at least {txn_count} txns. Do we generate enough gas objects during genesis?", ); let txn = txns.swap_remove(0); @@ -1181,8 +1179,8 @@ async fn test_pass_back_no_object() -> Result<(), anyhow::Error> { None, ) .await - .unwrap_or_else(|e| panic!("Failed to execute transaction {:?}: {:?}", digest, e)); - println!("res: {:?}", _res); + .unwrap_or_else(|e| panic!("Failed to execute transaction {digest:?}: {e:?}")); + println!("res: {_res:?}"); let ( _tx, diff --git a/crates/iota-e2e-tests/tests/snapshot_tests.rs b/crates/iota-e2e-tests/tests/snapshot_tests.rs index 6dd3123c1b6..83971b3fb58 100644 --- a/crates/iota-e2e-tests/tests/snapshot_tests.rs +++ b/crates/iota-e2e-tests/tests/snapshot_tests.rs @@ -45,7 +45,7 @@ async fn run_one( IotaCommand::Move { .. } => { unimplemented!("Supporting Move publish and upgrade commands") } - _ => panic!("Command {:?} not supported by RPC snapshot tests", cli_cmd), + _ => panic!("Command {cli_cmd:?} not supported by RPC snapshot tests"), } } Ok(test_output) diff --git a/crates/iota-e2e-tests/tests/traffic_control_tests.rs b/crates/iota-e2e-tests/tests/traffic_control_tests.rs index 03d13934614..761c1a8cab7 100644 --- a/crates/iota-e2e-tests/tests/traffic_control_tests.rs +++ b/crates/iota-e2e-tests/tests/traffic_control_tests.rs @@ -179,8 +179,7 @@ async fn test_fullnode_traffic_control_dry_run() -> Result<(), anyhow::Error> { let mut txns = batch_make_transfer_transactions(&context, txn_count as usize).await; assert!( txns.len() >= txn_count as usize, - "Expect at least {} txns. Do we generate enough gas objects during genesis?", - txn_count, + "Expect at least {txn_count} txns. Do we generate enough gas objects during genesis?", ); let txn = txns.swap_remove(0); @@ -288,8 +287,7 @@ async fn test_fullnode_traffic_control_spam_blocked() -> Result<(), anyhow::Erro let mut txns = batch_make_transfer_transactions(&context, txn_count as usize).await; assert!( txns.len() >= txn_count as usize, - "Expect at least {} txns. Do we generate enough gas objects during genesis?", - txn_count, + "Expect at least {txn_count} txns. Do we generate enough gas objects during genesis?", ); let txn = txns.swap_remove(0); @@ -354,8 +352,7 @@ async fn test_fullnode_traffic_control_error_blocked() -> Result<(), anyhow::Err let mut txns = batch_make_transfer_transactions(&context, txn_count as usize).await; assert!( txns.len() >= txn_count as usize, - "Expect at least {} txns. Do we generate enough gas objects during genesis?", - txn_count, + "Expect at least {txn_count} txns. Do we generate enough gas objects during genesis?", ); // it should take no more than 4 requests to be added to the blocklist @@ -405,7 +402,7 @@ async fn test_validator_traffic_control_error_delegated() -> Result<(), anyhow:: }; // enable remote firewall delegation let firewall_config = RemoteFirewallConfig { - remote_fw_url: format!("http://127.0.0.1:{}", port), + remote_fw_url: format!("http://127.0.0.1:{port}"), delegate_spam_blocking: true, delegate_error_blocking: false, destination_port: 8080, @@ -473,7 +470,7 @@ async fn test_fullnode_traffic_control_spam_delegated() -> Result<(), anyhow::Er }; // enable remote firewall delegation let firewall_config = RemoteFirewallConfig { - remote_fw_url: format!("http://127.0.0.1:{}", port), + remote_fw_url: format!("http://127.0.0.1:{port}"), delegate_spam_blocking: true, delegate_error_blocking: false, destination_port: 9000, @@ -496,8 +493,7 @@ async fn test_fullnode_traffic_control_spam_delegated() -> Result<(), anyhow::Er let mut txns = batch_make_transfer_transactions(&context, txn_count as usize).await; assert!( txns.len() >= txn_count as usize, - "Expect at least {} txns. Do we generate enough gas objects during genesis?", - txn_count, + "Expect at least {txn_count} txns. Do we generate enough gas objects during genesis?", ); let txn = txns.swap_remove(0); @@ -737,8 +733,7 @@ async fn assert_traffic_control_ok(mut test_cluster: TestCluster) -> Result<(), let mut txns = batch_make_transfer_transactions(context, txn_count).await; assert!( txns.len() >= txn_count, - "Expect at least {} txns. Do we generate enough gas objects during genesis?", - txn_count, + "Expect at least {txn_count} txns. Do we generate enough gas objects during genesis?", ); let txn = txns.swap_remove(0); @@ -806,8 +801,7 @@ async fn assert_validator_traffic_control_dry_run( let mut txns = batch_make_transfer_transactions(context, txn_count).await; assert!( txns.len() >= txn_count, - "Expect at least {} txns. Do we generate enough gas objects during genesis?", - txn_count, + "Expect at least {txn_count} txns. Do we generate enough gas objects during genesis?", ); let txn = txns.swap_remove(0); diff --git a/crates/iota-e2e-tests/tests/transaction_orchestrator_tests.rs b/crates/iota-e2e-tests/tests/transaction_orchestrator_tests.rs index 8a67df8b061..28732c85597 100644 --- a/crates/iota-e2e-tests/tests/transaction_orchestrator_tests.rs +++ b/crates/iota-e2e-tests/tests/transaction_orchestrator_tests.rs @@ -41,8 +41,7 @@ async fn test_blocking_execution() -> Result<(), anyhow::Error> { let mut txns = batch_make_transfer_transactions(context, txn_count).await; assert!( txns.len() >= txn_count, - "Expect at least {} txns. Do we generate enough gas objects during genesis?", - txn_count, + "Expect at least {txn_count} txns. Do we generate enough gas objects during genesis?", ); // Quorum driver does not execute txn locally @@ -74,7 +73,7 @@ async fn test_blocking_execution() -> Result<(), anyhow::Error> { ExecuteTransactionRequestType::WaitForLocalExecution, ) .await - .unwrap_or_else(|e| panic!("Failed to execute transaction {:?}: {:?}", digest, e)); + .unwrap_or_else(|e| panic!("Failed to execute transaction {digest:?}: {e:?}")); assert!(executed_locally); @@ -120,8 +119,7 @@ async fn test_fullnode_wal_log() -> Result<(), anyhow::Error> { let mut txns = batch_make_transfer_transactions(context, txn_count).await; assert!( txns.len() >= txn_count, - "Expect at least {} txns. Do we generate enough gas objects during genesis?", - txn_count, + "Expect at least {txn_count} txns. Do we generate enough gas objects during genesis?", ); // As a comparison, we first verify a tx can go through let txn = txns.swap_remove(0); @@ -132,7 +130,7 @@ async fn test_fullnode_wal_log() -> Result<(), anyhow::Error> { ExecuteTransactionRequestType::WaitForLocalExecution, ) .await - .unwrap_or_else(|e| panic!("Failed to execute transaction {:?}: {:?}", digest, e)); + .unwrap_or_else(|e| panic!("Failed to execute transaction {digest:?}: {e:?}")); let validator_addresses = test_cluster.get_validator_pubkeys(); assert_eq!(validator_addresses.len(), 4); @@ -269,7 +267,7 @@ async fn test_tx_across_epoch_boundaries() { Err(QuorumDriverError::TimeoutBeforeFinality) => { info!(?tx_digest, "tx result: timeout and will retry") } - Err(other) => panic!("unexpected error: {:?}", other), + Err(other) => panic!("unexpected error: {other:?}"), } }); @@ -288,7 +286,7 @@ async fn test_tx_across_epoch_boundaries() { let start = std::time::Instant::now(); match tokio::time::timeout(tokio::time::Duration::from_secs(15), result_rx.recv()).await { Ok(Some(effects_cert)) if effects_cert.epoch() == 1 => (), - other => panic!("unexpected error: {:?}", other), + other => panic!("unexpected error: {other:?}"), } info!("test completed in {:?}", start.elapsed()); } @@ -314,8 +312,7 @@ async fn execute_transaction_v1() -> Result<(), anyhow::Error> { let mut txns = batch_make_transfer_transactions(context, txn_count).await; assert!( txns.len() >= txn_count, - "Expect at least {} txns. Do we generate enough gas objects during genesis?", - txn_count, + "Expect at least {txn_count} txns. Do we generate enough gas objects during genesis?", ); // Quorum driver does not execute txn locally diff --git a/crates/iota-enum-compat-util/src/lib.rs b/crates/iota-enum-compat-util/src/lib.rs index 342c83824b4..58c20fd92fa 100644 --- a/crates/iota-enum-compat-util/src/lib.rs +++ b/crates/iota-enum-compat-util/src/lib.rs @@ -17,10 +17,10 @@ pub fn check_enum_compat_order(snapshot_file: PathBuf) { let mut file = std::fs::File::create(snapshot_file).unwrap(); let content: String = serde_yaml::to_string(&new_map).unwrap(); - write!(file, "{}", content).unwrap(); + write!(file, "{content}").unwrap(); return; } - panic!("Error reading file: {:?}: err {:?}", snapshot_file, err); + panic!("Error reading file: {snapshot_file:?}: err {err:?}"); } let existing_map: std::collections::BTreeMap = @@ -31,8 +31,7 @@ pub fn check_enum_compat_order(snapshot_file: PathBuf) { match new_map.get(&pos) { None => { panic!( - "Enum variant {} has been removed. Not allowed: enum must be backward compatible.", - val + "Enum variant {val} has been removed. Not allowed: enum must be backward compatible." ); } Some(new_val) if new_val == &val => continue, @@ -48,5 +47,5 @@ pub fn check_enum_compat_order(snapshot_file: PathBuf) { let mut file = std::fs::File::create(snapshot_file).unwrap(); let content: String = serde_yaml::to_string(&new_map).unwrap(); - write!(file, "{}", content).unwrap(); + write!(file, "{content}").unwrap(); } diff --git a/crates/iota-faucet/src/bin/merge_coins.rs b/crates/iota-faucet/src/bin/merge_coins.rs index ea66cffa8b0..80dcffe8f6f 100644 --- a/crates/iota-faucet/src/bin/merge_coins.rs +++ b/crates/iota-faucet/src/bin/merge_coins.rs @@ -71,7 +71,7 @@ async fn _split_coins_equally( ) .await?; - println!("{:?}", resp); + println!("{resp:?}"); Ok(()) } diff --git a/crates/iota-faucet/src/faucet/simple_faucet.rs b/crates/iota-faucet/src/faucet/simple_faucet.rs index 91478d97206..423aaf89f9d 100644 --- a/crates/iota-faucet/src/faucet/simple_faucet.rs +++ b/crates/iota-faucet/src/faucet/simple_faucet.rs @@ -718,8 +718,7 @@ impl SimpleFaucet { .to_vec(); if created.len() != number_of_coins { return Err(FaucetError::CoinAmountTransferredIncorrect(format!( - "PayIota Transaction should create exact {:?} new coins, but got {:?}", - number_of_coins, created + "PayIota Transaction should create exact {number_of_coins:?} new coins, but got {created:?}" ))); } assert!( @@ -877,7 +876,7 @@ impl SimpleFaucet { loop { let coin_id = consumer .try_recv() - .unwrap_or_else(|e| panic!("Expect the {}th candidate but got {}", i, e)); + .unwrap_or_else(|e| panic!("Expect the {i}th candidate but got {e}")); candidates.insert(coin_id); i += 1; if i == expected_gas_count { @@ -1242,8 +1241,7 @@ mod tests { assert_eq!(available as usize, candidates.len()); assert_eq!( candidates, gas_coins, - "gases: {:?}, candidates: {:?}", - gas_coins, candidates + "gases: {gas_coins:?}, candidates: {candidates:?}" ); } @@ -1294,8 +1292,7 @@ mod tests { assert_eq!(available as usize, candidates.len()); assert_eq!( candidates, gas_coins, - "gases: {:?}, candidates: {:?}", - gas_coins, candidates + "gases: {gas_coins:?}, candidates: {candidates:?}" ); } @@ -1516,8 +1513,7 @@ mod tests { assert_eq!(discarded, 1); assert_eq!( candidates, gas_coins, - "gases: {:?}, candidates: {:?}", - gas_coins, candidates + "gases: {gas_coins:?}, candidates: {candidates:?}" ); } diff --git a/crates/iota-faucet/src/server.rs b/crates/iota-faucet/src/server.rs index e609198c50b..37622d726b2 100644 --- a/crates/iota-faucet/src/server.rs +++ b/crates/iota-faucet/src/server.rs @@ -275,6 +275,6 @@ async fn handle_error(error: BoxError) -> impl IntoResponse { ( StatusCode::INTERNAL_SERVER_ERROR, - Cow::from(format!("Unhandled internal error: {}", error)), + Cow::from(format!("Unhandled internal error: {error}")), ) } diff --git a/crates/iota-framework/tests/build-system-packages.rs b/crates/iota-framework/tests/build-system-packages.rs index 01dbf7bd260..31feeafb2f1 100644 --- a/crates/iota-framework/tests/build-system-packages.rs +++ b/crates/iota-framework/tests/build-system-packages.rs @@ -337,7 +337,7 @@ fn relocate_docs(files: &[(String, String)], output: &mut BTreeMap", title_type, package, name, name, anchor) + format!("---\ntitle: {title_type}{package}\nsidebar_label: {name}\nslug: {name}\n---\nimport Link from '@docusaurus/Link';\n\n") }).to_string() }); } diff --git a/crates/iota-genesis-builder/examples/build_and_compile_native_token.rs b/crates/iota-genesis-builder/examples/build_and_compile_native_token.rs index f6f872191c4..7f60ac3fbe6 100644 --- a/crates/iota-genesis-builder/examples/build_and_compile_native_token.rs +++ b/crates/iota-genesis-builder/examples/build_and_compile_native_token.rs @@ -30,7 +30,7 @@ fn main() -> anyhow::Result<()> { ), ); - println!("DOGE token: {:?}", native_token_a); + println!("DOGE token: {native_token_a:?}"); let compiled_package_a = package_builder::build_and_compile(native_token_a)?; println!( @@ -55,7 +55,7 @@ fn main() -> anyhow::Result<()> { ), ); - println!("SMR token: {:?}", native_token_b); + println!("SMR token: {native_token_b:?}"); let compiled_package_b = package_builder::build_and_compile(native_token_b)?; println!( diff --git a/crates/iota-genesis-builder/src/lib.rs b/crates/iota-genesis-builder/src/lib.rs index 0d8a3d2e99f..b92032bd20c 100644 --- a/crates/iota-genesis-builder/src/lib.rs +++ b/crates/iota-genesis-builder/src/lib.rs @@ -778,7 +778,7 @@ impl Builder { let committee = system_state.get_current_epoch_committee(); for signature in self.signatures.values() { if !self.validators.contains_key(&signature.authority) { - panic!("found signature for unknown validator: {:#?}", signature); + panic!("found signature for unknown validator: {signature:#?}"); } signature diff --git a/crates/iota-genesis-builder/src/stardust/process_outputs.rs b/crates/iota-genesis-builder/src/stardust/process_outputs.rs index 6a0c1c1e69a..83297ed374f 100644 --- a/crates/iota-genesis-builder/src/stardust/process_outputs.rs +++ b/crates/iota-genesis-builder/src/stardust/process_outputs.rs @@ -321,8 +321,7 @@ impl Drop for SwapSplitIterator { self.swap_split_map.validate_successful_swap_split() { panic!( - "For at least one address, the SwapSplit operation was not fully performed. Origin: {}, destination: {}, tokens left: {}, timelocked tokens left: {}", - origin, destination, tokens_target, tokens_timelocked_target + "For at least one address, the SwapSplit operation was not fully performed. Origin: {origin}, destination: {destination}, tokens left: {tokens_target}, timelocked tokens left: {tokens_timelocked_target}" ) } debug!( diff --git a/crates/iota-genesis-builder/src/stardust/types/address_swap_map.rs b/crates/iota-genesis-builder/src/stardust/types/address_swap_map.rs index 2d8151bddf4..12b8a3564e0 100644 --- a/crates/iota-genesis-builder/src/stardust/types/address_swap_map.rs +++ b/crates/iota-genesis-builder/src/stardust/types/address_swap_map.rs @@ -200,7 +200,7 @@ mod tests { fn write_temp_file(content: &str) -> NamedTempFile { let mut file = NamedTempFile::new().unwrap(); - writeln!(file, "{}", content).unwrap(); + writeln!(file, "{content}").unwrap(); file } diff --git a/crates/iota-graphql-e2e-tests/tests/tests.rs b/crates/iota-graphql-e2e-tests/tests/tests.rs index caf7b60a628..1357e13c31a 100644 --- a/crates/iota-graphql-e2e-tests/tests/tests.rs +++ b/crates/iota-graphql-e2e-tests/tests/tests.rs @@ -88,7 +88,7 @@ async fn run_test(path: &Path) -> Result<(), Box> { let mut hasher = std::collections::hash_map::DefaultHasher::new(); path.to_path_buf().hash(&mut hasher); let hash = hasher.finish(); - let db_name = format!("iota_graphql_test_{}", hash); + let db_name = format!("iota_graphql_test_{hash}"); // Use the hash as a seed to generate a random port number let base_port = hash as u16 % 8192; diff --git a/crates/iota-graphql-rpc-client/examples/checkpoint.rs b/crates/iota-graphql-rpc-client/examples/checkpoint.rs index d147719c37d..4ac1511904b 100644 --- a/crates/iota-graphql-rpc-client/examples/checkpoint.rs +++ b/crates/iota-graphql-rpc-client/examples/checkpoint.rs @@ -61,7 +61,7 @@ async fn main() -> Result<(), anyhow::Error> { .ok_or(anyhow::anyhow!("missing sequenceNumber"))? ); // Full response - println!("{:#?}", resp_body); + println!("{resp_body:#?}"); Ok(()) } diff --git a/crates/iota-graphql-rpc-client/src/simple_client.rs b/crates/iota-graphql-rpc-client/src/simple_client.rs index 2b5dfac4649..5efd3b8ff5c 100644 --- a/crates/iota-graphql-rpc-client/src/simple_client.rs +++ b/crates/iota-graphql-rpc-client/src/simple_client.rs @@ -76,7 +76,7 @@ impl SimpleClient { // Make type defs which is a csv is the form of $var_name: $var_type let type_defs_csv = type_defs .iter() - .map(|(name, ty)| format!("${}: {}", name, ty)) + .map(|(name, ty)| format!("${name}: {ty}")) .collect::>() .join(", "); let query = format!( diff --git a/crates/iota-graphql-rpc/src/config.rs b/crates/iota-graphql-rpc/src/config.rs index 0301bdeaa66..d059a76cff9 100644 --- a/crates/iota-graphql-rpc/src/config.rs +++ b/crates/iota-graphql-rpc/src/config.rs @@ -358,7 +358,7 @@ impl ConnectionConfig { prom_port: u16, ) -> Self { Self { - db_url: format!("postgres://postgres:postgrespw@localhost:5432/{}", db_name), + db_url: format!("postgres://postgres:postgrespw@localhost:5432/{db_name}"), port, prom_port, ..Default::default() diff --git a/crates/iota-graphql-rpc/src/error.rs b/crates/iota-graphql-rpc/src/error.rs index f2b110873f1..99ae04ef59f 100644 --- a/crates/iota-graphql-rpc/src/error.rs +++ b/crates/iota-graphql-rpc/src/error.rs @@ -84,7 +84,7 @@ pub enum Error { impl ErrorExtensions for Error { fn extend(&self) -> async_graphql::Error { - async_graphql::Error::new(format!("{}", self)).extend_with(|_err, e| match self { + async_graphql::Error::new(format!("{self}")).extend_with(|_err, e| match self { Error::CursorNoFirstLast | Error::PageTooLarge(_, _) | Error::ProtocolVersionUnsupported(_, _) diff --git a/crates/iota-graphql-rpc/src/extensions/logger.rs b/crates/iota-graphql-rpc/src/extensions/logger.rs index 903846cc5b6..24b7fe16caa 100644 --- a/crates/iota-graphql-rpc/src/extensions/logger.rs +++ b/crates/iota-graphql-rpc/src/extensions/logger.rs @@ -138,10 +138,10 @@ impl Extension for LoggerExtension { } match s { PathSegment::Index(idx) => { - let _ = write!(&mut path, "{}", idx); + let _ = write!(&mut path, "{idx}"); } PathSegment::Field(name) => { - let _ = write!(&mut path, "{}", name); + let _ = write!(&mut path, "{name}"); } } } diff --git a/crates/iota-graphql-rpc/src/main.rs b/crates/iota-graphql-rpc/src/main.rs index 9185af16100..7d175196df6 100644 --- a/crates/iota-graphql-rpc/src/main.rs +++ b/crates/iota-graphql-rpc/src/main.rs @@ -38,16 +38,16 @@ async fn main() { panic!("Failed to write configuration to {}: {e}", path.display()) }); } else { - println!("{}", toml); + println!("{toml}"); } } Command::GenerateSchema { file } => { let out = export_schema(); if let Some(file) = file { - println!("Write schema to file: {:?}", file); + println!("Write schema to file: {file:?}"); std::fs::write(file, &out).unwrap(); } else { - println!("{}", out); + println!("{out}"); } } Command::StartServer { @@ -90,7 +90,7 @@ async fn main() { tokio::select! { result = graphql_service_handle => { if let Err(e) = result { - println!("GraphQL service crashed or exited with error: {:?}", e); + println!("GraphQL service crashed or exited with error: {e:?}"); } } _ = tokio::signal::ctrl_c() => { diff --git a/crates/iota-graphql-rpc/src/raw_query.rs b/crates/iota-graphql-rpc/src/raw_query.rs index ce7bd23b2f6..93d40fdc84d 100644 --- a/crates/iota-graphql-rpc/src/raw_query.rs +++ b/crates/iota-graphql-rpc/src/raw_query.rs @@ -57,7 +57,7 @@ impl RawQuery { /// conditions using `AND`. pub(crate) fn filter(mut self, condition: T) -> Self { self.where_ = match self.where_ { - Some(where_) => Some(format!("({}) AND {}", where_, condition)), + Some(where_) => Some(format!("({where_}) AND {condition}")), None => Some(condition.to_string()), }; @@ -68,7 +68,7 @@ impl RawQuery { /// conditions using `OR`. pub(crate) fn or_filter(mut self, condition: T) -> Self { self.where_ = match self.where_ { - Some(where_) => Some(format!("({}) OR {}", where_, condition)), + Some(where_) => Some(format!("({where_}) OR {condition}")), None => Some(condition.to_string()), }; @@ -147,7 +147,7 @@ impl RawQuery { } for (i, sql) in sql_components { - result.push_str(&format!("${}", i)); + result.push_str(&format!("${i}")); result.push_str(sql); } diff --git a/crates/iota-graphql-rpc/src/server/builder.rs b/crates/iota-graphql-rpc/src/server/builder.rs index 8c40bcffe7b..dc7aa5aa358 100644 --- a/crates/iota-graphql-rpc/src/server/builder.rs +++ b/crates/iota-graphql-rpc/src/server/builder.rs @@ -135,7 +135,7 @@ impl Server { axum::serve( TcpListener::bind(address) .await - .map_err(|e| Error::Internal(format!("listener bind failed: {}", e)))?, + .map_err(|e| Error::Internal(format!("listener bind failed: {e}")))?, router.into_make_service_with_connect_info::(), ) .with_graceful_shutdown(async move { @@ -143,7 +143,7 @@ impl Server { info!("Shutdown signal received, terminating graphql service"); }) .await - .map_err(|e| Error::Internal(format!("Server run failed: {}", e))) + .map_err(|e| Error::Internal(format!("Server run failed: {e}"))) }) }; @@ -374,7 +374,7 @@ impl ServerBuilder { router, address: address .parse() - .map_err(|_| Error::Internal(format!("Failed to parse address {}", address)))?, + .map_err(|_| Error::Internal(format!("Failed to parse address {address}")))?, watermark_task, system_package_task, trigger_exchange_rates_task, @@ -435,7 +435,7 @@ impl ServerBuilder { // time). config.service.limits.request_timeout_ms.into(), ) - .map_err(|e| Error::Internal(format!("Failed to create pg connection pool: {}", e)))?; + .map_err(|e| Error::Internal(format!("Failed to create pg connection pool: {e}")))?; // DB let db = Db::new( @@ -1105,7 +1105,7 @@ pub mod tests { let resp = reqwest::get(&url).await.unwrap(); assert_eq!(resp.status(), reqwest::StatusCode::OK); - let url_with_param = format!("{}?max_checkpoint_lag_ms=1", url); + let url_with_param = format!("{url}?max_checkpoint_lag_ms=1"); let resp = reqwest::get(&url_with_param).await.unwrap(); assert_eq!(resp.status(), reqwest::StatusCode::GATEWAY_TIMEOUT); } diff --git a/crates/iota-graphql-rpc/src/server/graphiql_server.rs b/crates/iota-graphql-rpc/src/server/graphiql_server.rs index 3fc30a0b9bb..dcf7a61d6b2 100644 --- a/crates/iota-graphql-rpc/src/server/graphiql_server.rs +++ b/crates/iota-graphql-rpc/src/server/graphiql_server.rs @@ -17,7 +17,7 @@ async fn graphiql( path: Option>, ) -> impl axum::response::IntoResponse { let endpoint = if let Some(Path(path)) = path { - format!("/graphql/{}", path) + format!("/graphql/{path}") } else { "/graphql".to_string() }; diff --git a/crates/iota-graphql-rpc/src/server/version.rs b/crates/iota-graphql-rpc/src/server/version.rs index b1c58ddcb1d..e59782e5fb2 100644 --- a/crates/iota-graphql-rpc/src/server/version.rs +++ b/crates/iota-graphql-rpc/src/server/version.rs @@ -195,7 +195,7 @@ mod tests { return plain_request(); } Request::builder() - .uri(format!("/graphql/{}", version)) + .uri(format!("/graphql/{version}")) .body(Body::empty()) .unwrap() } diff --git a/crates/iota-graphql-rpc/src/test_infra/cluster.rs b/crates/iota-graphql-rpc/src/test_infra/cluster.rs index 31e3639ed9b..406a0592ee2 100644 --- a/crates/iota-graphql-rpc/src/test_infra/cluster.rs +++ b/crates/iota-graphql-rpc/src/test_infra/cluster.rs @@ -121,7 +121,7 @@ pub async fn serve_executor( // can send a cancellation token on cleanup let cancellation_token = CancellationToken::new(); - let executor_server_url: SocketAddr = format!("127.0.0.1:{}", internal_data_source_rpc_port) + let executor_server_url: SocketAddr = format!("127.0.0.1:{internal_data_source_rpc_port}") .parse() .unwrap(); @@ -139,7 +139,7 @@ pub async fn serve_executor( db_url, true, None, - format!("http://{}", executor_server_url), + format!("http://{executor_server_url}"), IndexerTypeConfig::writer_mode(snapshot_config.clone(), epochs_to_keep), Some(data_ingestion_path), cancellation_token.clone(), @@ -189,11 +189,10 @@ pub async fn wait_for_graphql_checkpoint_pruned( let query = format!( r#" {{ - checkpoint(id: {{ sequenceNumber: {} }}) {{ + checkpoint(id: {{ sequenceNumber: {checkpoint} }}) {{ sequenceNumber }} - }}"#, - checkpoint + }}"# ); let timeout = base_timeout.mul_f64(checkpoint.max(1) as f64); @@ -395,8 +394,7 @@ impl ExecutorCluster { } }) .await - .unwrap_or_else(|_| panic!("Timeout waiting for indexer to update objects snapshot - latest_cp: {}, latest_snapshot_cp: {}", - latest_cp, latest_snapshot_cp)); + .unwrap_or_else(|_| panic!("Timeout waiting for indexer to update objects snapshot - latest_cp: {latest_cp}, latest_snapshot_cp: {latest_snapshot_cp}")); } /// Sends a cancellation signal to the graphql and indexer services, waits diff --git a/crates/iota-graphql-rpc/src/types/date_time.rs b/crates/iota-graphql-rpc/src/types/date_time.rs index d856075b538..703671343fe 100644 --- a/crates/iota-graphql-rpc/src/types/date_time.rs +++ b/crates/iota-graphql-rpc/src/types/date_time.rs @@ -34,7 +34,7 @@ impl ScalarType for DateTime { fn parse(value: Value) -> InputValueResult { match value { Value::String(s) => DateTime::from_str(&s) - .map_err(|e| InputValueError::custom(format!("Error parsing DateTime: {}", e))), + .map_err(|e| InputValueError::custom(format!("Error parsing DateTime: {e}"))), _ => Err(InputValueError::expected_type(value)), } } diff --git a/crates/iota-graphql-rpc/src/types/display.rs b/crates/iota-graphql-rpc/src/types/display.rs index c178abf4081..3f3ed1fab91 100644 --- a/crates/iota-graphql-rpc/src/types/display.rs +++ b/crates/iota-graphql-rpc/src/types/display.rs @@ -126,7 +126,7 @@ fn parse_template(template: &str, move_struct: &MoveStruct) -> Result { in_braces = false; let value = get_value_from_move_struct(move_struct, &var_name)?; - output = output.replace(&format!("{{{}}}", var_name), &value.to_string()); + output = output.replace(&format!("{{{var_name}}}"), &value.to_string()); } _ if !escaped => { if in_braces { diff --git a/crates/iota-graphql-rpc/src/types/dry_run_result.rs b/crates/iota-graphql-rpc/src/types/dry_run_result.rs index 38e8ef0e0d7..e86fed06012 100644 --- a/crates/iota-graphql-rpc/src/types/dry_run_result.rs +++ b/crates/iota-graphql-rpc/src/types/dry_run_result.rs @@ -72,8 +72,7 @@ impl TryFrom for DryRunEffect { .collect::, anyhow::Error>>() .map_err(|e| { Error::Internal(format!( - "Failed to parse results returned from dev inspect: {:?}", - e + "Failed to parse results returned from dev inspect: {e:?}" )) })?; let return_values = result @@ -88,8 +87,7 @@ impl TryFrom for DryRunEffect { .collect::, anyhow::Error>>() .map_err(|e| { Error::Internal(format!( - "Failed to parse results returned from dev inspect: {:?}", - e + "Failed to parse results returned from dev inspect: {e:?}" )) })?; Ok(Self { diff --git a/crates/iota-graphql-rpc/src/types/event/mod.rs b/crates/iota-graphql-rpc/src/types/event/mod.rs index 896cc666b27..62af7323b99 100644 --- a/crates/iota-graphql-rpc/src/types/event/mod.rs +++ b/crates/iota-graphql-rpc/src/types/event/mod.rs @@ -180,7 +180,7 @@ impl Event { // to `RawQuery` here. let query_string = ev_lookups.iter() .map(|&(tx, ev)| { - format!("SELECT * FROM events WHERE tx_sequence_number = {} AND event_sequence_number = {}", tx, ev) + format!("SELECT * FROM events WHERE tx_sequence_number = {tx} AND event_sequence_number = {ev}") }) .collect::>() .join(" UNION ALL "); diff --git a/crates/iota-graphql-rpc/src/types/move_value.rs b/crates/iota-graphql-rpc/src/types/move_value.rs index 06a411f531b..4bb2a010683 100644 --- a/crates/iota-graphql-rpc/src/types/move_value.rs +++ b/crates/iota-graphql-rpc/src/types/move_value.rs @@ -149,8 +149,7 @@ impl MoveValue { BoundedVisitor::deserialize_value(&self.bcs.0[..], &layout).map_err(|_| { let type_tag: TypeTag = (&layout).into(); Error::Internal(format!( - "Failed to deserialize Move value for type: {}", - type_tag + "Failed to deserialize Move value for type: {type_tag}" )) }) } @@ -513,7 +512,7 @@ mod tests { // The format for type from its `Display` impl does not technically match the // format that the RPC expects from the data layer (where a type's // package should be canonicalized), but it will suffice. - data_with_tag(format!("{}", tag), layout, data) + data_with_tag(format!("{tag}"), layout, data) } fn data_with_tag( diff --git a/crates/iota-graphql-rpc/src/types/object.rs b/crates/iota-graphql-rpc/src/types/object.rs index 677c997d748..6981ff80a95 100644 --- a/crates/iota-graphql-rpc/src/types/object.rs +++ b/crates/iota-graphql-rpc/src/types/object.rs @@ -1602,8 +1602,6 @@ where RawQuery::new( format!( "SELECT * FROM (({id_query}) UNION ALL ({key_query})) AS candidates", - id_query = id_query, - key_query = key_query, ), id_bindings.into_iter().chain(key_bindings).collect(), ) diff --git a/crates/iota-graphql-rpc/src/types/transaction_block_effects.rs b/crates/iota-graphql-rpc/src/types/transaction_block_effects.rs index c9aa6c141c0..51d1092513e 100644 --- a/crates/iota-graphql-rpc/src/types/transaction_block_effects.rs +++ b/crates/iota-graphql-rpc/src/types/transaction_block_effects.rs @@ -148,7 +148,7 @@ impl TransactionBlockEffects { break 'error error.to_string(); }; let fname_string = if let Some(fname) = &loc.function_name { - format!("::{}'", fname) + format!("::{fname}'") } else { "'".to_string() }; diff --git a/crates/iota-graphql-rpc/src/types/zklogin_verify_signature.rs b/crates/iota-graphql-rpc/src/types/zklogin_verify_signature.rs index fdba82eb07c..5fc84680db5 100644 --- a/crates/iota-graphql-rpc/src/types/zklogin_verify_signature.rs +++ b/crates/iota-graphql-rpc/src/types/zklogin_verify_signature.rs @@ -181,5 +181,5 @@ pub(crate) async fn verify_zklogin_signature( /// Format the error message for failed JWK read. fn as_jwks_read_error(e: String) -> Error { - Error::Internal(format!("Failed to read JWK from system object 0x7: {}", e)) + Error::Internal(format!("Failed to read JWK from system object 0x7: {e}")) } diff --git a/crates/iota-graphql-rpc/tests/e2e_tests.rs b/crates/iota-graphql-rpc/tests/e2e_tests.rs index 806d57b4712..a93b88fe48a 100644 --- a/crates/iota-graphql-rpc/tests/e2e_tests.rs +++ b/crates/iota-graphql-rpc/tests/e2e_tests.rs @@ -88,10 +88,9 @@ mod tests { .unwrap(); let exp = format!( - "{{\"data\":{{\"chainIdentifier\":\"{}\"}}}}", - chain_id_actual + "{{\"data\":{{\"chainIdentifier\":\"{chain_id_actual}\"}}}}" ); - assert_eq!(&format!("{}", res), &exp); + assert_eq!(&format!("{res}"), &exp); cluster.cleanup_resources().await } @@ -114,8 +113,7 @@ mod tests { let chain_id_actual = format!("{}", ChainIdentifier::from(genesis_checkpoint_digest1)); let exp = format!( - "{{\"data\":{{\"chainIdentifier\":\"{}\"}}}}", - chain_id_actual + "{{\"data\":{{\"chainIdentifier\":\"{chain_id_actual}\"}}}}" ); let cluster = iota_graphql_rpc::test_infra::cluster::serve_executor( ConnectionConfig::default(), @@ -141,7 +139,7 @@ mod tests { .await .unwrap(); - assert_eq!(&format!("{}", res), &exp); + assert_eq!(&format!("{res}"), &exp); } #[tokio::test] diff --git a/crates/iota-indexer/src/db.rs b/crates/iota-indexer/src/db.rs index 607e8d65a1e..996d4cf471b 100644 --- a/crates/iota-indexer/src/db.rs +++ b/crates/iota-indexer/src/db.rs @@ -146,8 +146,7 @@ pub fn new_connection_pool_with_config( pub fn get_pool_connection(pool: &ConnectionPool) -> Result { pool.get().map_err(|e| { IndexerError::PgPoolConnection(format!( - "Failed to get connection from PG connection pool with error: {:?}", - e + "Failed to get connection from PG connection pool with error: {e:?}" )) }) } @@ -251,8 +250,7 @@ pub mod setup_postgres { ) -> Result<(), IndexerError> { let db_url_secret = indexer_config.get_db_url().map_err(|e| { IndexerError::PgPoolConnection(format!( - "Failed parsing database url with error {:?}", - e + "Failed parsing database url with error {e:?}" )) })?; let db_url = db_url_secret.expose_secret(); @@ -274,8 +272,7 @@ pub mod setup_postgres { if indexer_config.reset_db { reset_database(&mut conn).map_err(|e| { let db_err_msg = format!( - "Failed resetting database with url: {:?} and error: {:?}", - db_url, e + "Failed resetting database with url: {db_url:?} and error: {e:?}" ); error!("{}", db_err_msg); IndexerError::PostgresReset(db_err_msg) diff --git a/crates/iota-indexer/src/handlers/checkpoint_handler.rs b/crates/iota-indexer/src/handlers/checkpoint_handler.rs index 2a1eb08313b..8a29e642d2a 100644 --- a/crates/iota-indexer/src/handlers/checkpoint_handler.rs +++ b/crates/iota-indexer/src/handlers/checkpoint_handler.rs @@ -383,8 +383,7 @@ impl CheckpointHandler { let actual_tx_digest = tx.transaction.digest(); if tx_digest != *actual_tx_digest { return Err(IndexerError::FullNodeReading(format!( - "Transactions has different ordering from CheckpointContents, for checkpoint {}, Mismatch found at {} v.s. {}", - checkpoint_seq, tx_digest, actual_tx_digest, + "Transactions has different ordering from CheckpointContents, for checkpoint {checkpoint_seq}, Mismatch found at {tx_digest} v.s. {actual_tx_digest}", ))); } diff --git a/crates/iota-indexer/src/handlers/tx_processor.rs b/crates/iota-indexer/src/handlers/tx_processor.rs index fccf61aa650..4727af073c6 100644 --- a/crates/iota-indexer/src/handlers/tx_processor.rs +++ b/crates/iota-indexer/src/handlers/tx_processor.rs @@ -103,8 +103,7 @@ impl TxChangesProcessor { effects, tx.input_objects().unwrap_or_else(|e| { panic!( - "Checkpointed tx {:?} has invalid input objects: {e}", - tx_digest, + "Checkpointed tx {tx_digest:?} has invalid input objects: {e}", ) }), None, diff --git a/crates/iota-indexer/src/indexer_reader.rs b/crates/iota-indexer/src/indexer_reader.rs index b52e2698d95..2a481b2ff8f 100644 --- a/crates/iota-indexer/src/indexer_reader.rs +++ b/crates/iota-indexer/src/indexer_reader.rs @@ -349,8 +349,7 @@ impl IndexerReader { .await .map_err(|e| { IndexerError::PostgresRead(format!( - "Fail to fetch package from package store with error {:?}", - e + "Fail to fetch package from package store with error {e:?}" )) })? .as_ref() @@ -467,8 +466,7 @@ impl IndexerReader { let system_state: IotaSystemStateSummary = bcs::from_bytes(&stored_epoch.system_state) .map_err(|_| { IndexerError::PersistentStorageDataCorruption(format!( - "Failed to deserialize `system_state` for epoch {:?}", - epoch, + "Failed to deserialize `system_state` for epoch {epoch:?}", )) })?; Ok(system_state) @@ -772,7 +770,7 @@ impl IndexerReader { let object_type = struct_tag.to_canonical_string(/* with_prefix */ true); query = - query.filter(objects::object_type.like(format!("{}%", object_type))); + query.filter(objects::object_type.like(format!("{object_type}%"))); } IotaObjectDataFilter::MatchAny(filters) => { let mut condition = "(".to_string(); @@ -782,11 +780,11 @@ impl IndexerReader { struct_tag.to_canonical_string(/* with_prefix */ true); if i == 0 { condition += - format!("objects.object_type LIKE '{}%'", object_type) + format!("objects.object_type LIKE '{object_type}%'") .as_str(); } else { condition += - format!(" OR objects.object_type LIKE '{}%'", object_type) + format!(" OR objects.object_type LIKE '{object_type}%'") .as_str(); } } else { @@ -804,7 +802,7 @@ impl IndexerReader { let object_type = struct_tag.to_canonical_string(/* with_prefix */ true); query = query.filter( - objects::object_type.not_like(format!("{}%", object_type)), + objects::object_type.not_like(format!("{object_type}%")), ); } else { return Err(IndexerError::InvalidArgument( @@ -850,8 +848,7 @@ impl IndexerReader { .map(|id| { ObjectID::from_bytes(id.clone()).map_err(|_e| { IndexerError::PersistentStorageDataCorruption(format!( - "Can't convert {:?} to ObjectID", - id, + "Can't convert {id:?} to ObjectID", )) }) }) @@ -961,9 +958,9 @@ impl IndexerReader { }; let cursor_clause = if let Some(cursor_tx_seq) = cursor_tx_seq { if is_descending { - format!("AND {TX_SEQUENCE_NUMBER_STR} < {}", cursor_tx_seq) + format!("AND {TX_SEQUENCE_NUMBER_STR} < {cursor_tx_seq}") } else { - format!("AND {TX_SEQUENCE_NUMBER_STR} > {}", cursor_tx_seq) + format!("AND {TX_SEQUENCE_NUMBER_STR} > {cursor_tx_seq}") } } else { "".to_string() @@ -993,15 +990,13 @@ impl IndexerReader { (Some(module), Some(function)) => ( "tx_calls_fun".into(), format!( - "package = '\\x{}'::bytea AND module = '{}' AND func = '{}'", - package, module, function + "package = '\\x{package}'::bytea AND module = '{module}' AND func = '{function}'" ), ), (Some(module), None) => ( "tx_calls_mod".into(), format!( - "package = '\\x{}'::bytea AND module = '{}'", - package, module + "package = '\\x{package}'::bytea AND module = '{module}'" ), ), (None, Some(_)) => { @@ -1011,7 +1006,7 @@ impl IndexerReader { } (None, None) => ( "tx_calls_pkg".into(), - format!("package = '\\x{}'::bytea", package), + format!("package = '\\x{package}'::bytea"), ), } } @@ -1019,28 +1014,28 @@ impl IndexerReader { let object_id = Hex::encode(object_id.to_vec()); ( "tx_input_objects".into(), - format!("object_id = '\\x{}'::bytea", object_id), + format!("object_id = '\\x{object_id}'::bytea"), ) } Some(TransactionFilter::ChangedObject(object_id)) => { let object_id = Hex::encode(object_id.to_vec()); ( "tx_changed_objects".into(), - format!("object_id = '\\x{}'::bytea", object_id), + format!("object_id = '\\x{object_id}'::bytea"), ) } Some(TransactionFilter::FromAddress(from_address)) => { let from_address = Hex::encode(from_address.to_vec()); ( "tx_senders".into(), - format!("sender = '\\x{}'::bytea", from_address), + format!("sender = '\\x{from_address}'::bytea"), ) } Some(TransactionFilter::ToAddress(to_address)) => { let to_address = Hex::encode(to_address.to_vec()); ( "tx_recipients".into(), - format!("recipient = '\\x{}'::bytea", to_address), + format!("recipient = '\\x{to_address}'::bytea"), ) } Some(TransactionFilter::FromAndToAddress { from, to }) => { @@ -1050,13 +1045,11 @@ impl IndexerReader { let cursor_clause = if let Some(cursor_tx_seq) = cursor_tx_seq { if is_descending { format!( - "AND tx_senders.{TX_SEQUENCE_NUMBER_STR} < {}", - cursor_tx_seq + "AND tx_senders.{TX_SEQUENCE_NUMBER_STR} < {cursor_tx_seq}" ) } else { format!( - "AND tx_senders.{TX_SEQUENCE_NUMBER_STR} > {}", - cursor_tx_seq + "AND tx_senders.{TX_SEQUENCE_NUMBER_STR} > {cursor_tx_seq}" ) } } else { @@ -1067,17 +1060,12 @@ impl IndexerReader { FROM tx_senders \ JOIN tx_recipients \ ON tx_senders.{TX_SEQUENCE_NUMBER_STR} = tx_recipients.{TX_SEQUENCE_NUMBER_STR} \ - WHERE tx_senders.sender = '\\x{}'::BYTEA \ - AND tx_recipients.recipient = '\\x{}'::BYTEA \ - {} \ - ORDER BY {TX_SEQUENCE_NUMBER_STR} {} \ - LIMIT {}) AS inner_query + WHERE tx_senders.sender = '\\x{from_address}'::BYTEA \ + AND tx_recipients.recipient = '\\x{to_address}'::BYTEA \ + {cursor_clause} \ + ORDER BY {TX_SEQUENCE_NUMBER_STR} {order_str} \ + LIMIT {limit}) AS inner_query ", - from_address, - to_address, - cursor_clause, - order_str, - limit, ); (inner_query, "1 = 1".into()) } @@ -1087,26 +1075,18 @@ impl IndexerReader { "( \ ( \ SELECT {TX_SEQUENCE_NUMBER_STR} FROM tx_senders \ - WHERE sender = '\\x{}'::BYTEA {} \ - ORDER BY {TX_SEQUENCE_NUMBER_STR} {} \ - LIMIT {} \ + WHERE sender = '\\x{address}'::BYTEA {cursor_clause} \ + ORDER BY {TX_SEQUENCE_NUMBER_STR} {order_str} \ + LIMIT {limit} \ ) \ UNION \ ( \ SELECT {TX_SEQUENCE_NUMBER_STR} FROM tx_recipients \ - WHERE recipient = '\\x{}'::BYTEA {} \ - ORDER BY {TX_SEQUENCE_NUMBER_STR} {} \ - LIMIT {} \ + WHERE recipient = '\\x{address}'::BYTEA {cursor_clause} \ + ORDER BY {TX_SEQUENCE_NUMBER_STR} {order_str} \ + LIMIT {limit} \ ) \ ) AS combined", - address, - cursor_clause, - order_str, - limit, - address, - cursor_clause, - order_str, - limit, ); (inner_query, "1 = 1".into()) } @@ -1183,8 +1163,7 @@ impl IndexerReader { }; let query = format!( - "SELECT {TX_SEQUENCE_NUMBER_STR} FROM {} WHERE {} {} ORDER BY {TX_SEQUENCE_NUMBER_STR} {} LIMIT {}", - table_name, main_where_clause, cursor_clause, order_str, limit, + "SELECT {TX_SEQUENCE_NUMBER_STR} FROM {table_name} WHERE {main_where_clause} {cursor_clause} ORDER BY {TX_SEQUENCE_NUMBER_STR} {order_str} LIMIT {limit}", ); tracing::debug!("query transaction blocks: {}", query); @@ -1382,13 +1361,11 @@ impl IndexerReader { // Need to remove ambiguities for tx_sequence_number column let cursor_clause = if descending_order { format!( - "(e.{TX_SEQUENCE_NUMBER_STR} < {} OR (e.{TX_SEQUENCE_NUMBER_STR} = {} AND e.{EVENT_SEQUENCE_NUMBER_STR} < {}))", - tx_seq, tx_seq, event_seq + "(e.{TX_SEQUENCE_NUMBER_STR} < {tx_seq} OR (e.{TX_SEQUENCE_NUMBER_STR} = {tx_seq} AND e.{EVENT_SEQUENCE_NUMBER_STR} < {event_seq}))" ) } else { format!( - "(e.{TX_SEQUENCE_NUMBER_STR} > {} OR (e.{TX_SEQUENCE_NUMBER_STR} = {} AND e.{EVENT_SEQUENCE_NUMBER_STR} > {}))", - tx_seq, tx_seq, event_seq + "(e.{TX_SEQUENCE_NUMBER_STR} > {tx_seq} OR (e.{TX_SEQUENCE_NUMBER_STR} = {tx_seq} AND e.{EVENT_SEQUENCE_NUMBER_STR} > {event_seq}))" ) }; let order_clause = if descending_order { @@ -1458,13 +1435,11 @@ impl IndexerReader { let cursor_clause = if descending_order { format!( - "AND ({TX_SEQUENCE_NUMBER_STR} < {} OR ({TX_SEQUENCE_NUMBER_STR} = {} AND {EVENT_SEQUENCE_NUMBER_STR} < {}))", - tx_seq, tx_seq, event_seq + "AND ({TX_SEQUENCE_NUMBER_STR} < {tx_seq} OR ({TX_SEQUENCE_NUMBER_STR} = {tx_seq} AND {EVENT_SEQUENCE_NUMBER_STR} < {event_seq}))" ) } else { format!( - "AND ({TX_SEQUENCE_NUMBER_STR} > {} OR ({TX_SEQUENCE_NUMBER_STR} = {} AND {EVENT_SEQUENCE_NUMBER_STR} > {}))", - tx_seq, tx_seq, event_seq + "AND ({TX_SEQUENCE_NUMBER_STR} > {tx_seq} OR ({TX_SEQUENCE_NUMBER_STR} = {tx_seq} AND {EVENT_SEQUENCE_NUMBER_STR} > {event_seq}))" ) }; let order_clause = if descending_order { @@ -1476,11 +1451,10 @@ impl IndexerReader { format!( " SELECT * FROM events \ - WHERE {} {} \ - ORDER BY {} \ - LIMIT {} + WHERE {main_where_clause} {cursor_clause} \ + ORDER BY {order_clause} \ + LIMIT {limit} ", - main_where_clause, cursor_clause, order_clause, limit, ) }; tracing::debug!("query events: {}", query); @@ -1768,7 +1742,7 @@ impl IndexerReader { coin_type: Option, ) -> Result, IndexerError> { let coin_type_filter = if let Some(coin_type) = coin_type { - format!("= '{}'", coin_type) + format!("= '{coin_type}'") } else { "IS NOT NULL".to_string() }; @@ -1973,7 +1947,7 @@ impl IndexerReader { .package_obj_type_cache .lock() .unwrap() - .cache_get_or_set_with(format!("{}{}", package_id, coin_metadata_type), || { + .cache_get_or_set_with(format!("{package_id}{coin_metadata_type}"), || { get_single_obj_id_from_package_publish(self, package_id, coin_metadata_type.clone()) .unwrap() }); @@ -2001,19 +1975,17 @@ impl IndexerReader { .package_obj_type_cache .lock() .unwrap() - .cache_get_or_set_with(format!("{}{}", package_id, treasury_cap_type), || { + .cache_get_or_set_with(format!("{package_id}{treasury_cap_type}"), || { get_single_obj_id_from_package_publish(self, package_id, treasury_cap_type.clone()) .unwrap() }) .ok_or(IndexerError::Generic(format!( - "Cannot find treasury cap for type {}", - treasury_cap_type + "Cannot find treasury cap for type {treasury_cap_type}" )))?; let treasury_cap_obj_object = self.get_object(&treasury_cap_obj_id, None)? .ok_or(IndexerError::Generic(format!( - "Cannot find treasury cap object with id {}", - treasury_cap_obj_id + "Cannot find treasury cap object with id {treasury_cap_obj_id}" )))?; Ok(TreasuryCap::try_from(treasury_cap_obj_object)?.total_supply) } diff --git a/crates/iota-indexer/src/lib.rs b/crates/iota-indexer/src/lib.rs index 0c29560a6bf..0a4b3215662 100644 --- a/crates/iota-indexer/src/lib.rs +++ b/crates/iota-indexer/src/lib.rs @@ -285,8 +285,7 @@ fn get_http_client(rpc_client_url: &str) -> Result { .map_err(|e| { warn!("Failed to get new Http client with error: {:?}", e); IndexerError::HttpClientInit(format!( - "Failed to initialize fullnode RPC client with error: {:?}", - e + "Failed to initialize fullnode RPC client with error: {e:?}" )) }) } diff --git a/crates/iota-indexer/src/models/checkpoints.rs b/crates/iota-indexer/src/models/checkpoints.rs index 4dbaf92371f..9b2b0938341 100644 --- a/crates/iota-indexer/src/models/checkpoints.rs +++ b/crates/iota-indexer/src/models/checkpoints.rs @@ -103,8 +103,7 @@ impl TryFrom for RpcCheckpoint { .map(|digest| { CheckpointDigest::try_from(digest.clone()).map_err(|e| { IndexerError::PersistentStorageDataCorruption(format!( - "Failed to decode previous checkpoint digest: {:?} with err: {:?}", - digest, e + "Failed to decode previous checkpoint digest: {digest:?} with err: {e:?}" )) }) }) @@ -122,8 +121,7 @@ impl TryFrom for RpcCheckpoint { Some(tx_digest) => TransactionDigest::try_from(tx_digest.as_slice()) .map_err(|e| { IndexerError::PersistentStorageDataCorruption(format!( - "Failed to decode transaction digest: {:?} with err: {:?}", - tx_digest, e + "Failed to decode transaction digest: {tx_digest:?} with err: {e:?}" )) }), }) @@ -152,8 +150,7 @@ impl TryFrom for RpcCheckpoint { .map(|data| { bcs::from_bytes(data).map_err(|e| { IndexerError::PersistentStorageDataCorruption(format!( - "Failed to decode end of epoch data: {:?} with err: {:?}", - data, e + "Failed to decode end of epoch data: {data:?} with err: {e:?}" )) }) }) diff --git a/crates/iota-indexer/src/models/events.rs b/crates/iota-indexer/src/models/events.rs index 2fb1cd4eb78..abc9b3d6dcc 100644 --- a/crates/iota-indexer/src/models/events.rs +++ b/crates/iota-indexer/src/models/events.rs @@ -158,8 +158,7 @@ impl StoredEvent { let sender = match sender { Some(ref s) => IotaAddress::from_bytes(s).map_err(|_e| { IndexerError::PersistentStorageDataCorruption(format!( - "Failed to parse event sender address: {:?}", - sender + "Failed to parse event sender address: {sender:?}" )) })?, None => { diff --git a/crates/iota-indexer/src/models/objects.rs b/crates/iota-indexer/src/models/objects.rs index e809df3ae7f..16dd823cec9 100644 --- a/crates/iota-indexer/src/models/objects.rs +++ b/crates/iota-indexer/src/models/objects.rs @@ -455,22 +455,19 @@ impl TryFrom for IotaCoin { let coin_type_canonical = o.coin_type .ok_or(IndexerError::PersistentStorageDataCorruption(format!( - "Object {} is supposed to be a coin but has an empty coin_type column", - coin_object_id, + "Object {coin_object_id} is supposed to be a coin but has an empty coin_type column", )))?; let coin_type = parse_to_struct_tag(coin_type_canonical.as_str()) .map_err(|_| { IndexerError::PersistentStorageDataCorruption(format!( - "The type of object {} cannot be parsed as a struct tag", - coin_object_id, + "The type of object {coin_object_id} cannot be parsed as a struct tag", )) })? .to_string(); let balance = o .coin_balance .ok_or(IndexerError::PersistentStorageDataCorruption(format!( - "Object {} is supposed to be a coin but has an empty coin_balance column", - coin_object_id, + "Object {coin_object_id} is supposed to be a coin but has an empty coin_balance column", )))?; Ok(IotaCoin { coin_type, diff --git a/crates/iota-indexer/src/models/transactions.rs b/crates/iota-indexer/src/models/transactions.rs index e999049330a..55a523b6b60 100644 --- a/crates/iota-indexer/src/models/transactions.rs +++ b/crates/iota-indexer/src/models/transactions.rs @@ -255,15 +255,13 @@ impl StoredTransaction { Some(event) => { let event: Event = bcs::from_bytes(&event).map_err(|e| { IndexerError::PersistentStorageDataCorruption(format!( - "Can't convert event bytes into Event. tx_digest={:?} Error: {e}", - tx_digest + "Can't convert event bytes into Event. tx_digest={tx_digest:?} Error: {e}" )) })?; Ok(event) } None => Err(IndexerError::PersistentStorageDataCorruption(format!( - "Event should not be null, tx_digest={:?}", - tx_digest + "Event should not be null, tx_digest={tx_digest:?}" ))), }) .collect::, IndexerError>>()? @@ -283,11 +281,11 @@ impl StoredTransaction { Some(object_change) => { let object_change: IndexedObjectChange = bcs::from_bytes(&object_change) .map_err(|e| IndexerError::PersistentStorageDataCorruption( - format!("Can't convert object_change bytes into IndexedObjectChange. tx_digest={:?} Error: {e}", tx_digest) + format!("Can't convert object_change bytes into IndexedObjectChange. tx_digest={tx_digest:?} Error: {e}") ))?; Ok(ObjectChange::from(object_change)) } - None => Err(IndexerError::PersistentStorageDataCorruption(format!("object_change should not be null, tx_digest={:?}", tx_digest))), + None => Err(IndexerError::PersistentStorageDataCorruption(format!("object_change should not be null, tx_digest={tx_digest:?}"))), } }).collect::, IndexerError>>()? }; @@ -303,11 +301,11 @@ impl StoredTransaction { Some(balance_change) => { let balance_change: BalanceChange = bcs::from_bytes(&balance_change) .map_err(|e| IndexerError::PersistentStorageDataCorruption( - format!("Can't convert balance_change bytes into BalanceChange. tx_digest={:?} Error: {e}", tx_digest) + format!("Can't convert balance_change bytes into BalanceChange. tx_digest={tx_digest:?} Error: {e}") ))?; Ok(balance_change) } - None => Err(IndexerError::PersistentStorageDataCorruption(format!("object_change should not be null, tx_digest={:?}", tx_digest))), + None => Err(IndexerError::PersistentStorageDataCorruption(format!("object_change should not be null, tx_digest={tx_digest:?}"))), } }).collect::, IndexerError>>()? }; diff --git a/crates/iota-indexer/src/store/package_resolver.rs b/crates/iota-indexer/src/store/package_resolver.rs index 1f9e304cac0..aed1f66d444 100644 --- a/crates/iota-indexer/src/store/package_resolver.rs +++ b/crates/iota-indexer/src/store/package_resolver.rs @@ -55,13 +55,12 @@ impl IndexerStorePackageResolver { })? else { return Err(IndexerError::PostgresRead(format!( - "Package not found in DB: {:?}", - id + "Package not found in DB: {id:?}" ))); }; let object = bcs::from_bytes::(&bcs)?; Package::read_from_object(&object).map_err(|e| { - IndexerError::PostgresRead(format!("Failed parsing object to package: {:?}", e)) + IndexerError::PostgresRead(format!("Failed parsing object to package: {e:?}")) }) } diff --git a/crates/iota-indexer/src/store/pg_indexer_analytical_store.rs b/crates/iota-indexer/src/store/pg_indexer_analytical_store.rs index 487b704d9ef..1d444031e4d 100644 --- a/crates/iota-indexer/src/store/pg_indexer_analytical_store.rs +++ b/crates/iota-indexer/src/store/pg_indexer_analytical_store.rs @@ -525,7 +525,7 @@ fn construct_peak_tps_query(epoch: i64, offset: i64) -> String { timestamp_ms FROM tx_count_metrics - WHERE epoch > ({} - {}) AND epoch <= {} + WHERE epoch > ({epoch} - {offset}) AND epoch <= {epoch} GROUP BY timestamp_ms ), @@ -543,8 +543,7 @@ fn construct_peak_tps_query(epoch: i64, offset: i64) -> String { tps_data WHERE time_diff IS NOT NULL; - ", - epoch, offset, epoch + " ) } @@ -558,7 +557,7 @@ fn construct_address_persisting_query(start_tx_seq: i64, end_tx_seq: i64) -> Str FROM tx_senders s JOIN transactions t ON s.tx_sequence_number = t.tx_sequence_number - WHERE s.tx_sequence_number >= {} AND s.tx_sequence_number < {} + WHERE s.tx_sequence_number >= {start_tx_seq} AND s.tx_sequence_number < {end_tx_seq} ), recipients AS ( SELECT @@ -568,7 +567,7 @@ fn construct_address_persisting_query(start_tx_seq: i64, end_tx_seq: i64) -> Str FROM tx_recipients r JOIN transactions t ON r.tx_sequence_number = t.tx_sequence_number - WHERE r.tx_sequence_number >= {} AND r.tx_sequence_number < {} + WHERE r.tx_sequence_number >= {start_tx_seq} AND r.tx_sequence_number < {end_tx_seq} ), union_address AS ( SELECT @@ -600,8 +599,7 @@ fn construct_address_persisting_query(start_tx_seq: i64, end_tx_seq: i64) -> Str SET last_appearance_tx = GREATEST(EXCLUDED.last_appearance_tx, addresses.last_appearance_tx), last_appearance_time = GREATEST(EXCLUDED.last_appearance_time, addresses.last_appearance_time); - ", - start_tx_seq, end_tx_seq, start_tx_seq, end_tx_seq + " ) } @@ -615,7 +613,7 @@ fn construct_active_address_persisting_query(start_tx_seq: i64, end_tx_seq: i64) FROM tx_senders s JOIN transactions t ON s.tx_sequence_number = t.tx_sequence_number - WHERE s.tx_sequence_number >= {} AND s.tx_sequence_number < {} + WHERE s.tx_sequence_number >= {start_tx_seq} AND s.tx_sequence_number < {end_tx_seq} ) INSERT INTO active_addresses SELECT @@ -630,8 +628,7 @@ fn construct_active_address_persisting_query(start_tx_seq: i64, end_tx_seq: i64) SET last_appearance_tx = GREATEST(EXCLUDED.last_appearance_tx, active_addresses.last_appearance_tx), last_appearance_time = GREATEST(EXCLUDED.last_appearance_time, active_addresses.last_appearance_time); - ", - start_tx_seq, end_tx_seq + " ) } @@ -650,9 +647,8 @@ fn construct_move_call_persist_query(start_tx_seq: i64, end_tx_seq: i64) -> Stri ON m.tx_sequence_number = t.tx_sequence_number INNER JOIN checkpoints c ON t.checkpoint_sequence_number = c.sequence_number - WHERE m.tx_sequence_number >= {} AND m.tx_sequence_number < {} + WHERE m.tx_sequence_number >= {start_tx_seq} AND m.tx_sequence_number < {end_tx_seq} ON CONFLICT (transaction_sequence_number, move_package, move_module, move_function) DO NOTHING; - ", - start_tx_seq, end_tx_seq + " ) } diff --git a/crates/iota-indexer/src/store/pg_indexer_store.rs b/crates/iota-indexer/src/store/pg_indexer_store.rs index fde412f1806..f0da00f676d 100644 --- a/crates/iota-indexer/src/store/pg_indexer_store.rs +++ b/crates/iota-indexer/src/store/pg_indexer_store.rs @@ -896,8 +896,7 @@ impl PgIndexerStore { .collect::, _>>() .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist all event indices in a chunk: {:?}", - e + "Failed to persist all event indices in a chunk: {e:?}" )) })?; let elapsed = guard.stop_and_record(); @@ -1167,8 +1166,7 @@ impl PgIndexerStore { .collect::, _>>() .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist all tx indices in a chunk: {:?}", - e + "Failed to persist all tx indices in a chunk: {e:?}" )) })?; let elapsed = guard.stop_and_record(); @@ -1630,8 +1628,7 @@ impl IndexerStore for PgIndexerStore { .collect::, _>>() .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist all object mutation chunks: {:?}", - e + "Failed to persist all object mutation chunks: {e:?}" )) })?; let deletion_futures = object_deletion_chunks @@ -1650,8 +1647,7 @@ impl IndexerStore for PgIndexerStore { .collect::, _>>() .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist all object deletion chunks: {:?}", - e + "Failed to persist all object deletion chunks: {e:?}" )) })?; @@ -1703,8 +1699,7 @@ impl IndexerStore for PgIndexerStore { .collect::, _>>() .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist all objects snapshot chunks: {:?}", - e + "Failed to persist all objects snapshot chunks: {e:?}" )) })?; let elapsed = guard.stop_and_record(); @@ -1752,8 +1747,7 @@ impl IndexerStore for PgIndexerStore { .collect::, _>>() .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist all objects history chunks: {:?}", - e + "Failed to persist all objects history chunks: {e:?}" )) })?; let elapsed = guard.stop_and_record(); @@ -1786,8 +1780,7 @@ impl IndexerStore for PgIndexerStore { .collect::, _>>() .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist all object version chunks: {:?}", - e + "Failed to persist all object version chunks: {e:?}" )) })?; info!("Persisted {} objects history", object_versions_count); @@ -1827,8 +1820,7 @@ impl IndexerStore for PgIndexerStore { .collect::, _>>() .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist all transactions chunks: {:?}", - e + "Failed to persist all transactions chunks: {e:?}" )) })?; let elapsed = guard.stop_and_record(); @@ -1858,8 +1850,7 @@ impl IndexerStore for PgIndexerStore { .await .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist optimistic transaction: {:?}", - e + "Failed to persist optimistic transaction: {e:?}" )) })??; @@ -1923,7 +1914,7 @@ impl IndexerStore for PgIndexerStore { .into_iter() .collect::, _>>() .map_err(|e| { - IndexerError::PostgresWrite(format!("Failed to persist all events chunks: {:?}", e)) + IndexerError::PostgresWrite(format!("Failed to persist all events chunks: {e:?}")) })?; let elapsed = guard.stop_and_record(); info!(elapsed, "Persisted {} events", len); @@ -1950,8 +1941,7 @@ impl IndexerStore for PgIndexerStore { })? .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist all optimistic events chunks: {:?}", - e + "Failed to persist all optimistic events chunks: {e:?}" )) }) } @@ -2003,8 +1993,7 @@ impl IndexerStore for PgIndexerStore { .collect::, _>>() .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist all event_indices chunks: {:?}", - e + "Failed to persist all event_indices chunks: {e:?}" )) })?; let elapsed = guard.stop_and_record(); @@ -2126,8 +2115,7 @@ impl IndexerStore for PgIndexerStore { .collect::, _>>() .map_err(|e| { IndexerError::PostgresWrite(format!( - "Failed to persist all tx_indices chunks: {:?}", - e + "Failed to persist all tx_indices chunks: {e:?}" )) })?; let elapsed = guard.stop_and_record(); @@ -2226,8 +2214,7 @@ impl IndexerStore for PgIndexerStore { let (mut min_cp, max_cp) = match self.get_checkpoint_range_for_epoch(epoch)? { (min_cp, Some(max_cp)) => Ok((min_cp, max_cp)), _ => Err(IndexerError::PostgresRead(format!( - "Failed to get checkpoint range for epoch {}", - epoch + "Failed to get checkpoint range for epoch {epoch}" ))), }?; diff --git a/crates/iota-indexer/src/test_utils.rs b/crates/iota-indexer/src/test_utils.rs index b1c04a5600c..43a13826f78 100644 --- a/crates/iota-indexer/src/test_utils.rs +++ b/crates/iota-indexer/src/test_utils.rs @@ -219,12 +219,12 @@ pub fn create_pg_store(db_url: Secret, reset_database: bool) -> PgIndexe // Delete the old db if it exists default_conn - .batch_execute(&format!("DROP DATABASE IF EXISTS {}", db_name)) + .batch_execute(&format!("DROP DATABASE IF EXISTS {db_name}")) .unwrap(); // Create the new db default_conn - .batch_execute(&format!("CREATE DATABASE {}", db_name)) + .batch_execute(&format!("CREATE DATABASE {db_name}")) .unwrap(); parsed_url = replace_db_name(parsed_url.expose_secret(), db_name) .0 @@ -259,7 +259,7 @@ pub async fn force_delete_database(db_url: String) { blocking_pool .get() .unwrap() - .batch_execute(&format!("DROP DATABASE IF EXISTS {} WITH (FORCE)", db_name)) + .batch_execute(&format!("DROP DATABASE IF EXISTS {db_name} WITH (FORCE)")) .unwrap(); } diff --git a/crates/iota-indexer/tests/common/mod.rs b/crates/iota-indexer/tests/common/mod.rs index 5bb7d609c97..f754eb5ecf2 100644 --- a/crates/iota-indexer/tests/common/mod.rs +++ b/crates/iota-indexer/tests/common/mod.rs @@ -91,7 +91,7 @@ impl SimulacrumTestSetup { let sim = env_initializer(data_ingestion_path.clone()); let sim = Arc::new(sim); - let db_name = format!("simulacrum_env_db_{}", unique_env_name); + let db_name = format!("simulacrum_env_db_{unique_env_name}"); let (_, store, _, client) = runtime.block_on(start_simulacrum_rest_api_with_read_write_indexer( sim.clone(), @@ -317,7 +317,7 @@ pub async fn start_simulacrum_rest_api_with_write_indexer( get_indexer_db_url(database_name), true, db_init_hook, - format!("http://{}", server_url), + format!("http://{server_url}"), IndexerTypeConfig::writer_mode( Some(SnapshotLagConfig { snapshot_min_lag: 5, @@ -353,7 +353,7 @@ pub async fn start_simulacrum_rest_api_with_read_write_indexer( // start indexer in read mode let indexer_port = start_indexer_reader( - format!("http://{}", simulacrum_server_url), + format!("http://{simulacrum_server_url}"), data_ingestion_path, database_name, ); diff --git a/crates/iota-indexer/tests/rpc-tests/extended_api.rs b/crates/iota-indexer/tests/rpc-tests/extended_api.rs index 8198a7ef044..73e5b2bc723 100644 --- a/crates/iota-indexer/tests/rpc-tests/extended_api.rs +++ b/crates/iota-indexer/tests/rpc-tests/extended_api.rs @@ -302,7 +302,7 @@ fn get_network_metrics() { let network_metrics = client.get_network_metrics().await.unwrap(); - println!("{:#?}", network_metrics); + println!("{network_metrics:#?}"); }); } @@ -351,7 +351,7 @@ fn get_latest_address_metrics() { let address_metrics = client.get_latest_address_metrics().await.unwrap(); - println!("{:#?}", address_metrics); + println!("{address_metrics:#?}"); }); } @@ -370,7 +370,7 @@ fn get_checkpoint_address_metrics() { let address_metrics = client.get_checkpoint_address_metrics(0).await.unwrap(); - println!("{:#?}", address_metrics); + println!("{address_metrics:#?}"); }); } @@ -389,7 +389,7 @@ fn get_all_epoch_address_metrics() { let address_metrics = client.get_all_epoch_address_metrics(None).await.unwrap(); - println!("{:#?}", address_metrics); + println!("{address_metrics:#?}"); }); } diff --git a/crates/iota-indexer/tests/rpc-tests/read_api.rs b/crates/iota-indexer/tests/rpc-tests/read_api.rs index 0fcf98c5853..f54d84028df 100644 --- a/crates/iota-indexer/tests/rpc-tests/read_api.rs +++ b/crates/iota-indexer/tests/rpc-tests/read_api.rs @@ -1299,7 +1299,7 @@ fn try_get_past_object_version_found() { gas_ref.1, data.version ); } - _ => panic!("Expected VersionFound response, got: {:?}", result), + _ => panic!("Expected VersionFound response, got: {result:?}"), } }); } @@ -1461,7 +1461,7 @@ fn try_get_past_object_object_deleted() { nft_object_ref.1, data.version ); } - _ => panic!("Expected VersionFound response, got: {:?}", result), + _ => panic!("Expected VersionFound response, got: {result:?}"), } }); } @@ -1578,8 +1578,7 @@ fn try_multi_get_past_objects() { ); } _ => panic!( - "Expected VersionFound response, got: {:?}", - past_object_response_1 + "Expected VersionFound response, got: {past_object_response_1:?}" ), } @@ -1592,8 +1591,7 @@ fn try_multi_get_past_objects() { ); } _ => panic!( - "Expected VersionFound response, got: {:?}", - past_object_response_2 + "Expected VersionFound response, got: {past_object_response_2:?}" ), } @@ -1679,7 +1677,7 @@ fn try_get_object_before_version() { gas_ref.1, data.version ); } - _ => panic!("Expected VersionFound response, got: {:?}", result), + _ => panic!("Expected VersionFound response, got: {result:?}"), } }); } diff --git a/crates/iota-json-rpc-tests/tests/coin_api.rs b/crates/iota-json-rpc-tests/tests/coin_api.rs index 5f2be50f360..be60bcc8ea3 100644 --- a/crates/iota-json-rpc-tests/tests/coin_api.rs +++ b/crates/iota-json-rpc-tests/tests/coin_api.rs @@ -188,7 +188,7 @@ async fn get_coins() -> Result<(), anyhow::Error> { Some(3), ) .await?; - assert_eq!(2, result.data.len(), "{:?}", result); + assert_eq!(2, result.data.len(), "{result:?}"); assert!(!result.has_next_page); let result: CoinPage = http_client @@ -199,7 +199,7 @@ async fn get_coins() -> Result<(), anyhow::Error> { None, ) .await?; - assert_eq!(0, result.data.len(), "{:?}", result); + assert_eq!(0, result.data.len(), "{result:?}"); assert!(!result.has_next_page); Ok(()) diff --git a/crates/iota-json-rpc-types/src/iota_move.rs b/crates/iota-json-rpc-types/src/iota_move.rs index feb3ce0264d..48f88678438 100644 --- a/crates/iota-json-rpc-types/src/iota_move.rs +++ b/crates/iota-json-rpc-types/src/iota_move.rs @@ -461,7 +461,7 @@ impl Display for IotaMoveVariant { writeln!(writer, " {}: {type_}", "type".bold().bright_black())?; writeln!(writer, " {}: {variant}", "variant".bold().bright_black())?; for (name, value) in fields { - let value = format!("{}", value); + let value = format!("{value}"); let value = if value.starts_with('\n') { indent(&value, 2) } else { diff --git a/crates/iota-json-rpc/src/coin_api.rs b/crates/iota-json-rpc/src/coin_api.rs index 577071efdf7..736621ac6f0 100644 --- a/crates/iota-json-rpc/src/coin_api.rs +++ b/crates/iota-json-rpc/src/coin_api.rs @@ -345,8 +345,7 @@ async fn find_package_object_id( } } Err(IotaRpcInputError::GenericNotFound(format!( - "Cannot find object [{}] from [{}] package event.", - object_struct_tag, package_id, + "Cannot find object [{object_struct_tag}] from [{package_id}] package event.", )) .into()) }) @@ -578,7 +577,7 @@ mod tests { } fn get_test_coin_type(package_id: ObjectID) -> String { - format!("{}::test_coin::TEST_COIN", package_id) + format!("{package_id}::test_coin::TEST_COIN") } fn get_test_coin_type_tag(coin_type: String) -> TypeTag { @@ -1209,7 +1208,7 @@ mod tests { if let Some(pos) = result.iter().position(|i| *i == item) { result.remove(pos); } else { - panic!("{:?} not found in result", item); + panic!("{item:?} not found in result"); } } assert!(result.is_empty()); diff --git a/crates/iota-json-rpc/src/error.rs b/crates/iota-json-rpc/src/error.rs index eff852b408d..799b7166c73 100644 --- a/crates/iota-json-rpc/src/error.rs +++ b/crates/iota-json-rpc/src/error.rs @@ -196,8 +196,7 @@ impl From for RpcError { retried_tx_success, } => { let error_message = format!( - "Failed to sign transaction by a quorum of validators because of locked objects. Retried a conflicting transaction {:?}, success: {:?}", - retried_tx, retried_tx_success + "Failed to sign transaction by a quorum of validators because of locked objects. Retried a conflicting transaction {retried_tx:?}, success: {retried_tx_success:?}" ); let new_map = conflicting_txes @@ -254,8 +253,7 @@ impl From for RpcError { let error_list = new_errors.join(", "); let error_msg = format!( - "Transaction execution failed due to issues with transaction inputs, please review the errors and try again: {}.", - error_list + "Transaction execution failed due to issues with transaction inputs, please review the errors and try again: {error_list}." ); let error_object = ErrorObject::owned::<()>( diff --git a/crates/iota-json-rpc/src/move_utils.rs b/crates/iota-json-rpc/src/move_utils.rs index dc6b83ea36a..33fa434d847 100644 --- a/crates/iota-json-rpc/src/move_utils.rs +++ b/crates/iota-json-rpc/src/move_utils.rs @@ -79,8 +79,7 @@ impl MoveUtilsInternalTrait for MoveUtilsInternal { Ok(match normalized.get(&module_name) { Some(module) => Ok(module.clone()), None => Err(IotaRpcInputError::GenericNotFound(format!( - "No module found with module name {}", - module_name + "No module found with module name {module_name}" ))), }?) } @@ -110,14 +109,12 @@ impl MoveUtilsInternalTrait for MoveUtilsInternal { }) } _ => Err(IotaRpcInputError::GenericInvalid(format!( - "Object is not a package with ID {}", - package + "Object is not a package with ID {package}" )))?, } } _ => Err(IotaRpcInputError::GenericNotFound(format!( - "Package object does not exist with ID {}", - package + "Package object does not exist with ID {package}" )))?, } } @@ -197,8 +194,7 @@ impl MoveUtilsServer for MoveUtils { match structs.get(&identifier) { Some(struct_) => Ok(struct_.clone().into()), None => Err(IotaRpcInputError::GenericNotFound(format!( - "No struct was found with struct name {}", - struct_name + "No struct was found with struct name {struct_name}" )))?, } } diff --git a/crates/iota-json-rpc/src/read_api.rs b/crates/iota-json-rpc/src/read_api.rs index 2065347aa6a..d9983aaa95f 100644 --- a/crates/iota-json-rpc/src/read_api.rs +++ b/crates/iota-json-rpc/src/read_api.rs @@ -563,13 +563,13 @@ impl ReadApiServer for ReadApi { Ok(response) => Ok(response), Err(error) => { error!("Failed to fetch object with error: {error:?}"); - Err(format!("Error: {}", error)) + Err(format!("Error: {error}")) } }) .collect(); let objects = objects_result.map_err(|err| { - Error::Unexpected(format!("Failed to fetch objects with error: {}", err)) + Error::Unexpected(format!("Failed to fetch objects with error: {err}")) })?; self.metrics @@ -1244,7 +1244,7 @@ fn parse_template(template: &str, move_struct: &IotaMoveStruct) -> Result { in_braces = false; let value = get_value_from_move_struct(move_struct, &var_name)?; - output = output.replace(&format!("{{{}}}", var_name), &value.to_string()); + output = output.replace(&format!("{{{var_name}}}"), &value.to_string()); } _ if !escaped => { if in_braces { diff --git a/crates/iota-json/src/tests.rs b/crates/iota-json/src/tests.rs index 8424fc028f1..583f80fcefa 100644 --- a/crates/iota-json/src/tests.rs +++ b/crates/iota-json/src/tests.rs @@ -333,7 +333,7 @@ fn test_basic_args_linter_pure_args_good() { ), // U128 value encoded as hex str ( - Value::from(format!("0x{:02x}", u128_val)), + Value::from(format!("0x{u128_val:02x}")), MoveTypeLayout::U128, bcs::to_bytes(&u128_val).unwrap(), ), @@ -696,7 +696,7 @@ fn test_convert_struct() { let value = json!({"id":"0xf1416fe18c7baa1673187375777a7606708481311cb3548509ec91a5871c6b9a", "balance": "1000000"}); let iota_json = IotaJsonValue::new(value).unwrap(); - println!("JS: {:#?}", iota_json); + println!("JS: {iota_json:#?}"); let bcs = iota_json.to_bcs_bytes(&layout).unwrap(); diff --git a/crates/iota-keys/src/key_derive.rs b/crates/iota-keys/src/key_derive.rs index e17096cc0db..2aac50b46d6 100644 --- a/crates/iota-keys/src/key_derive.rs +++ b/crates/iota-keys/src/key_derive.rs @@ -65,7 +65,7 @@ pub fn derive_key_pair_from_path( | SignatureScheme::MultiSig | SignatureScheme::ZkLoginAuthenticator | SignatureScheme::PasskeyAuthenticator => Err(IotaError::UnsupportedFeature { - error: format!("key derivation not supported {:?}", key_scheme), + error: format!("key derivation not supported {key_scheme:?}"), }), } } @@ -166,7 +166,7 @@ pub fn validate_path( | SignatureScheme::MultiSig | SignatureScheme::ZkLoginAuthenticator | SignatureScheme::PasskeyAuthenticator => Err(IotaError::UnsupportedFeature { - error: format!("key derivation not supported {:?}", key_scheme), + error: format!("key derivation not supported {key_scheme:?}"), }), } } diff --git a/crates/iota-keys/src/keystore.rs b/crates/iota-keys/src/keystore.rs index 05f40c2d376..eda1ae3fab7 100644 --- a/crates/iota-keys/src/keystore.rs +++ b/crates/iota-keys/src/keystore.rs @@ -157,11 +157,11 @@ impl Display for Keystore { Keystore::File(file) => { writeln!(writer, "Keystore Type: File")?; write!(writer, "Keystore Path : {:?}", file.path)?; - write!(f, "{}", writer) + write!(f, "{writer}") } Keystore::InMem(_) => { writeln!(writer, "Keystore Type: InMem")?; - write!(f, "{}", writer) + write!(f, "{writer}") } } } diff --git a/crates/iota-light-client/src/utils.rs b/crates/iota-light-client/src/utils.rs index f85dc738d2e..6f8821591d1 100644 --- a/crates/iota-light-client/src/utils.rs +++ b/crates/iota-light-client/src/utils.rs @@ -172,7 +172,7 @@ pub fn read_checkpoint_general( checkpoint_path.push(path); } // TODO why yaml? rename to .sum - checkpoint_path.push(format!("{}.yaml", checkpoint_number)); + checkpoint_path.push(format!("{checkpoint_number}.yaml")); let mut reader = fs::File::open(checkpoint_path.clone())?; let metadata = fs::metadata(&checkpoint_path)?; let mut buffer = vec![0; metadata.len() as usize]; @@ -248,7 +248,7 @@ pub async fn download_checkpoint_summary_from_object_store( let url = Url::parse(&config.object_store_url)?; let (dyn_store, _store_path) = parse_url(&url).unwrap(); - let path = Path::from(format!("{}.chk", checkpoint_number)); + let path = Path::from(format!("{checkpoint_number}.chk")); let response = dyn_store.get(&path).await?; let bytes = response.bytes().await?; let (_, blob) = bcs::from_bytes::<(u8, CheckpointData)>(&bytes)?; @@ -305,8 +305,7 @@ pub async fn sync_checkpoint_list_to_latest(config: &Config) -> anyhow::Result<( last_epoch = target_epoch; println!( - "Last Epoch: {} Last Checkpoint: {}", - target_epoch, target_last_checkpoint_number + "Last Epoch: {target_epoch} Last Checkpoint: {target_last_checkpoint_number}" ); } @@ -337,7 +336,7 @@ pub async fn check_and_sync_checkpoints(config: &Config) -> anyhow::Result<()> { // check if there is a file with this name ckp_id.yaml in the // checkpoint_summary_dir let mut checkpoint_path = config.checkpoint_summary_dir.clone(); - checkpoint_path.push(format!("{}.yaml", ckp_id)); + checkpoint_path.push(format!("{ckp_id}.yaml")); // If file exists read the file otherwise download it from the server let summary = if checkpoint_path.exists() { @@ -411,7 +410,7 @@ pub async fn get_full_checkpoint_from_object_store( let url = Url::parse(&config.object_store_url) .map_err(|_| anyhow!("Cannot parse object store URL"))?; let (dyn_store, _store_path) = parse_url(&url).unwrap(); - let path = Path::from(format!("{}.chk", checkpoint_number)); + let path = Path::from(format!("{checkpoint_number}.chk")); info!("Request full checkpoint: {}", path); let response = dyn_store .get(&path) diff --git a/crates/iota-light-client/tests/check_proof.rs b/crates/iota-light-client/tests/check_proof.rs index a87cacede0d..1614a4a0a4e 100644 --- a/crates/iota-light-client/tests/check_proof.rs +++ b/crates/iota-light-client/tests/check_proof.rs @@ -23,7 +23,7 @@ use iota_types::{ }; async fn read_full_checkpoint(checkpoint_path: &PathBuf) -> anyhow::Result { - println!("Reading checkpoint from {:?}", checkpoint_path); + println!("Reading checkpoint from {checkpoint_path:?}"); let mut reader = fs::File::open(checkpoint_path.clone())?; let mut buffer = Vec::new(); reader.read_to_end(&mut buffer)?; @@ -60,7 +60,7 @@ async fn read_test_data() -> (Committee, CheckpointData) { async fn read_data(committee_seq: u64, seq: u64) -> (Committee, CheckpointData) { let mut checkpoint_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - checkpoint_path.push(format!("example_config/{}.chk", committee_seq)); + checkpoint_path.push(format!("example_config/{committee_seq}.chk")); let committee_checkpoint = read_full_checkpoint(&checkpoint_path).await.unwrap(); @@ -86,7 +86,7 @@ async fn read_data(committee_seq: u64, seq: u64) -> (Committee, CheckpointData) ); let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - d.push(format!("example_config/{}.chk", seq)); + d.push(format!("example_config/{seq}.chk")); let full_checkpoint = read_full_checkpoint(&d).await.unwrap(); diff --git a/crates/iota-macros/src/lib.rs b/crates/iota-macros/src/lib.rs index 366067ff0a4..e2b76a72d69 100644 --- a/crates/iota-macros/src/lib.rs +++ b/crates/iota-macros/src/lib.rs @@ -63,8 +63,7 @@ fn get_async_fp_result(result: Box) -> BoxFu match result.downcast::>() { Ok(fut) => *fut, Err(err) => panic!( - "async failpoint must return BoxFuture<'static, ()> {:?}", - err + "async failpoint must return BoxFuture<'static, ()> {err:?}" ), } } @@ -131,8 +130,7 @@ fn clear_fail_point_impl(identifier: &'static str) { with_fp_map(move |map| { assert!( map.remove(identifier).is_some(), - "fail point {:?} does not exist", - identifier + "fail point {identifier:?} does not exist" ); }) } diff --git a/crates/iota-mainnet-unlocks/src/bin/generate_aggregated_data.rs b/crates/iota-mainnet-unlocks/src/bin/generate_aggregated_data.rs index 3417e321f1b..954fb9bc1bf 100644 --- a/crates/iota-mainnet-unlocks/src/bin/generate_aggregated_data.rs +++ b/crates/iota-mainnet-unlocks/src/bin/generate_aggregated_data.rs @@ -56,7 +56,7 @@ fn aggregate_unlocks(repo_path: &Path) -> Result> { for folder in FOLDERS { let csv_path = repo_path.join(folder).join("summary.csv"); - println!("Processing file: {:?}", csv_path); + println!("Processing file: {csv_path:?}"); let mut rdr = Reader::from_path(&csv_path) .with_context(|| format!("failed to open CSV file: {csv_path:?}"))?; diff --git a/crates/iota-metrics/src/histogram.rs b/crates/iota-metrics/src/histogram.rs index 20e95abd847..06cf0e323c9 100644 --- a/crates/iota-metrics/src/histogram.rs +++ b/crates/iota-metrics/src/histogram.rs @@ -141,8 +141,8 @@ impl HistogramVec { registry: &Registry, percentiles: Vec, ) -> Self { - let sum_name = format!("{}_sum", name); - let count_name = format!("{}_count", name); + let sum_name = format!("{name}_sum"); + let count_name = format!("{name}_count"); let sum = register_int_counter_vec_with_registry!(sum_name, desc, labels, registry).unwrap(); let count = @@ -198,24 +198,24 @@ impl HistogramVec { // HistogramVec and remove them from the registry. Counters can be safely // unregistered even if they are still in use. pub fn unregister(name: &str, desc: &str, labels: &[&str], registry: &Registry) { - let sum_name = format!("{}_sum", name); - let count_name = format!("{}_count", name); + let sum_name = format!("{name}_sum"); + let count_name = format!("{name}_count"); let sum = IntCounterVec::new(opts!(sum_name, desc), labels).unwrap(); registry .unregister(Box::new(sum)) - .unwrap_or_else(|_| panic!("{}_sum counter is in prometheus registry", name)); + .unwrap_or_else(|_| panic!("{name}_sum counter is in prometheus registry")); let count = IntCounterVec::new(opts!(count_name, desc), labels).unwrap(); registry .unregister(Box::new(count)) - .unwrap_or_else(|_| panic!("{}_count counter is in prometheus registry", name)); + .unwrap_or_else(|_| panic!("{name}_count counter is in prometheus registry")); let labels: Vec<_> = labels.iter().cloned().chain(["pct"]).collect(); let gauge = IntGaugeVec::new(opts!(name, desc), &labels).unwrap(); registry .unregister(Box::new(gauge)) - .unwrap_or_else(|_| panic!("{} gauge is in prometheus registry", name)); + .unwrap_or_else(|_| panic!("{name} gauge is in prometheus registry")); } } diff --git a/crates/iota-move-build/src/lib.rs b/crates/iota-move-build/src/lib.rs index de9e3544e8e..da8e420fc44 100644 --- a/crates/iota-move-build/src/lib.rs +++ b/crates/iota-move-build/src/lib.rs @@ -191,7 +191,7 @@ impl BuildConfig { .resolution_graph_for_package(path, chain_id, &mut std::io::sink()) } .map_err(|err| IotaError::ModuleBuildFailure { - error: format!("{:?}", err), + error: format!("{err:?}"), }) } } @@ -257,8 +257,7 @@ pub fn build_from_resolution_graph( pkg.get_bytecodes_bytes() .map_err(|error| IotaError::ModuleDeserializationFailure { error: format!( - "Deserializing bytecode dependency for package {}: {:?}", - name, error + "Deserializing bytecode dependency for package {name}: {error:?}" ), })?; for module in modules { @@ -266,8 +265,7 @@ pub fn build_from_resolution_graph( CompiledModule::deserialize_with_defaults(module.as_ref()).map_err(|error| { IotaError::ModuleDeserializationFailure { error: format!( - "Deserializing bytecode dependency for package {}: {:?}", - name, error + "Deserializing bytecode dependency for package {name}: {error:?}" ), } })?; @@ -285,7 +283,7 @@ pub fn build_from_resolution_graph( let (package, fn_info) = match result { Err(error) => { return Err(IotaError::ModuleBuildFailure { - error: format!("{:?}", error), + error: format!("{error:?}"), }); } Ok((package, fn_info)) => (package, fn_info), diff --git a/crates/iota-move/src/disassemble.rs b/crates/iota-move/src/disassemble.rs index 52206583414..61f124805b9 100644 --- a/crates/iota-move/src/disassemble.rs +++ b/crates/iota-move/src/disassemble.rs @@ -85,7 +85,7 @@ impl Disassemble { if self.bytecode_map { println!("{}", serialize_to_json_string(&bcode_map)?); } - println!("{}", disassemble_string); + println!("{disassemble_string}"); } Ok(()) diff --git a/crates/iota-move/src/new.rs b/crates/iota-move/src/new.rs index e4e06f26347..5bb3f4d2a89 100644 --- a/crates/iota-move/src/new.rs +++ b/crates/iota-move/src/new.rs @@ -43,8 +43,7 @@ module {name}::{name}; // For Move coding conventions, see // https://docs.iota.org/developer/iota-101/move-overview/conventions -"#, - name = name +"# )?; create_dir_all(p.join(SourcePackageLayout::Tests.path()))?; @@ -71,8 +70,7 @@ fun test_{name}() {{ fun test_{name}_fail() {{ abort ENotImplemented }} -*/"#, - name = name +*/"# )?; Ok(()) diff --git a/crates/iota-network/src/discovery/tests.rs b/crates/iota-network/src/discovery/tests.rs index 0078c771710..7bfca5b9ce9 100644 --- a/crates/iota-network/src/discovery/tests.rs +++ b/crates/iota-network/src/discovery/tests.rs @@ -640,14 +640,12 @@ fn assert_peers( .collect::>(); assert_eq!( actual, expected_network_known_peers, - "{} network known peers mismatch. Expected: {:#?}, actual: {:#?}", - self_name, expected_network_known_peers, actual, + "{self_name} network known peers mismatch. Expected: {expected_network_known_peers:#?}, actual: {actual:#?}", ); let actual = network.peers().iter().copied().collect::>(); assert_eq!( actual, expected_network_connected_peers, - "{} network connected peers mismatch. Expected: {:#?}, actual: {:#?}", - self_name, expected_network_connected_peers, actual, + "{self_name} network connected peers mismatch. Expected: {expected_network_connected_peers:#?}, actual: {actual:#?}", ); let actual = state .read() @@ -658,8 +656,7 @@ fn assert_peers( .collect::>(); assert_eq!( actual, expected_discovery_known_peers, - "{} discovery known peers mismatch. Expected: {:#?}, actual: {:#?}", - self_name, expected_discovery_known_peers, actual, + "{self_name} discovery known peers mismatch. Expected: {expected_discovery_known_peers:#?}, actual: {actual:#?}", ); let actual = state @@ -671,8 +668,7 @@ fn assert_peers( .collect::>(); assert_eq!( actual, expected_discovery_connected_peers, - "{} discovery connected peers mismatch. Expected: {:#?}, actual: {:#?}", - self_name, expected_discovery_connected_peers, actual, + "{self_name} discovery connected peers mismatch. Expected: {expected_discovery_connected_peers:#?}, actual: {actual:#?}", ); } @@ -686,7 +682,7 @@ fn unwrap_new_peer_event(event: PeerEvent) -> PeerId { fn local_allowlisted_peer(peer_id: PeerId, port: Option) -> AllowlistedPeer { AllowlistedPeer { peer_id, - address: port.map(|port| format!("/dns/localhost/udp/{}", port).parse().unwrap()), + address: port.map(|port| format!("/dns/localhost/udp/{port}").parse().unwrap()), } } @@ -728,7 +724,7 @@ fn create_test_channel() -> ( #[tokio::test] async fn test_handle_trusted_peer_change_event() -> Result<()> { fn mock_multiaddr(id: u16) -> Multiaddr { - format!("/dns/mockhost/udp/{}", id).parse().unwrap() + format!("/dns/mockhost/udp/{id}").parse().unwrap() } // Create mock peers, good enough for the test diff --git a/crates/iota-node/src/admin.rs b/crates/iota-node/src/admin.rs index e9b1771e8c2..870360baba9 100644 --- a/crates/iota-node/src/admin.rs +++ b/crates/iota-node/src/admin.rs @@ -171,15 +171,15 @@ async fn enable_tracing( if let Some(sample_rate) = sample_rate { state.tracing_handle.update_sampling_rate(sample_rate); - response.push(format!("sample rate set to {:?}", sample_rate)); + response.push(format!("sample rate set to {sample_rate:?}")); } if let Some(trace_file) = trace_file { if let Err(err) = state.tracing_handle.update_trace_file(&trace_file) { - response.push(format!("can't update trace file: {:?}", err)); + response.push(format!("can't update trace file: {err:?}")); return (StatusCode::BAD_REQUEST, response.join("\n")); } else { - response.push(format!("trace file set to {:?}", trace_file)); + response.push(format!("trace file set to {trace_file:?}")); } } @@ -200,8 +200,8 @@ async fn enable_tracing( match state.tracing_handle.update_trace_filter(&filter, duration) { Ok(()) => { - response.push(format!("filter set to {:?}", filter)); - response.push(format!("filter will be reset after {:?}", duration)); + response.push(format!("filter set to {filter:?}")); + response.push(format!("filter will be reset after {duration:?}")); (StatusCode::OK, response.join("\n")) } Err(TelemetryError::TracingDisabled) => { @@ -209,7 +209,7 @@ async fn enable_tracing( (StatusCode::NOT_IMPLEMENTED, response.join("\n")) } Err(err) => { - response.push(format!("can't update filter: {:?}", err)); + response.push(format!("can't update filter: {err:?}")); (StatusCode::BAD_REQUEST, response.join("\n")) } } @@ -255,7 +255,7 @@ async fn capabilities(State(state): State>) -> (StatusCode, String let mut output = String::new(); let capabilities = epoch_store.get_capabilities_v1(); for capability in capabilities.unwrap_or_default() { - output.push_str(&format!("{:?}\n", capability)); + output.push_str(&format!("{capability:?}\n")); } (StatusCode::OK, output) @@ -265,7 +265,7 @@ async fn node_config(State(state): State>) -> (StatusCode, String) let node_config = &state.node.config; // Note private keys will be masked - (StatusCode::OK, format!("{:#?}\n", node_config)) + (StatusCode::OK, format!("{node_config:#?}\n")) } #[derive(Deserialize)] @@ -309,7 +309,7 @@ async fn set_override_protocol_upgrade_buffer_stake( { Ok(()) => ( StatusCode::OK, - format!("protocol upgrade buffer stake set to '{}'\n", buffer_bps), + format!("protocol upgrade buffer stake set to '{buffer_bps}'\n"), ), Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()), } diff --git a/crates/iota-node/src/lib.rs b/crates/iota-node/src/lib.rs index 12852ce8a64..ab633f9d03d 100644 --- a/crates/iota-node/src/lib.rs +++ b/crates/iota-node/src/lib.rs @@ -1149,7 +1149,7 @@ impl IotaNode { } anemo_config.quic = Some(quic_config); - let server_name = format!("iota-{}", chain_identifier); + let server_name = format!("iota-{chain_identifier}"); let network = Network::bind(config.p2p_config.listen_address) .server_name(&server_name) .private_key(config.network_key_pair().copy().private().0.to_bytes()) diff --git a/crates/iota-node/src/metrics.rs b/crates/iota-node/src/metrics.rs index a6670b91a58..4ffdb2ffbe3 100644 --- a/crates/iota-node/src/metrics.rs +++ b/crates/iota-node/src/metrics.rs @@ -344,7 +344,7 @@ iota_counter_2 1" async fn get_metrics(port: u16) -> String { let client = reqwest::Client::new(); let response = client - .get(format!("http://127.0.0.1:{}/metrics", port)) + .get(format!("http://127.0.0.1:{port}/metrics")) .send() .await .unwrap(); diff --git a/crates/iota-open-rpc/src/lib.rs b/crates/iota-open-rpc/src/lib.rs index 348923a47ec..28eada956cd 100644 --- a/crates/iota-open-rpc/src/lib.rs +++ b/crates/iota-open-rpc/src/lib.rs @@ -389,7 +389,7 @@ impl RpcModuleDocBuilder { } else { Some(doc.trim().to_string()) }; - let name = format!("{}_{}", namespace, name); + let name = format!("{namespace}_{name}"); self.methods.insert( name.clone(), Method { diff --git a/crates/iota-package-management/build.rs b/crates/iota-package-management/build.rs index 50831cc4ac4..299b7380341 100644 --- a/crates/iota-package-management/build.rs +++ b/crates/iota-package-management/build.rs @@ -47,7 +47,7 @@ fn generate_system_packages_version_table() -> anyhow::Result<()> { writeln!(&mut file, "]")?; - println!("cargo::rerun-if-changed={}", manifest_path); + println!("cargo::rerun-if-changed={manifest_path}"); println!("cargo::rerun-if-changed=build.rs"); Ok(()) } diff --git a/crates/iota-protocol-config-macros/src/lib.rs b/crates/iota-protocol-config-macros/src/lib.rs index e0c998e7828..680b888d432 100644 --- a/crates/iota-protocol-config-macros/src/lib.rs +++ b/crates/iota-protocol-config-macros/src/lib.rs @@ -233,7 +233,7 @@ pub fn protocol_config_override_macro(input: TokenStream) -> TokenStream { // Create a new struct name by appending "Optional". let struct_name = &ast.ident; let optional_struct_name = - syn::Ident::new(&format!("{}Optional", struct_name), struct_name.span()); + syn::Ident::new(&format!("{struct_name}Optional"), struct_name.span()); // Extract the fields from the struct let fields = match &ast.data { diff --git a/crates/iota-protocol-config/src/lib.rs b/crates/iota-protocol-config/src/lib.rs index e2e46458ffc..81a00939afe 100644 --- a/crates/iota-protocol-config/src/lib.rs +++ b/crates/iota-protocol-config/src/lib.rs @@ -1990,7 +1990,7 @@ impl ProtocolConfig { // // // Remove a constant (ensure that it is never accessed during this version). // max_move_object_size: None, - _ => panic!("unsupported version {:?}", version), + _ => panic!("unsupported version {version:?}"), } } cfg @@ -2232,7 +2232,7 @@ mod test { // only test Mainnet and Testnet let chain_str = match chain_id { Chain::Unknown => "".to_string(), - _ => format!("{:?}_", chain_id), + _ => format!("{chain_id:?}_"), }; for i in MIN_PROTOCOL_VERSION..=MAX_PROTOCOL_VERSION { let cur = ProtocolVersion::new(i); diff --git a/crates/iota-proxy/src/admin.rs b/crates/iota-proxy/src/admin.rs index 3b8e08217f1..ba9a3960270 100644 --- a/crates/iota-proxy/src/admin.rs +++ b/crates/iota-proxy/src/admin.rs @@ -181,7 +181,7 @@ pub fn generate_self_cert(hostname: String) -> CertKeyPair { /// Load a certificate for use by the listening service fn load_certs(filename: &str) -> Vec> { let certfile = fs::File::open(filename) - .unwrap_or_else(|e| panic!("cannot open certificate file: {}; {}", filename, e)); + .unwrap_or_else(|e| panic!("cannot open certificate file: {filename}; {e}")); let mut reader = BufReader::new(certfile); rustls_pemfile::certs(&mut reader) .collect::, _>>() @@ -191,7 +191,7 @@ fn load_certs(filename: &str) -> Vec> /// Load a private key fn load_private_key(filename: &str) -> rustls::pki_types::PrivateKeyDer<'static> { let keyfile = fs::File::open(filename) - .unwrap_or_else(|e| panic!("cannot open private key file {}; {}", filename, e)); + .unwrap_or_else(|e| panic!("cannot open private key file {filename}; {e}")); let mut reader = BufReader::new(keyfile); loop { @@ -205,8 +205,7 @@ fn load_private_key(filename: &str) -> rustls::pki_types::PrivateKeyDer<'static> } panic!( - "no keys found in {:?} (encrypted keys not supported)", - filename + "no keys found in {filename:?} (encrypted keys not supported)" ); } @@ -265,7 +264,7 @@ pub fn create_server_cert_enforce_peer( )); }; let static_peers = load_static_peers(static_peers).map_err(|e| { - iota_tls::rustls::Error::General(format!("unable to load static pub keys: {}", e)) + iota_tls::rustls::Error::General(format!("unable to load static pub keys: {e}")) })?; let allower = IotaNodeProvider::new(dynamic_peers.url, dynamic_peers.interval, static_peers); allower.poll_peer_list(); diff --git a/crates/iota-proxy/src/config.rs b/crates/iota-proxy/src/config.rs index e16304c48be..4b4c493eddf 100644 --- a/crates/iota-proxy/src/config.rs +++ b/crates/iota-proxy/src/config.rs @@ -103,7 +103,7 @@ pub fn load, T: DeserializeOwned + Serialize>(path: P) let path = path.as_ref(); debug!("Reading config from {:?}", path); Ok(serde_yaml::from_reader( - std::fs::File::open(path).context(format!("cannot open {:?}", path))?, + std::fs::File::open(path).context(format!("cannot open {path:?}"))?, )?) } diff --git a/crates/iota-replay/src/batch_replay.rs b/crates/iota-replay/src/batch_replay.rs index 487a9586bcc..04bcd49adfb 100644 --- a/crates/iota-replay/src/batch_replay.rs +++ b/crates/iota-replay/src/batch_replay.rs @@ -124,7 +124,7 @@ async fn run_task( "[{}/{}] Replaying transaction {:?}...", index, total_count, digest ); - let sandbox_persist_path = persist_path.map(|path| path.join(format!("{}.json", digest,))); + let sandbox_persist_path = persist_path.map(|path| path.join(format!("{digest}.json",))); if let Some(p) = sandbox_persist_path.as_ref() { if p.exists() { info!( diff --git a/crates/iota-replay/src/displays/gas_status_displays.rs b/crates/iota-replay/src/displays/gas_status_displays.rs index 11858d59db7..d8e8b364bf9 100644 --- a/crates/iota-replay/src/displays/gas_status_displays.rs +++ b/crates/iota-replay/src/displays/gas_status_displays.rs @@ -42,7 +42,7 @@ fn per_object_storage_table(f: &mut Formatter, iota_gas_status: &GasStatusV1) -> 1, TableStyle::modern().get_horizontal(), )])); - write!(f, "\n{}\n", table) + write!(f, "\n{table}\n") } fn display_info(f: &mut Formatter<'_>, iota_gas_status: &GasStatusV1) -> std::fmt::Result { @@ -75,5 +75,5 @@ fn display_info(f: &mut Formatter<'_>, iota_gas_status: &GasStatusV1) -> std::fm let mut table = builder.build(); table.with(TableStyle::rounded()); - write!(f, "\n{}\n", table) + write!(f, "\n{table}\n") } diff --git a/crates/iota-replay/src/displays/transaction_displays.rs b/crates/iota-replay/src/displays/transaction_displays.rs index e7673957092..78cc7cdef93 100644 --- a/crates/iota-replay/src/displays/transaction_displays.rs +++ b/crates/iota-replay/src/displays/transaction_displays.rs @@ -95,7 +95,7 @@ impl Display for Pretty<'_, FullPTB> { 1, TableStyle::modern().get_horizontal(), )])); - write!(f, "\n{}\n", table)?; + write!(f, "\n{table}\n")?; } else { write!(f, "\n No input objects for this transaction")?; } @@ -137,7 +137,7 @@ impl Display for Pretty<'_, FullPTB> { 1, TableStyle::modern().get_horizontal(), )])); - write!(f, "\n{}\n", table)?; + write!(f, "\n{table}\n")?; } else { write!(f, "\n No commands for this transaction")?; } @@ -214,8 +214,7 @@ impl Display for Pretty<'_, ProgrammableMoveCall> { write!( f, - "MoveCall:\n ┌\n │ Function: {} \n │ Module: {}\n │ Package: {}", - function, module, package + "MoveCall:\n ┌\n │ Function: {function} \n │ Module: {module}\n │ Package: {package}" )?; if !type_arguments.is_empty() { @@ -237,11 +236,11 @@ impl Display for Pretty<'_, Argument> { let output = match argument { Argument::GasCoin => "GasCoin".to_string(), - Argument::Input(i) => format!("Input {}", i), - Argument::Result(i) => format!("Result {}", i), - Argument::NestedResult(j, k) => format!("Result {}: {}", j, k), + Argument::Input(i) => format!("Input {i}"), + Argument::Result(i) => format!("Result {i}"), + Argument::NestedResult(j, k) => format!("Result {j}: {k}"), }; - write!(f, "{}", output) + write!(f, "{output}") } } impl Display for Pretty<'_, ResolvedResults> { @@ -260,7 +259,7 @@ impl Display for Pretty<'_, ResolvedResults> { for (i, value) in return_values.iter().enumerate() { write!(f, "\n • Result {i:<2} ")?; - write!(f, "\n{:#}\n", value)?; + write!(f, "\n{value:#}\n")?; } if len_m_ref > 0 { @@ -271,8 +270,8 @@ impl Display for Pretty<'_, ResolvedResults> { } for (arg, value) in mutable_reference_outputs { - write!(f, "\n • {} ", arg)?; - write!(f, "\n{:#}\n", value)?; + write!(f, "\n • {arg} ")?; + write!(f, "\n{value:#}\n")?; } if len_ret_vals == 0 && len_m_ref == 0 { @@ -294,7 +293,7 @@ impl Display for Pretty<'_, TypeTag> { write!(f, "{}::{}", s.module, s.name) } _ => { - write!(f, "{}", type_tag) + write!(f, "{type_tag}") } } } diff --git a/crates/iota-replay/src/lib.rs b/crates/iota-replay/src/lib.rs index 4c27d96156e..1cd16e4b7f8 100644 --- a/crates/iota-replay/src/lib.rs +++ b/crates/iota-replay/src/lib.rs @@ -242,7 +242,7 @@ pub async fn execute_replay_command( .await?; let out = serde_json::to_string(&sandbox_state).unwrap(); - let path = base_path.join(format!("{}.json", tx_digest)); + let path = base_path.join(format!("{tx_digest}.json")); std::fs::write(path, out)?; None } @@ -303,7 +303,7 @@ pub async fn execute_replay_command( let digests = buf_reader.lines().map(|line| { let line = line.unwrap(); TransactionDigest::from_str(&line).unwrap_or_else(|err| { - panic!("Error parsing tx digest {:?}: {:?}", line, err); + panic!("Error parsing tx digest {line:?}: {err:?}"); }) }); batch_replay::batch_replay( @@ -451,7 +451,7 @@ pub async fn execute_replay_command( for x in lx.protocol_version_system_package_table { println!("Protocol version: {}", x.0); for (package_id, seq_num) in x.1 { - println!("Package: {} Seq: {}", package_id, seq_num); + println!("Package: {package_id} Seq: {seq_num}"); } } None diff --git a/crates/iota-replay/src/replay.rs b/crates/iota-replay/src/replay.rs index 35f3bd41ad7..62f0cef506a 100644 --- a/crates/iota-replay/src/replay.rs +++ b/crates/iota-replay/src/replay.rs @@ -89,10 +89,10 @@ impl ExecutionSandboxState { if self.transaction_info.effects != self.local_exec_effects { error!("Replay tool forked {}", self.transaction_info.tx_digest); let diff = self.diff_effects(); - println!("{}", diff); + println!("{diff}"); return Err(ReplayEngineError::EffectsForked { digest: self.transaction_info.tx_digest, - diff: format!("\n{}", diff), + diff: format!("\n{diff}"), on_chain: Box::new(self.transaction_info.effects.clone()), local: Box::new(self.local_exec_effects.clone()), }); @@ -104,8 +104,8 @@ impl ExecutionSandboxState { pub fn diff_effects(&self) -> String { let eff1 = &self.transaction_info.effects; let eff2 = &self.local_exec_effects; - let on_chain_str = format!("{:#?}", eff1); - let local_chain_str = format!("{:#?}", eff2); + let on_chain_str = format!("{eff1:#?}"); + let local_chain_str = format!("{eff2:#?}"); let mut res = vec![]; let diff = TextDiff::from_lines(&on_chain_str, &local_chain_str); @@ -115,7 +115,7 @@ impl ExecutionSandboxState { ChangeTag::Insert => "+++", ChangeTag::Equal => " ", }; - res.push(format!("{}{}", sign, change)); + res.push(format!("{sign}{change}")); } res.join("") @@ -1405,8 +1405,7 @@ impl LocalExec { .checkpoint .unwrap_or_else(|| { panic!( - "Checkpoint for transaction {} not present. Could be due to pruning", - epoch_change_tx + "Checkpoint for transaction {epoch_change_tx} not present. Could be due to pruning" ) }), idx, @@ -1425,8 +1424,7 @@ impl LocalExec { .checkpoint .unwrap_or_else(|| { panic!( - "Checkpoint for transaction {} not present. Could be due to pruning", - next_epoch_change_tx + "Checkpoint for transaction {next_epoch_change_tx} not present. Could be due to pruning" ) }); diff --git a/crates/iota-replay/src/tests.rs b/crates/iota-replay/src/tests.rs index f88b0086f08..150d4a7cb2c 100644 --- a/crates/iota-replay/src/tests.rs +++ b/crates/iota-replay/src/tests.rs @@ -78,8 +78,7 @@ async fn verify_latest_tx_replay_impl() { if non_system_txs.is_none() { panic!( - "No non-system txs found in the last {} checkpoints for network {} using rpc url {}", - NUM_CHECKPOINTS_TO_ATTEMPT, chain_id, url + "No non-system txs found in the last {NUM_CHECKPOINTS_TO_ATTEMPT} checkpoints for network {chain_id} using rpc url {url}" ); } let tx: TransactionDigest = non_system_txs.unwrap(); @@ -98,7 +97,7 @@ async fn verify_latest_tx_replay_impl() { for (url, ret) in rets { if let Err(e) = ret { - panic!("Replay failed for network {} with error {:?}", url, e); + panic!("Replay failed for network {url} with error {e:?}"); } } } diff --git a/crates/iota-replay/src/types.rs b/crates/iota-replay/src/types.rs index 43efba9777d..a7a8107d7fd 100644 --- a/crates/iota-replay/src/types.rs +++ b/crates/iota-replay/src/types.rs @@ -176,7 +176,7 @@ pub enum ReplayEngineError { #[error("Unable to query system events; {}", rpc_err)] UnableToQuerySystemEvents { rpc_err: String }, - #[error("Internal error or cache corrupted! Object {id}{} should be in cache.", version.map(|q| format!(" version {:#?}", q)).unwrap_or_default() + #[error("Internal error or cache corrupted! Object {id}{} should be in cache.", version.map(|q| format!(" version {q:#?}")).unwrap_or_default() )] InternalCacheInvariantViolation { id: ObjectID, @@ -227,7 +227,7 @@ impl From for ReplayEngineError { impl From for IotaError { fn from(err: ReplayEngineError) -> Self { - IotaError::Unknown(format!("{:#?}", err)) + IotaError::Unknown(format!("{err:#?}")) } } @@ -243,7 +243,7 @@ impl From for ReplayEngineError { ReplayEngineError::IotaRpcRequestTimeout } _ => ReplayEngineError::IotaRpcError { - err: format!("{:?}", err), + err: format!("{err:?}"), }, } } @@ -258,7 +258,7 @@ impl From for ReplayEngineError { impl From for ReplayEngineError { fn from(err: anyhow::Error) -> Self { ReplayEngineError::GeneralError { - err: format!("{:#?}", err), + err: format!("{err:#?}"), } } } diff --git a/crates/iota-rest-api/src/error.rs b/crates/iota-rest-api/src/error.rs index b6c07b47026..5bf4a1f6e52 100644 --- a/crates/iota-rest-api/src/error.rs +++ b/crates/iota-rest-api/src/error.rs @@ -102,8 +102,7 @@ impl From for RestError { .collect::>>(); let message = format!( - "Failed to sign transaction by a quorum of validators because of locked objects. Retried a conflicting transaction {:?}, success: {:?}. Conflicting Transactions:\n{:#?}", - retried_tx, retried_tx_success, new_map, + "Failed to sign transaction by a quorum of validators because of locked objects. Retried a conflicting transaction {retried_tx:?}, success: {retried_tx_success:?}. Conflicting Transactions:\n{new_map:#?}", ); RestError::new(StatusCode::CONFLICT, message) @@ -151,8 +150,7 @@ impl From for RestError { let error_list = new_errors.join(", "); let error_msg = format!( - "Transaction execution failed due to issues with transaction inputs, please review the errors and try again: {}.", - error_list + "Transaction execution failed due to issues with transaction inputs, please review the errors and try again: {error_list}." ); RestError::new(StatusCode::BAD_REQUEST, error_msg) diff --git a/crates/iota-rest-api/src/openapi.rs b/crates/iota-rest-api/src/openapi.rs index f8840098856..480475b7115 100644 --- a/crates/iota-rest-api/src/openapi.rs +++ b/crates/iota-rest-api/src/openapi.rs @@ -198,7 +198,7 @@ impl<'a, S> Api<'a, S> { Method::POST => &mut pathitem.post, Method::PUT => &mut pathitem.put, Method::TRACE => &mut pathitem.trace, - other => panic!("unexpected method `{}`", other), + other => panic!("unexpected method `{other}`"), }; let operation = endpoint.operation(generator); diff --git a/crates/iota-rosetta/src/unit_tests/balance_changing_tx_tests.rs b/crates/iota-rosetta/src/unit_tests/balance_changing_tx_tests.rs index dc38acc8d1e..6d178ef6d55 100644 --- a/crates/iota-rosetta/src/unit_tests/balance_changing_tx_tests.rs +++ b/crates/iota-rosetta/src/unit_tests/balance_changing_tx_tests.rs @@ -762,8 +762,7 @@ async fn test_transaction( assert_eq!( IotaExecutionStatus::Success, *effects.status(), - "TX execution failed for {:#?}", - data + "TX execution failed for {data:#?}" ); } else { assert!(matches!( @@ -784,8 +783,7 @@ async fn test_transaction( } assert_eq!( actual_balance_change, balances_from_ops, - "balance check failed for tx: {}\neffect:{:#?}", - tx, effects + "balance check failed for tx: {tx}\neffect:{effects:#?}" ); response } diff --git a/crates/iota-rosetta/src/unit_tests/operations_tests.rs b/crates/iota-rosetta/src/unit_tests/operations_tests.rs index ff1a081f0de..29c83dbdeab 100644 --- a/crates/iota-rosetta/src/unit_tests/operations_tests.rs +++ b/crates/iota-rosetta/src/unit_tests/operations_tests.rs @@ -58,5 +58,5 @@ async fn test_iota_json() { let arg2 = CallArg::Pure(bcs::to_bytes(&30215u64).unwrap()); let json1 = IotaCallArg::try_from(arg1, Some(&MoveTypeLayout::U64)).unwrap(); let json2 = IotaCallArg::try_from(arg2, Some(&MoveTypeLayout::U64)).unwrap(); - println!("{:?}, {:?}", json1, json2); + println!("{json1:?}, {json2:?}"); } diff --git a/crates/iota-rosetta/tests/end_to_end_tests.rs b/crates/iota-rosetta/tests/end_to_end_tests.rs index 2260aad6e80..52bec129f97 100644 --- a/crates/iota-rosetta/tests/end_to_end_tests.rs +++ b/crates/iota-rosetta/tests/end_to_end_tests.rs @@ -455,7 +455,7 @@ async fn test_pay_iota_multiple_times() { let (rosetta_client, _handle) = start_rosetta_test_server(client.clone()).await; for i in 1..20 { - println!("Iteration: {}", i); + println!("Iteration: {i}"); let ops = serde_json::from_value(json!( [{ "operation_identifier":{"index":0}, diff --git a/crates/iota-rosetta/tests/rosetta_client.rs b/crates/iota-rosetta/tests/rosetta_client.rs index 1af8ccc2ace..c7fe9b8a4ab 100644 --- a/crates/iota-rosetta/tests/rosetta_client.rs +++ b/crates/iota-rosetta/tests/rosetta_client.rs @@ -35,14 +35,14 @@ pub async fn start_rosetta_test_server(client: IotaClient) -> (RosettaClient, Ve let offline_server = RosettaOfflineServer::new(IotaEnv::LocalNet); let local_ip = local_ip_utils::localhost_for_testing(); let port = local_ip_utils::get_available_port(&local_ip); - let rosetta_address = format!("{}:{}", local_ip, port); + let rosetta_address = format!("{local_ip}:{port}"); let online_handle = tokio::spawn(async move { online_server .serve(SocketAddr::from_str(&rosetta_address).unwrap()) .await }); let offline_port = local_ip_utils::get_available_port(&local_ip); - let offline_address = format!("{}:{}", local_ip, offline_port); + let offline_address = format!("{local_ip}:{offline_port}"); let offline_handle = tokio::spawn(async move { offline_server .serve(SocketAddr::from_str(&offline_address).unwrap()) diff --git a/crates/iota-rpc-loadgen/src/main.rs b/crates/iota-rpc-loadgen/src/main.rs index d8967c43b37..d6ae538a478 100644 --- a/crates/iota-rpc-loadgen/src/main.rs +++ b/crates/iota-rpc-loadgen/src/main.rs @@ -152,14 +152,14 @@ fn get_iota_config_directory() -> PathBuf { pub fn expand_path(dir_path: &str) -> String { shellexpand::full(&dir_path) .map(|v| v.into_owned()) - .unwrap_or_else(|e| panic!("Failed to expand directory '{:?}': {}", dir_path, e)) + .unwrap_or_else(|e| panic!("Failed to expand directory '{dir_path:?}': {e}")) } fn get_log_file_path(dir_path: String) -> String { let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); let timestamp = current_time.as_secs(); // use timestamp to signify which file is newer - let log_filename = format!("iota-rpc-loadgen.{}.log", timestamp); + let log_filename = format!("iota-rpc-loadgen.{timestamp}.log"); let dir_path = expand_path(&dir_path); format!("{dir_path}/{log_filename}") diff --git a/crates/iota-rpc-loadgen/src/payload/rpc_command_processor.rs b/crates/iota-rpc-loadgen/src/payload/rpc_command_processor.rs index 75a2bb9f3e0..9511309df99 100644 --- a/crates/iota-rpc-loadgen/src/payload/rpc_command_processor.rs +++ b/crates/iota-rpc-loadgen/src/payload/rpc_command_processor.rs @@ -368,7 +368,7 @@ fn write_data_to_file(data: &T, file_path: &str) -> Result<(), any path_buf.pop(); fs::create_dir_all(&path_buf).map_err(|e| anyhow!("Error creating directory: {}", e))?; - let file_name = format!("{}.json", file_path); + let file_name = format!("{file_path}.json"); let file = File::create(file_name).map_err(|e| anyhow!("Error creating file: {}", e))?; serde_json::to_writer(file, data).map_err(|e| anyhow!("Error writing to file: {}", e))?; diff --git a/crates/iota-sdk/examples/event_api.rs b/crates/iota-sdk/examples/event_api.rs index 19876789cbf..b76eef28c19 100644 --- a/crates/iota-sdk/examples/event_api.rs +++ b/crates/iota-sdk/examples/event_api.rs @@ -23,7 +23,7 @@ async fn main() -> Result<(), anyhow::Error> { // for demonstration purposes, we set to make a transaction let digest = split_coin_digest(&client, &active_address).await?; let events = client.event_api().get_events(digest).await?; - println!("{:?}", events); + println!("{events:?}"); println!(" *** Get events ***\n "); let descending = true; @@ -32,7 +32,7 @@ async fn main() -> Result<(), anyhow::Error> { .query_events(EventFilter::All(vec![]), None, 5, descending) // query first 5 events in descending order .await?; println!(" *** Query events *** "); - println!("{:?}", query_events); + println!("{query_events:?}"); println!(" *** Query events ***\n "); let ws = IotaClientBuilder::default() diff --git a/crates/iota-sdk/examples/governance_api.rs b/crates/iota-sdk/examples/governance_api.rs index 8a550d54c66..af0987deb78 100644 --- a/crates/iota-sdk/examples/governance_api.rs +++ b/crates/iota-sdk/examples/governance_api.rs @@ -20,14 +20,14 @@ async fn main() -> Result<(), anyhow::Error> { let stakes = client.governance_api().get_stakes(active_address).await?; println!(" *** Stakes ***"); - println!("{:?}", stakes); + println!("{stakes:?}"); println!(" *** Stakes ***\n"); // Committee Info let committee = client.governance_api().get_committee_info(None).await?; // None defaults to the latest epoch println!(" *** Committee Info ***"); - println!("{:?}", committee); + println!("{committee:?}"); println!(" *** Committee Info ***\n"); // Latest IOTA System State @@ -37,7 +37,7 @@ async fn main() -> Result<(), anyhow::Error> { .await?; println!(" *** IOTA System State ***"); - println!("{:?}", iota_system_state); + println!("{iota_system_state:?}"); println!(" *** IOTA System State ***\n"); // List all active validators because we listed committee info above. @@ -57,7 +57,7 @@ async fn main() -> Result<(), anyhow::Error> { let reference_gas_price = client.governance_api().get_reference_gas_price().await?; println!(" *** Reference Gas Price ***"); - println!("{:?}", reference_gas_price); + println!("{reference_gas_price:?}"); println!(" *** Reference Gas Price ***\n"); Ok(()) diff --git a/crates/iota-sdk/examples/read_api/checkpoints.rs b/crates/iota-sdk/examples/read_api/checkpoints.rs index 3895861bb0e..cdd428b4f52 100644 --- a/crates/iota-sdk/examples/read_api/checkpoints.rs +++ b/crates/iota-sdk/examples/read_api/checkpoints.rs @@ -31,7 +31,7 @@ async fn main() -> Result<(), anyhow::Error> { .read_api() .get_checkpoints(Some((latest_checkpoint_number - 3).into()), 2, false) .await?; - println!("Second and third last checkpoints:\n{:?}", checkpoints); + println!("Second and third last checkpoints:\n{checkpoints:?}"); Ok(()) } diff --git a/crates/iota-sdk/examples/transaction_builder/batch_tx.rs b/crates/iota-sdk/examples/transaction_builder/batch_tx.rs index 2fe664a30db..7a93acbf721 100644 --- a/crates/iota-sdk/examples/transaction_builder/batch_tx.rs +++ b/crates/iota-sdk/examples/transaction_builder/batch_tx.rs @@ -51,7 +51,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } Ok(()) diff --git a/crates/iota-sdk/examples/transaction_builder/function_move_call.rs b/crates/iota-sdk/examples/transaction_builder/function_move_call.rs index 9d7823196a6..acd027316e5 100644 --- a/crates/iota-sdk/examples/transaction_builder/function_move_call.rs +++ b/crates/iota-sdk/examples/transaction_builder/function_move_call.rs @@ -100,6 +100,6 @@ async fn main() -> Result<(), anyhow::Error> { ExecuteTransactionRequestType::WaitForLocalExecution, ) .await?; - println!("{}", transaction_response); + println!("{transaction_response}"); Ok(()) } diff --git a/crates/iota-sdk/examples/transaction_builder/move_package.rs b/crates/iota-sdk/examples/transaction_builder/move_package.rs index 024a9a99257..550caac85af 100644 --- a/crates/iota-sdk/examples/transaction_builder/move_package.rs +++ b/crates/iota-sdk/examples/transaction_builder/move_package.rs @@ -47,7 +47,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Object changes:"); let object_changes = transaction_response.object_changes.unwrap(); for object_change in &object_changes { - println!("{:?}", object_change); + println!("{object_change:?}"); } // Wait some time for the indexer to process the tx @@ -104,7 +104,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } Ok(()) diff --git a/crates/iota-sdk/examples/transaction_builder/pay.rs b/crates/iota-sdk/examples/transaction_builder/pay.rs index 1dbf1015ac0..07ebcb1dd8d 100644 --- a/crates/iota-sdk/examples/transaction_builder/pay.rs +++ b/crates/iota-sdk/examples/transaction_builder/pay.rs @@ -44,7 +44,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } Ok(()) diff --git a/crates/iota-sdk/examples/transaction_builder/pay_iota.rs b/crates/iota-sdk/examples/transaction_builder/pay_iota.rs index 78cad34df74..db40d02006f 100644 --- a/crates/iota-sdk/examples/transaction_builder/pay_iota.rs +++ b/crates/iota-sdk/examples/transaction_builder/pay_iota.rs @@ -63,7 +63,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } Ok(()) diff --git a/crates/iota-sdk/examples/transaction_builder/programmable_transactions_api.rs b/crates/iota-sdk/examples/transaction_builder/programmable_transactions_api.rs index 2d4bfaeb329..4040b9eef68 100644 --- a/crates/iota-sdk/examples/transaction_builder/programmable_transactions_api.rs +++ b/crates/iota-sdk/examples/transaction_builder/programmable_transactions_api.rs @@ -76,7 +76,7 @@ async fn main() -> Result<(), anyhow::Error> { print!("Executing the transaction..."); let transaction_response = sign_and_execute_transaction(&client, &sender, tx_data).await?; print!("done\n Transaction information: "); - println!("{:?}", transaction_response); + println!("{transaction_response:?}"); let coins = client .coin_read_api() diff --git a/crates/iota-sdk/examples/transaction_builder/single_move_call.rs b/crates/iota-sdk/examples/transaction_builder/single_move_call.rs index 1195f422727..64fa6250975 100644 --- a/crates/iota-sdk/examples/transaction_builder/single_move_call.rs +++ b/crates/iota-sdk/examples/transaction_builder/single_move_call.rs @@ -59,7 +59,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } Ok(()) diff --git a/crates/iota-sdk/examples/transaction_builder/split_merge_coins.rs b/crates/iota-sdk/examples/transaction_builder/split_merge_coins.rs index 539d9ca86d3..a351bf20fb9 100644 --- a/crates/iota-sdk/examples/transaction_builder/split_merge_coins.rs +++ b/crates/iota-sdk/examples/transaction_builder/split_merge_coins.rs @@ -36,7 +36,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } // Wait some time for the indexer to process the tx @@ -65,7 +65,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } // Wait some time for the indexer to process the tx @@ -93,7 +93,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } Ok(()) diff --git a/crates/iota-sdk/examples/transaction_builder/stake.rs b/crates/iota-sdk/examples/transaction_builder/stake.rs index e4d03385740..8864fef2d3e 100644 --- a/crates/iota-sdk/examples/transaction_builder/stake.rs +++ b/crates/iota-sdk/examples/transaction_builder/stake.rs @@ -60,7 +60,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } // Unstake IOTA, if staking for longer than 1 epoch already @@ -87,7 +87,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } } else { println!("No stake found that can be unlocked (must be staked >= 1 epoch)") diff --git a/crates/iota-sdk/examples/transaction_builder/timelocked_stake.rs b/crates/iota-sdk/examples/transaction_builder/timelocked_stake.rs index 26882a61ddb..8f9bcc9d118 100644 --- a/crates/iota-sdk/examples/transaction_builder/timelocked_stake.rs +++ b/crates/iota-sdk/examples/transaction_builder/timelocked_stake.rs @@ -108,7 +108,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } // Wait for indexer to process the tx @@ -164,7 +164,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } // Wait for indexer to process the tx diff --git a/crates/iota-sdk/examples/transaction_builder/transfer.rs b/crates/iota-sdk/examples/transaction_builder/transfer.rs index 9674672b31f..060e409ba25 100644 --- a/crates/iota-sdk/examples/transaction_builder/transfer.rs +++ b/crates/iota-sdk/examples/transaction_builder/transfer.rs @@ -36,7 +36,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } // Very similar to above, but works with any object, not just with IOTAs @@ -62,7 +62,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } Ok(()) diff --git a/crates/iota-sdk/examples/transaction_builder/tx_data.rs b/crates/iota-sdk/examples/transaction_builder/tx_data.rs index 1b2c8016045..ba46d048136 100644 --- a/crates/iota-sdk/examples/transaction_builder/tx_data.rs +++ b/crates/iota-sdk/examples/transaction_builder/tx_data.rs @@ -44,7 +44,7 @@ async fn main() -> Result<(), anyhow::Error> { println!("Transaction sent {}", transaction_response.digest); println!("Object changes:"); for object_change in transaction_response.object_changes.unwrap() { - println!("{:?}", object_change); + println!("{object_change:?}"); } Ok(()) diff --git a/crates/iota-sdk/src/apis/read.rs b/crates/iota-sdk/src/apis/read.rs index 3ef8fb5d66c..ce98e301269 100644 --- a/crates/iota-sdk/src/apis/read.rs +++ b/crates/iota-sdk/src/apis/read.rs @@ -441,13 +441,12 @@ impl ReadApi { .await? .into_object() .map_err(|e| { - Error::Data(format!("Can't get bcs of object {:?}: {:?}", object_id, e)) + Error::Data(format!("Can't get bcs of object {object_id:?}: {e:?}")) })?; // unwrap: requested bcs data let move_object = resp.bcs.unwrap(); let raw_move_obj = move_object.try_into_move().ok_or(Error::Data(format!( - "Object {:?} is not a MoveObject", - object_id + "Object {object_id:?} is not a MoveObject" )))?; Ok(raw_move_obj.bcs_bytes) } diff --git a/crates/iota-sdk/src/iota_client_config.rs b/crates/iota-sdk/src/iota_client_config.rs index d985bccd6b3..c046e920738 100644 --- a/crates/iota-sdk/src/iota_client_config.rs +++ b/crates/iota-sdk/src/iota_client_config.rs @@ -294,13 +294,13 @@ impl Display for IotaClientConfig { )?; write!(writer, "Active address: ")?; match self.active_address { - Some(r) => writeln!(writer, "{}", r)?, + Some(r) => writeln!(writer, "{r}")?, None => writeln!(writer, "None")?, }; writeln!(writer, "{}", self.keystore)?; if let Ok(env) = self.get_active_env() { - write!(writer, "{}", env)?; + write!(writer, "{env}")?; } - write!(f, "{}", writer) + write!(f, "{writer}") } } diff --git a/crates/iota-sdk/src/lib.rs b/crates/iota-sdk/src/lib.rs index ac53c7a76f6..e513f8329a8 100644 --- a/crates/iota-sdk/src/lib.rs +++ b/crates/iota-sdk/src/lib.rs @@ -248,11 +248,11 @@ impl IotaClientBuilder { if let Some((username, password)) = self.basic_auth { let auth = base64::engine::general_purpose::STANDARD - .encode(format!("{}:{}", username, password)); + .encode(format!("{username}:{password}")); headers.insert( "authorization", // reqwest::header::AUTHORIZATION, - HeaderValue::from_str(&format!("Basic {}", auth)).unwrap(), + HeaderValue::from_str(&format!("Basic {auth}")).unwrap(), ); } diff --git a/crates/iota-sdk/src/wallet_context.rs b/crates/iota-sdk/src/wallet_context.rs index 62b7b1a324f..c1544b0d43f 100644 --- a/crates/iota-sdk/src/wallet_context.rs +++ b/crates/iota-sdk/src/wallet_context.rs @@ -338,8 +338,7 @@ impl WalletContext { let response = self.execute_transaction_may_fail(tx).await.unwrap(); assert!( response.status_ok().unwrap(), - "Transaction failed: {:?}", - response + "Transaction failed: {response:?}" ); response } diff --git a/crates/iota-single-node-benchmark/src/tx_generator/package_publish_tx_generator.rs b/crates/iota-single-node-benchmark/src/tx_generator/package_publish_tx_generator.rs index 656fb309f6f..321ecc5201b 100644 --- a/crates/iota-single-node-benchmark/src/tx_generator/package_publish_tx_generator.rs +++ b/crates/iota-single-node-benchmark/src/tx_generator/package_publish_tx_generator.rs @@ -134,9 +134,9 @@ struct Package { fn load_manifest_json(file_path: &PathBuf) -> PackageDependencyManifest { let data = fs::read_to_string(file_path) - .unwrap_or_else(|_| panic!("Unable to read file at: {:?}", file_path)); + .unwrap_or_else(|_| panic!("Unable to read file at: {file_path:?}")); let parsed_data: PackageDependencyManifest = serde_json::from_str(&data) - .unwrap_or_else(|_| panic!("Unable to parse json from file at: {:?}", file_path)); + .unwrap_or_else(|_| panic!("Unable to parse json from file at: {file_path:?}")); parsed_data } diff --git a/crates/iota-snapshot/src/lib.rs b/crates/iota-snapshot/src/lib.rs index b9c9e4be2e3..0d805f0b8c9 100644 --- a/crates/iota-snapshot/src/lib.rs +++ b/crates/iota-snapshot/src/lib.rs @@ -319,8 +319,7 @@ pub async fn accumulate_live_object_iter( let accumulations_per_sec = num_accumulated as f64 / a_instant.elapsed().as_secs_f64(); cloned_progress_bar.set_position(num_accumulated); cloned_progress_bar.set_message(format!( - "DB live obj accumulations per sec: {}", - accumulations_per_sec + "DB live obj accumulations per sec: {accumulations_per_sec}" )); tokio::time::sleep(Duration::from_secs(1)).await; } diff --git a/crates/iota-snapshot/src/reader.rs b/crates/iota-snapshot/src/reader.rs index 86057c231d5..a894c7ba3bc 100644 --- a/crates/iota-snapshot/src/reader.rs +++ b/crates/iota-snapshot/src/reader.rs @@ -80,7 +80,7 @@ impl StateSnapshotReaderV1 { download_concurrency: NonZeroUsize, multi_progress_bar: MultiProgress, ) -> Result { - let epoch_dir = format!("epoch_{}", epoch); + let epoch_dir = format!("epoch_{epoch}"); let remote_object_store = if remote_store_config.no_sign_request { remote_store_config.make_http()? } else { @@ -261,7 +261,7 @@ impl StateSnapshotReaderV1 { .or_insert(hasher.finalize().digest); } checksum_progress_bar.inc(1); - checksum_progress_bar.set_message(format!("Bucket: {}, Part: {}", bucket, part)); + checksum_progress_bar.set_message(format!("Bucket: {bucket}, Part: {part}")); } } checksum_progress_bar.finish_with_message("Checksumming complete"); @@ -312,8 +312,7 @@ impl StateSnapshotReaderV1 { num_partitions as f64 / a_instant.elapsed().as_secs_f64(); cloned_accum_progress_bar.set_position(num_partitions); cloned_accum_progress_bar.set_message(format!( - "file partitions per sec: {}", - total_partitions_per_sec + "file partitions per sec: {total_partitions_per_sec}" )); tokio::time::sleep(Duration::from_secs(1)).await; } diff --git a/crates/iota-snapshot/src/writer.rs b/crates/iota-snapshot/src/writer.rs index e647710f1ad..24a380a2193 100644 --- a/crates/iota-snapshot/src/writer.rs +++ b/crates/iota-snapshot/src/writer.rs @@ -514,7 +514,7 @@ impl StateSnapshotWriterV1 { } fn epoch_dir(&self, epoch: u64) -> Path { - Path::from(format!("epoch_{}", epoch)) + Path::from(format!("epoch_{epoch}")) } /// Creates a new epoch directory and a new staging directory for the epoch @@ -529,7 +529,7 @@ impl StateSnapshotWriterV1 { ) .await?; // Deletes local staging epoch dir if it exists - let local_epoch_dir_path = self.local_staging_dir.join(format!("epoch_{}", epoch)); + let local_epoch_dir_path = self.local_staging_dir.join(format!("epoch_{epoch}")); if local_epoch_dir_path.exists() { fs::remove_dir_all(&local_epoch_dir_path)?; } diff --git a/crates/iota-source-validation-service/tests/tests.rs b/crates/iota-source-validation-service/tests/tests.rs index 4a28b9ded4d..8ce03f73a24 100644 --- a/crates/iota-source-validation-service/tests/tests.rs +++ b/crates/iota-source-validation-service/tests/tests.rs @@ -472,7 +472,7 @@ paths = [ ), ], }"#]]; - expect.assert_eq(&format!("{:#?}", config)); + expect.assert_eq(&format!("{config:#?}")); Ok(()) } @@ -531,6 +531,6 @@ fn test_clone_command() -> anyhow::Result<()> { repo_url: "https://github.com/user/repo", }"# ]; - expect.assert_eq(&format!("{:#?}", command)); + expect.assert_eq(&format!("{command:#?}")); Ok(()) } diff --git a/crates/iota-source-validation/src/error.rs b/crates/iota-source-validation/src/error.rs index f418c1d9685..0f1b1434f3f 100644 --- a/crates/iota-source-validation/src/error.rs +++ b/crates/iota-source-validation/src/error.rs @@ -76,11 +76,11 @@ impl fmt::Display for AggregateError { let Self(errors) = self; match &errors[..] { [] => unreachable!("Aggregate error with no errors"), - [error] => write!(f, "{}", error)?, + [error] => write!(f, "{error}")?, errors => { writeln!(f, "Multiple source verification errors found:")?; for error in errors { - write!(f, "\n- {}", error)?; + write!(f, "\n- {error}")?; } return Ok(()); } diff --git a/crates/iota-source-validation/src/toolchain.rs b/crates/iota-source-validation/src/toolchain.rs index 88515eb744b..bb421866c8e 100644 --- a/crates/iota-source-validation/src/toolchain.rs +++ b/crates/iota-source-validation/src/toolchain.rs @@ -236,7 +236,7 @@ fn download_and_compile( Err(e) => return Err(e.into()), }.into_reader(); - let dest_tarball = dest_version.join(format!("{}.tgz", compiler_version)); + let dest_tarball = dest_version.join(format!("{compiler_version}.tgz")); debug!("tarball destination: {} ", dest_tarball.display()); if let Some(parent) = dest_tarball.parent() { std::fs::create_dir_all(parent) diff --git a/crates/iota-storage/src/bin/http_kv_tool.rs b/crates/iota-storage/src/bin/http_kv_tool.rs index cd27c5ccee6..96f326e8b75 100644 --- a/crates/iota-storage/src/bin/http_kv_tool.rs +++ b/crates/iota-storage/src/bin/http_kv_tool.rs @@ -70,12 +70,12 @@ async fn main() { if options.type_ == "tx" { let tx = kv.multi_get_tx(&digests).await.unwrap(); for (digest, tx) in digests.iter().zip(tx.iter()) { - println!("fetched tx: {:?} {:?}", digest, tx); + println!("fetched tx: {digest:?} {tx:?}"); } } else { let fx = kv.multi_get_fx_by_tx_digest(&digests).await.unwrap(); for (digest, fx) in digests.iter().zip(fx.iter()) { - println!("fetched fx: {:?} {:?}", digest, fx); + println!("fetched fx: {digest:?} {fx:?}"); } } } @@ -86,7 +86,7 @@ async fn main() { for (seq, ckpt) in seqs.iter().zip(ckpts.1.iter()) { // populate digest before printing ckpt.as_ref().map(|c| c.digest()); - println!("fetched ckpt contents: {:?} {:?}", seq, ckpt); + println!("fetched ckpt contents: {seq:?} {ckpt:?}"); } } @@ -105,19 +105,19 @@ async fn main() { for (seq, ckpt) in seqs.iter().zip(ckpts.0.iter()) { // populate digest before printing ckpt.as_ref().map(|c| c.digest()); - println!("fetched ckpt summary: {:?} {:?}", seq, ckpt); + println!("fetched ckpt summary: {seq:?} {ckpt:?}"); } for (digest, ckpt) in digests.iter().zip(ckpts.2.iter()) { // populate digest before printing ckpt.as_ref().map(|c| c.digest()); - println!("fetched ckpt summary: {:?} {:?}", digest, ckpt); + println!("fetched ckpt summary: {digest:?} {ckpt:?}"); } } "ob" => { let object_id = ObjectID::from_str(&options.digest[0]).expect("invalid object id"); let object = kv.get_object(object_id, seqs[0].into()).await.unwrap(); - println!("fetched object {:?}", object); + println!("fetched object {object:?}"); } _ => { diff --git a/crates/iota-storage/src/http_key_value_store.rs b/crates/iota-storage/src/http_key_value_store.rs index 4ab9a4ce0ea..9e6593eb78b 100644 --- a/crates/iota-storage/src/http_key_value_store.rs +++ b/crates/iota-storage/src/http_key_value_store.rs @@ -296,7 +296,7 @@ impl HttpKVStore { let base_url = if base_url.ends_with('/') { base_url.to_string() } else { - format!("{}/", base_url) + format!("{base_url}/") }; let base_url = Url::parse(&base_url).into_iota_result()?; diff --git a/crates/iota-storage/src/indexes.rs b/crates/iota-storage/src/indexes.rs index bef5f1c2990..06beabd9cad 100644 --- a/crates/iota-storage/src/indexes.rs +++ b/crates/iota-storage/src/indexes.rs @@ -363,8 +363,7 @@ impl IndexStore { let object = input_coins.get(obj_id).or(written_coins.get(obj_id))?; let coin_type_tag = object.coin_type_maybe().unwrap_or_else(|| { panic!( - "object_id: {:?} is not a coin type, input_coins: {:?}, written_coins: {:?}, tx_digest: {:?}", - obj_id, input_coins, written_coins, digest + "object_id: {obj_id:?} is not a coin type, input_coins: {input_coins:?}, written_coins: {written_coins:?}, tx_digest: {digest:?}" ) }); let map = balance_changes.entry(*owner).or_default(); @@ -401,14 +400,12 @@ impl IndexStore { let obj = written_coins.get(obj_id)?; let coin_type_tag = obj.coin_type_maybe().unwrap_or_else(|| { panic!( - "object_id: {:?} in written_coins is not a coin type, written_coins: {:?}, tx_digest: {:?}", - obj_id, written_coins, digest + "object_id: {obj_id:?} in written_coins is not a coin type, written_coins: {written_coins:?}, tx_digest: {digest:?}" ) }); let coin = obj.as_coin_maybe().unwrap_or_else(|| { panic!( - "object_id: {:?} in written_coins cannot be deserialized as a Coin, written_coins: {:?}, tx_digest: {:?}", - obj_id, written_coins, digest + "object_id: {obj_id:?} in written_coins cannot be deserialized as a Coin, written_coins: {written_coins:?}, tx_digest: {digest:?}" ) }); let map = balance_changes.entry(*owner).or_default(); @@ -697,7 +694,7 @@ impl IndexStore { // NOTE: filter via checkpoint sequence number is implemented in // `get_transactions` of authority.rs. Some(_) => Err(IotaError::UserInput { - error: UserInputError::Unsupported(format!("{:?}", filter)), + error: UserInputError::Unsupported(format!("{filter:?}")), }), None => { let iter = self.tables.transaction_order.unbounded_iter(); @@ -1355,7 +1352,7 @@ impl IndexStore { }) .await .unwrap() - .map_err(|e| IotaError::Execution(format!("Failed to read balance frm DB: {:?}", e))); + .map_err(|e| IotaError::Execution(format!("Failed to read balance frm DB: {e:?}"))); } self.metrics.balance_lookup_from_total.inc(); @@ -1392,7 +1389,7 @@ impl IndexStore { .await .unwrap() .map_err(|e| { - IotaError::Execution(format!("Failed to read balance frm DB: {:?}", e)) + IotaError::Execution(format!("Failed to read balance frm DB: {e:?}")) }) }) .await @@ -1418,7 +1415,7 @@ impl IndexStore { .await .unwrap() .map_err(|e| { - IotaError::Execution(format!("Failed to read all balance from DB: {:?}", e)) + IotaError::Execution(format!("Failed to read all balance from DB: {e:?}")) }); } @@ -1434,7 +1431,7 @@ impl IndexStore { .await .unwrap() .map_err(|e| { - IotaError::Execution(format!("Failed to read all balance from DB: {:?}", e)) + IotaError::Execution(format!("Failed to read all balance from DB: {e:?}")) }) }) .await @@ -1486,7 +1483,7 @@ impl IndexStore { coin_object_count += 1; } let coin_type = TypeTag::Struct(Box::new(parse_iota_struct_tag(&coin_type).map_err( - |e| IotaError::Execution(format!("Failed to parse event sender address: {:?}", e)), + |e| IotaError::Execution(format!("Failed to parse event sender address: {e:?}")), )?)); balances.insert( coin_type, diff --git a/crates/iota-storage/src/key_value_store.rs b/crates/iota-storage/src/key_value_store.rs index 6bf08e2a7d1..e0ec736222b 100644 --- a/crates/iota-storage/src/key_value_store.rs +++ b/crates/iota-storage/src/key_value_store.rs @@ -313,7 +313,7 @@ impl TransactionKeyValueStore { .next() .flatten() .ok_or(IotaError::UserInput { - error: UserInputError::VerifiedCheckpointDigestNotFound(format!("{:?}", digest)), + error: UserInputError::VerifiedCheckpointDigestNotFound(format!("{digest:?}")), }) } diff --git a/crates/iota-storage/src/lib.rs b/crates/iota-storage/src/lib.rs index 90e54577718..a94a638e3e6 100644 --- a/crates/iota-storage/src/lib.rs +++ b/crates/iota-storage/src/lib.rs @@ -268,8 +268,7 @@ pub async fn verify_checkpoint_range( .expect("store operation should not fail") .unwrap_or_else(|| { panic!( - "Checkpoint {} should exist in store after summary sync but does not", - a + "Checkpoint {a} should exist in store after summary sync but does not" ); }); let next = store @@ -277,8 +276,7 @@ pub async fn verify_checkpoint_range( .expect("store operation should not fail") .unwrap_or_else(|| { panic!( - "Checkpoint {} should exist in store after summary sync but does not", - a + "Checkpoint {a} should exist in store after summary sync but does not" ); }); let committee = store diff --git a/crates/iota-storage/src/object_store/util.rs b/crates/iota-storage/src/object_store/util.rs index 159d6727758..24dbd6e916d 100644 --- a/crates/iota-storage/src/object_store/util.rs +++ b/crates/iota-storage/src/object_store/util.rs @@ -144,7 +144,7 @@ pub async fn copy_files( .try_for_each(|(path, ret)| { if let Some(progress_bar_clone) = &progress_bar_clone { progress_bar_clone.inc(1); - progress_bar_clone.set_message(format!("file: {}", path)); + progress_bar_clone.set_message(format!("file: {path}")); instant = Instant::now(); } futures::future::ready(ret) @@ -416,7 +416,7 @@ pub async fn write_snapshot_manifest( let bytes = Bytes::from(epoch_manifest.serialize_as_newline_delimited()); put( store, - &Path::from(format!("{}/{}", dir, MANIFEST_FILENAME)), + &Path::from(format!("{dir}/{MANIFEST_FILENAME}")), bytes, ) .await?; diff --git a/crates/iota-storage/src/package_object_cache.rs b/crates/iota-storage/src/package_object_cache.rs index edfd8e01e4e..11067ec6eab 100644 --- a/crates/iota-storage/src/package_object_cache.rs +++ b/crates/iota-storage/src/package_object_cache.rs @@ -41,8 +41,7 @@ impl PackageObjectCache { assert_eq!( store.get_object(package_id).unwrap().unwrap().digest(), p.object().digest(), - "Package object cache is inconsistent for package {:?}", - package_id + "Package object cache is inconsistent for package {package_id:?}" ) } return Ok(Some(p.clone())); diff --git a/crates/iota-swarm-config/src/node_config_builder.rs b/crates/iota-swarm-config/src/node_config_builder.rs index ffe63cb4b7b..4983aea8476 100644 --- a/crates/iota-swarm-config/src/node_config_builder.rs +++ b/crates/iota-swarm-config/src/node_config_builder.rs @@ -448,7 +448,7 @@ impl FullnodeConfigBuilder { let rpc_port = self .rpc_port .unwrap_or_else(|| local_ip_utils::get_available_port(&ip)); - format!("{}:{}", ip, rpc_port).parse().unwrap() + format!("{ip}:{rpc_port}").parse().unwrap() }); let checkpoint_executor_config = CheckpointExecutorConfig { diff --git a/crates/iota-swarm/src/memory/node.rs b/crates/iota-swarm/src/memory/node.rs index 72311fbe471..e47a498a32f 100644 --- a/crates/iota-swarm/src/memory/node.rs +++ b/crates/iota-swarm/src/memory/node.rs @@ -138,7 +138,7 @@ pub enum HealthCheckError { impl std::fmt::Display for HealthCheckError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/crates/iota-tls/src/verifier.rs b/crates/iota-tls/src/verifier.rs index 79489b8df19..db7a0e8e1ba 100644 --- a/crates/iota-tls/src/verifier.rs +++ b/crates/iota-tls/src/verifier.rs @@ -130,8 +130,7 @@ impl rustls::server::danger::ClientCertVerifier for ClientCertVerifi if !self.allower.allowed(&public_key) { return Err(rustls::Error::General(format!( - "invalid certificate: {:?} is not in the validator set", - public_key, + "invalid certificate: {public_key:?} is not in the validator set", ))); } @@ -211,8 +210,7 @@ impl rustls::client::danger::ServerCertVerifier for ServerCertVerifier { let public_key = public_key_from_certificate(end_entity)?; if public_key != self.public_key { return Err(rustls::Error::General(format!( - "invalid certificate: {:?} is not the expected server public key", - public_key, + "invalid certificate: {public_key:?} is not the expected server public key", ))); } diff --git a/crates/iota-tool/src/commands.rs b/crates/iota-tool/src/commands.rs index e84f0b90f20..2730a573d98 100644 --- a/crates/iota-tool/src/commands.rs +++ b/crates/iota-tool/src/commands.rs @@ -406,7 +406,7 @@ async fn check_locked_object( let output = get_object(id, None, None, clients.clone()).await?; let output = GroupedObjectOutput::new(output, committee); if output.fully_locked { - println!("Object {} is fully locked.", id); + println!("Object {id} is fully locked."); return Ok(()); } let top_record = output.voting_power.first().unwrap(); @@ -414,18 +414,17 @@ async fn check_locked_object( let top_record = top_record.0.unwrap(); if top_record.4.is_none() { println!( - "Object {} does not seem to be locked by majority of validators (unlocked stake: {})", - id, top_record_stake + "Object {id} does not seem to be locked by majority of validators (unlocked stake: {top_record_stake})" ); return Ok(()); } let tx_digest = top_record.2; if !rescue { - println!("Object {} is rescueable, top tx: {:?}", id, tx_digest); + println!("Object {id} is rescueable, top tx: {tx_digest:?}"); return Ok(()); } - println!("Object {} is rescueable, trying tx {}", id, tx_digest); + println!("Object {id} is rescueable, trying tx {tx_digest}"); let validator = output .grouped_results .get(&Some(top_record)) @@ -449,10 +448,10 @@ async fn check_locked_object( .await; match res { Ok(_) => { - println!("Transaction executed successfully ({:?})", tx_digest); + println!("Transaction executed successfully ({tx_digest:?})"); } Err(e) => { - println!("Failed to execute transaction ({:?}): {:?}", tx_digest, e); + println!("Failed to execute transaction ({tx_digest:?}): {e:?}"); } } Ok(()) @@ -594,7 +593,7 @@ impl ToolCommand { } ToolCommand::DumpGenesis { genesis } => { let genesis = Genesis::load(genesis)?; - println!("{:#?}", genesis); + println!("{genesis:#?}"); } ToolCommand::FetchCheckpoint { sequence_number, @@ -618,8 +617,8 @@ impl ToolCommand { contents, } = resp; println!("Validator: {:?}\n", name.concise()); - println!("Checkpoint: {:?}\n", checkpoint); - println!("Content: {:?}\n", contents); + println!("Checkpoint: {checkpoint:?}\n"); + println!("Content: {contents:?}\n"); } } ToolCommand::Anemo { args } => { @@ -853,8 +852,7 @@ impl ToolCommand { check_completed_snapshot(&snapshot_store_config, epoch_to_download).await { panic!( - "Aborting snapshot restore: {}, snapshot may not be uploaded yet", - e + "Aborting snapshot restore: {e}, snapshot may not be uploaded yet" ); } @@ -1010,8 +1008,7 @@ impl ToolCommand { check_completed_snapshot(&snapshot_store_config, epoch_to_download).await { panic!( - "Aborting snapshot restore: {}, snapshot may not be uploaded yet", - e + "Aborting snapshot restore: {e}, snapshot may not be uploaded yet" ); } download_db_snapshot( @@ -1080,7 +1077,7 @@ impl ToolCommand { let (agg, _) = AuthorityAggregatorBuilder::from_genesis(&genesis).build_network_clients(); let result = agg.process_transaction(transaction, None).await; - println!("{:?}", result); + println!("{result:?}"); } }; Ok(()) diff --git a/crates/iota-tool/src/db_tool/db_dump.rs b/crates/iota-tool/src/db_tool/db_dump.rs index c1ddfd489c8..5f476877689 100644 --- a/crates/iota-tool/src/db_tool/db_dump.rs +++ b/crates/iota-tool/src/db_tool/db_dump.rs @@ -46,7 +46,7 @@ pub enum StoreName { } impl std::fmt::Display for StoreName { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } @@ -163,7 +163,7 @@ pub fn print_table_metadata( table.add_row(row); } - eprintln!("{}", table); + eprintln!("{table}"); Ok(()) } @@ -346,7 +346,7 @@ mod test { let mut missing_tables = vec![]; for t in tables { - println!("{}", t); + println!("{t}"); if dump_table( StoreName::Validator, Some(0), diff --git a/crates/iota-tool/src/db_tool/index_search.rs b/crates/iota-tool/src/db_tool/index_search.rs index 70ee8693827..50e943790ce 100644 --- a/crates/iota-tool/src/db_tool/index_search.rs +++ b/crates/iota-tool/src/db_tool/index_search.rs @@ -47,7 +47,7 @@ pub fn search_index( termination: SearchRange, ) -> Result, anyhow::Error> { let start = start.as_str(); - println!("Opening db at {:?} ...", db_path); + println!("Opening db at {db_path:?} ..."); let db_read_only_handle = IndexStoreTables::get_read_only_handle(db_path, None, None, MetricConf::default()); match table_name.as_str() { @@ -203,7 +203,7 @@ where get_entries(db_map, start, termination).map(|entries| { entries .into_iter() - .map(|(k, v)| (format!("{:?}", k), format!("{:?}", v))) + .map(|(k, v)| (format!("{k:?}"), format!("{v:?}"))) .collect() }) } diff --git a/crates/iota-tool/src/db_tool/mod.rs b/crates/iota-tool/src/db_tool/mod.rs index 25864206dd6..19a0dbaee77 100644 --- a/crates/iota-tool/src/db_tool/mod.rs +++ b/crates/iota-tool/src/db_tool/mod.rs @@ -206,7 +206,7 @@ pub async fn execute_db_tool_command(db_path: PathBuf, cmd: DbToolCommand) -> an SearchRange::ExclusiveLastKey(rg.end_key), )?; for (k, v) in res { - println!("{}: {}", k, v); + println!("{k}: {v}"); } Ok(()) } @@ -218,7 +218,7 @@ pub async fn execute_db_tool_command(db_path: PathBuf, cmd: DbToolCommand) -> an SearchRange::Count(sc.count), )?; for (k, v) in res { - println!("{}: {}", k, v); + println!("{k}: {v}"); } Ok(()) } @@ -227,7 +227,7 @@ pub async fn execute_db_tool_command(db_path: PathBuf, cmd: DbToolCommand) -> an } pub fn print_db_all_tables(db_path: PathBuf) -> anyhow::Result<()> { - list_tables(db_path)?.iter().for_each(|t| println!("{}", t)); + list_tables(db_path)?.iter().for_each(|t| println!("{t}")); Ok(()) } @@ -235,8 +235,7 @@ pub fn print_db_duplicates_summary(db_path: PathBuf) -> anyhow::Result<()> { let (total_count, duplicate_count, total_bytes, duplicated_bytes) = duplicate_objects_summary(db_path); println!( - "Total objects = {}, duplicated objects = {}, total bytes = {}, duplicated bytes = {}", - total_count, duplicate_count, total_bytes, duplicated_bytes + "Total objects = {total_count}, duplicated objects = {duplicate_count}, total bytes = {total_bytes}, duplicated bytes = {duplicated_bytes}" ); Ok(()) } @@ -249,7 +248,7 @@ pub fn print_last_consensus_index(path: &Path) -> anyhow::Result<()> { None, ); let last_index = epoch_tables.get_last_consensus_index()?; - println!("Last consensus index is {:?}", last_index); + println!("Last consensus index is {last_index:?}"); Ok(()) } @@ -299,7 +298,7 @@ pub fn print_checkpoint(path: &Path, opt: PrintCheckpointOptions) -> anyhow::Res "Checkpoint digest {:?} not found in checkpoint store", opt.digest ))?; - println!("Checkpoint: {:?}", checkpoint); + println!("Checkpoint: {checkpoint:?}"); drop(checkpoint_store); print_checkpoint_content( path, @@ -320,7 +319,7 @@ pub fn print_checkpoint_content( "Checkpoint content digest {:?} not found in checkpoint store", opt.digest ))?; - println!("Checkpoint content: {:?}", contents); + println!("Checkpoint content: {contents:?}"); Ok(()) } @@ -469,7 +468,7 @@ pub fn print_all_entries( page_number: usize, ) -> anyhow::Result<()> { for (k, v) in dump_table(store, epoch, path, table_name, page_size, page_number)? { - println!("{:>100?}: {:?}", k, v); + println!("{k:>100?}: {v:?}"); } Ok(()) } diff --git a/crates/iota-tool/src/lib.rs b/crates/iota-tool/src/lib.rs index 3d7da969b57..c3ca813791b 100644 --- a/crates/iota-tool/src/lib.rs +++ b/crates/iota-tool/src/lib.rs @@ -143,7 +143,7 @@ where fn opt_debug(&self, def_str: &str) -> String { match self { None => def_str.to_string(), - Some(t) => format!("{:?}", t), + Some(t) => format!("{t:?}"), } } } @@ -283,7 +283,7 @@ impl std::fmt::Display for ConciseObjectOutput { let obj_digest = resp.object.compute_object_reference().2; let parent = resp.object.previous_transaction; let owner = resp.object.owner; - write!(f, " {:<66} {:<45} {:<51}", obj_digest, parent, owner)?; + write!(f, " {obj_digest:<66} {parent:<45} {owner:<51}")?; } } writeln!(f)?; @@ -308,7 +308,7 @@ impl std::fmt::Display for VerboseObjectOutput { )?; match resp { - Err(e) => writeln!(f, "Error fetching object: {}", e)?, + Err(e) => writeln!(f, "Error fetching object: {e}")?, Ok(resp) => { writeln!( f, @@ -429,19 +429,17 @@ pub async fn get_transaction_block( Ok(Some((tx, effects, effects_digest))) => { writeln!( &mut s, - "#{:<2} tx_digest: {:<68?} effects_digest: {:?}", - i, tx_digest, effects_digest, + "#{i:<2} tx_digest: {tx_digest:<68?} effects_digest: {effects_digest:?}", )?; - writeln!(&mut s, "{:#?}", effects)?; + writeln!(&mut s, "{effects:#?}")?; if show_input_tx { - writeln!(&mut s, "{:#?}", tx)?; + writeln!(&mut s, "{tx:#?}")?; } } Ok(None) => { writeln!( &mut s, - "#{:<2} tx_digest: {:<68?} Signed but not executed", - i, tx_digest + "#{i:<2} tx_digest: {tx_digest:<68?} Signed but not executed" )?; if show_input_tx { // In this case, we expect at least one validator knows about this tx @@ -450,11 +448,11 @@ pub async fn get_transaction_block( let tx_info = client.handle_transaction_info_request(TransactionInfoRequest { transaction_digest: tx_digest, }).await.unwrap_or_else(|e| panic!("Validator {:?} should have known about tx_digest: {:?}, got error: {:?}", validator_aware_of_tx.0, tx_digest, e)); - writeln!(&mut s, "{:#?}", tx_info)?; + writeln!(&mut s, "{tx_info:#?}")?; } } other => { - writeln!(&mut s, "#{:<2} {:#?}", i, other)?; + writeln!(&mut s, "#{i:<2} {other:#?}")?; } } for (j, (_, _, res)) in group.enumerate() { @@ -659,8 +657,7 @@ fn start_summary_sync( num_summaries as f64 / s_instant.elapsed().as_secs_f64(); cloned_progress_bar.set_position(s_start + num_summaries); cloned_progress_bar.set_message(format!( - "checkpoints synced per sec: {}", - total_checkpoints_per_sec + "checkpoints synced per sec: {total_checkpoints_per_sec}" )); tokio::time::sleep(Duration::from_secs(1)).await; } @@ -713,8 +710,7 @@ fn start_summary_sync( num_summaries as f64 / v_instant.elapsed().as_secs_f64(); cloned_verify_progress_bar.set_position(v_start + num_summaries); cloned_verify_progress_bar.set_message(format!( - "checkpoints verified per sec: {}", - total_checkpoints_per_sec + "checkpoints verified per sec: {total_checkpoints_per_sec}" )); tokio::time::sleep(Duration::from_secs(1)).await; } @@ -799,7 +795,7 @@ pub async fn check_completed_snapshot( snapshot_store_config: &ObjectStoreConfig, epoch: EpochId, ) -> Result<(), anyhow::Error> { - let success_marker = format!("epoch_{}/_SUCCESS", epoch); + let success_marker = format!("epoch_{epoch}/_SUCCESS"); let remote_object_store = if snapshot_store_config.no_sign_request { snapshot_store_config.make_http()? } else { @@ -834,8 +830,7 @@ pub async fn download_formal_snapshot( ) -> Result<(), anyhow::Error> { let m = MultiProgress::new(); m.println(format!( - "Beginning formal snapshot restore to end of epoch {}, network: {:?}, verification mode: {:?}", - epoch, network, verify, + "Beginning formal snapshot restore to end of epoch {epoch}, network: {network:?}, verification mode: {verify:?}", ))?; let path = path.join("staging").to_path_buf(); if path.exists() { @@ -896,11 +891,11 @@ pub async fn download_formal_snapshot( m_clone, ) .await - .unwrap_or_else(|err| panic!("Failed to create reader: {}", err)); + .unwrap_or_else(|err| panic!("Failed to create reader: {err}")); reader .read(&perpetual_db_clone, abort_registration, Some(sender)) .await - .unwrap_or_else(|err| panic!("Failed during read: {}", err)); + .unwrap_or_else(|err| panic!("Failed during read: {err}")); Ok::<(), anyhow::Error>(()) }); let mut root_accumulator = Accumulator::default(); @@ -998,8 +993,7 @@ pub async fn download_formal_snapshot( fs::rename(&path, &new_path)?; fs::remove_dir_all(snapshot_dir.clone())?; println!( - "Successfully restored state from snapshot at end of epoch {}", - epoch + "Successfully restored state from snapshot at end of epoch {epoch}" ); Ok(()) @@ -1030,7 +1024,7 @@ pub async fn download_db_snapshot( )); } - let epoch_path = format!("epoch_{}", epoch); + let epoch_path = format!("epoch_{epoch}"); let epoch_dir = get_path(&epoch_path); let manifest_file = epoch_dir.child(MANIFEST_FILENAME); @@ -1074,7 +1068,7 @@ pub async fn download_db_snapshot( let counter_cloned = file_counter.clone(); async move { counter_cloned.fetch_add(1, Ordering::Relaxed); - let file_path = get_path(format!("epoch_{}/{}", epoch, file).as_str()); + let file_path = get_path(format!("epoch_{epoch}/{file}").as_str()); copy_file(&file_path, &file_path, &remote_store, &local_store).await?; Ok::<::object_store::path::Path, anyhow::Error>(file_path.clone()) } diff --git a/crates/iota-transaction-checks/src/lib.rs b/crates/iota-transaction-checks/src/lib.rs index f8388da3228..8d63f7b51ba 100644 --- a/crates/iota-transaction-checks/src/lib.rs +++ b/crates/iota-transaction-checks/src/lib.rs @@ -165,8 +165,7 @@ mod checked { kind.validity_check(config)?; if kind.is_system_tx() { return Err(UserInputError::Unsupported(format!( - "Transaction kind {} is not supported in dev-inspect", - kind + "Transaction kind {kind} is not supported in dev-inspect" )) .into()); } @@ -483,8 +482,7 @@ mod checked { owner == &actual_owner, UserInputError::IncorrectUserSignature { error: format!( - "Object {:?} is owned by account address {:?}, but given owner/signer address is {:?}", - object_id, actual_owner, owner + "Object {object_id:?} is owned by account address {actual_owner:?}, but given owner/signer address is {owner:?}" ), } ); diff --git a/crates/iota-transactional-test-runner/src/lib.rs b/crates/iota-transactional-test-runner/src/lib.rs index a32d53e58d0..aa32e065291 100644 --- a/crates/iota-transactional-test-runner/src/lib.rs +++ b/crates/iota-transactional-test-runner/src/lib.rs @@ -256,8 +256,7 @@ impl TransactionalAdapter for ValidatorWithFullnode { .get_system_state() .map_err(|e| { IotaError::IotaSystemStateRead(format!( - "Failed to get system state from fullnode: {}", - e + "Failed to get system state from fullnode: {e}" )) })? .into_iota_system_state_summary(); diff --git a/crates/iota-transactional-test-runner/src/test_adapter.rs b/crates/iota-transactional-test-runner/src/test_adapter.rs index 370bbccd531..337f64df474 100644 --- a/crates/iota-transactional-test-runner/src/test_adapter.rs +++ b/crates/iota-transactional-test-runner/src/test_adapter.rs @@ -429,7 +429,7 @@ impl MoveTestAdapter<'_> for IotaTestAdapter { if !output.is_empty() { output.push_str(", ") } - write!(output, "{}: object({})", account, fake).unwrap() + write!(output, "{account}: object({fake})").unwrap() } for object_id in object_ids { test_adapter.enumerate_fake(object_id); @@ -521,9 +521,8 @@ impl MoveTestAdapter<'_> for IotaTestAdapter { .insert(named_addr.to_string(), package_addr); match prev_package.map(|a| a.into_inner()) { Some(addr) if addr != AccountAddress::ZERO => panic!( - "Cannot reuse named address '{}' for multiple packages. \ - It should be set to 0 initially", - named_addr + "Cannot reuse named address '{named_addr}' for multiple packages. \ + It should be set to 0 initially" ), _ => (), } @@ -666,7 +665,7 @@ impl MoveTestAdapter<'_> for IotaTestAdapter { self.executor.create_checkpoint().await?; } let latest_chk = self.executor.get_latest_checkpoint_sequence_number()?; - Ok(Some(format!("Checkpoint created: {}", latest_chk))) + Ok(Some(format!("Checkpoint created: {latest_chk}"))) } IotaSubcommand::AdvanceEpoch(AdvanceEpochCommand { count }) => { for _ in 0..count.unwrap_or(1) { @@ -726,9 +725,9 @@ impl MoveTestAdapter<'_> for IotaTestAdapter { .join(", "); assert!(!modules.is_empty()); if num_modules > 1 { - format!("{}::{{{}}}", fake_id, modules) + format!("{fake_id}::{{{modules}}}") } else { - format!("{}::{}", fake_id, modules) + format!("{fake_id}::{modules}") } } })) @@ -744,7 +743,7 @@ impl MoveTestAdapter<'_> for IotaTestAdapter { let obj_arg = IotaValue::Object(fake_id, None).into_argument(&mut builder, self)?; let recipient = match self.accounts.get(&recipient) { Some(test_account) => test_account.address, - None => panic!("Unbound account {}", recipient), + None => panic!("Unbound account {recipient}"), }; let gas_budget = gas_budget.unwrap_or(DEFAULT_GAS_BUDGET); let gas_price: u64 = gas_price.unwrap_or(self.gas_price); @@ -1195,7 +1194,7 @@ impl MoveTestAdapter<'_> for IotaTestAdapter { let mut err = error.to_string(); for (name, account) in &self.accounts { let addr = account.address.to_string(); - let replace = format!("@{}", name); + let replace = format!("@{name}"); err = err.replace(&addr, &replace); // Also match without 0x since different error messages may use different // format. @@ -1203,7 +1202,7 @@ impl MoveTestAdapter<'_> for IotaTestAdapter { } for (id, fake_id) in &self.object_enumeration { let id = id.to_string(); - let replace = format!("object({})", fake_id); + let replace = format!("object({fake_id})"); err = err.replace(&id, &replace); // Also match without 0x since different error messages may use different // format. @@ -1253,7 +1252,7 @@ impl IotaTestAdapter { .compiled_state .named_address_mapping .iter() - .map(|(name, addr)| (name.clone(), format!("{:#02x}", addr))); + .map(|(name, addr)| (name.clone(), format!("{addr:#02x}"))); for (name, addr) in named_addrs { let addr = addr.to_string(); @@ -1286,8 +1285,7 @@ impl IotaTestAdapter { let obj_id = objects_mapping.get(&obj_lookup).unwrap_or_else(|| { panic!( - "Unknown object lookup: {}\nAllowed variable mappings are {:#?}", - obj_lookup, variables + "Unknown object lookup: {obj_lookup}\nAllowed variable mappings are {variables:#?}" ) }); @@ -1347,7 +1345,7 @@ impl IotaTestAdapter { )); }; - let pattern = format!("@{{{}}}", var_name); + let pattern = format!("@{{{var_name}}}"); interpolated_query = interpolated_query.replace(&pattern, value); } @@ -1432,9 +1430,8 @@ impl IotaTestAdapter { .insert(new_package_name.to_string(), package_addr); match prev_package.map(|a| a.into_inner()) { Some(addr) if addr != AccountAddress::ZERO => panic!( - "Cannot reuse named address '{}' for multiple packages. \ - It should be set to 0 initially", - new_package_name + "Cannot reuse named address '{new_package_name}' for multiple packages. \ + It should be set to 0 initially" ), _ => (), } @@ -1505,7 +1502,7 @@ impl IotaTestAdapter { match sender { Some(n) => match self.accounts.get(&n) { Some(test_account) => test_account, - None => panic!("Unbound account {}", n), + None => panic!("Unbound account {n}"), }, None => &self.default_account, } @@ -1870,7 +1867,7 @@ impl IotaTestAdapter { .unwrap(); } out.push('\n'); - write!(out, "gas summary: {}", gas_summary).unwrap(); + write!(out, "gas summary: {gas_summary}").unwrap(); if out.is_empty() { None } else { Some(out) } } @@ -1881,7 +1878,7 @@ impl IotaTestAdapter { } events .iter() - .map(|event| self.stabilize_str(format!("{:?}", event))) + .map(|event| self.stabilize_str(format!("{event:?}"))) .collect::>() .join(", ") } @@ -1897,7 +1894,7 @@ impl IotaTestAdapter { let id: AccountAddress = id.into(); format!("0x{id:x}") } - Some(fake) => format!("object({})", fake), + Some(fake) => format!("object({fake})"), }) .collect::>() .join(", ") @@ -1948,7 +1945,7 @@ impl IotaTestAdapter { let hex_str = if hex_str.starts_with("0x") { hex_str } else { - format!("0x{}", hex_str) + format!("0x{hex_str}") }; let parsed = AccountAddress::from_hex_literal(&hex_str).unwrap(); if let Some((known, _)) = self @@ -1965,7 +1962,7 @@ impl IotaTestAdapter { let id: AccountAddress = id.into(); format!("0x{id:x}") } - Some(fake) => format!("fake({})", fake), + Some(fake) => format!("fake({fake})"), } } @@ -2007,7 +2004,7 @@ impl<'a> GetModule for &'a IotaTestAdapter { self.compiled_state .dep_modules() .find(|m| &m.self_id() == id) - .unwrap_or_else(|| panic!("Internal error: Unbound module {}", id)), + .unwrap_or_else(|| panic!("Internal error: Unbound module {id}")), )) } } @@ -2017,9 +2014,9 @@ impl fmt::Display for FakeID { match self { FakeID::Known(id) => { let addr: AccountAddress = (*id).into(); - write!(f, "0x{:x}", addr) + write!(f, "0x{addr:x}") } - FakeID::Enumerated(task, i) => write!(f, "{},{}", task, i), + FakeID::Enumerated(task, i) => write!(f, "{task},{i}"), } } } @@ -2407,8 +2404,7 @@ async fn update_named_address_mapping( || name == "iota" { panic!( - "Invalid init. The named address '{}' is reserved or duplicated", - name + "Invalid init. The named address '{name}' is reserved or duplicated" ) } named_address_mapping.insert(name, addr); diff --git a/crates/iota-types/src/base_types.rs b/crates/iota-types/src/base_types.rs index c77b3b52c8f..adad75b4339 100644 --- a/crates/iota-types/src/base_types.rs +++ b/crates/iota-types/src/base_types.rs @@ -1157,7 +1157,7 @@ impl SequenceNumber { } pub fn increment_to(&mut self, next: SequenceNumber) { - debug_assert!(*self < next, "Not an increment: {} to {}", self, next); + debug_assert!(*self < next, "Not an increment: {self} to {next}"); *self = next; } @@ -1167,7 +1167,7 @@ impl SequenceNumber { } pub fn decrement_to(&mut self, prev: SequenceNumber) { - debug_assert!(prev < *self, "Not a decrement: {} to {}", self, prev); + debug_assert!(prev < *self, "Not a decrement: {self} to {prev}"); *self = prev; } @@ -1487,8 +1487,8 @@ impl fmt::Display for MoveObjectType { impl fmt::Display for ObjectType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { match self { - ObjectType::Package => write!(f, "{}", PACKAGE), - ObjectType::Struct(t) => write!(f, "{}", t), + ObjectType::Package => write!(f, "{PACKAGE}"), + ObjectType::Struct(t) => write!(f, "{t}"), } } } diff --git a/crates/iota-types/src/bridge.rs b/crates/iota-types/src/bridge.rs index 193c82a2b94..244c51a87a6 100644 --- a/crates/iota-types/src/bridge.rs +++ b/crates/iota-types/src/bridge.rs @@ -202,15 +202,13 @@ pub fn get_bridge(object_store: &dyn ObjectStore) -> Result { let result: BridgeInnerV1 = get_dynamic_field_from_store(object_store, id, &version) .map_err(|err| { IotaError::IotaBridgeRead(format!( - "Failed to load bridge inner object with ID {:?} and version {:?}: {:?}", - id, version, err + "Failed to load bridge inner object with ID {id:?} and version {version:?}: {err:?}" )) })?; Ok(Bridge::V1(result)) } _ => Err(IotaError::IotaBridgeRead(format!( - "Unsupported IotaBridge version: {}", - version + "Unsupported IotaBridge version: {version}" ))), } } diff --git a/crates/iota-types/src/coin.rs b/crates/iota-types/src/coin.rs index e89a8ab2f5a..8daa0ee0513 100644 --- a/crates/iota-types/src/coin.rs +++ b/crates/iota-types/src/coin.rs @@ -151,7 +151,7 @@ impl TreasuryCap { /// Create a TreasuryCap from BCS bytes pub fn from_bcs_bytes(content: &[u8]) -> Result { bcs::from_bytes(content).map_err(|err| IotaError::ObjectDeserialization { - error: format!("Unable to deserialize TreasuryCap object: {}", err), + error: format!("Unable to deserialize TreasuryCap object: {err}"), }) } @@ -191,7 +191,7 @@ impl TryFrom for TreasuryCap { } Err(IotaError::Type { - error: format!("Object type is not a TreasuryCap: {:?}", object), + error: format!("Object type is not a TreasuryCap: {object:?}"), }) } } @@ -223,7 +223,7 @@ impl CoinMetadata { /// Create a coin from BCS bytes pub fn from_bcs_bytes(content: &[u8]) -> Result { bcs::from_bytes(content).map_err(|err| IotaError::ObjectDeserialization { - error: format!("Unable to deserialize CoinMetadata object: {}", err), + error: format!("Unable to deserialize CoinMetadata object: {err}"), }) } @@ -270,7 +270,7 @@ impl TryFrom<&Object> for CoinMetadata { } Err(IotaError::Type { - error: format!("Object type is not a CoinMetadata: {:?}", object), + error: format!("Object type is not a CoinMetadata: {object:?}"), }) } } diff --git a/crates/iota-types/src/crypto.rs b/crates/iota-types/src/crypto.rs index 8add7dae38d..1784e85ceca 100644 --- a/crates/iota-types/src/crypto.rs +++ b/crates/iota-types/src/crypto.rs @@ -434,7 +434,7 @@ pub struct AuthorityPublicKeyBytes( impl AuthorityPublicKeyBytes { fn fmt_impl(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { let s = Hex::encode(self.0); - write!(f, "k#{}", s)?; + write!(f, "k#{s}")?; Ok(()) } } @@ -462,7 +462,7 @@ pub struct ConciseAuthorityPublicKeyBytesRef<'a>(&'a AuthorityPublicKeyBytes); impl Debug for ConciseAuthorityPublicKeyBytesRef<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { let s = Hex::encode(self.0.0.get(0..4).ok_or(std::fmt::Error)?); - write!(f, "k#{}..", s) + write!(f, "k#{s}..") } } @@ -479,7 +479,7 @@ pub struct ConciseAuthorityPublicKeyBytes(AuthorityPublicKeyBytes); impl Debug for ConciseAuthorityPublicKeyBytes { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> { let s = Hex::encode(self.0.0.get(0..4).ok_or(std::fmt::Error)?); - write!(f, "k#{}..", s) + write!(f, "k#{s}..") } } @@ -1030,8 +1030,7 @@ impl IotaSignature for S { if author != address { return Err(IotaError::IncorrectSigner { error: format!( - "Incorrect signer, expected {:?}, got {:?}", - author, address + "Incorrect signer, expected {author:?}, got {address:?}" ), }); } @@ -1040,7 +1039,7 @@ impl IotaSignature for S { pk.verify(&digest, sig) .map_err(|e| IotaError::InvalidSignature { - error: format!("Fail to verify user sig {}", e), + error: format!("Fail to verify user sig {e}"), }) } } @@ -1498,7 +1497,7 @@ where fn write(&self, writer: &mut W) { let name = serde_name::trace_name::().expect("Self must be a struct or an enum"); // Note: This assumes that names never contain the separator `::`. - write!(writer, "{}::", name).expect("Hasher should not fail"); + write!(writer, "{name}::").expect("Hasher should not fail"); bcs::serialize_into(writer, &self).expect("Message serialization should not fail"); } } @@ -1519,7 +1518,7 @@ where fn from_signable_bytes(bytes: &[u8]) -> Result { // Remove name tag before deserialization using BCS let name = serde_name::trace_name::().expect("Self should be a struct or an enum"); - let name_byte_len = format!("{}::", name).bytes().len(); + let name_byte_len = format!("{name}::").bytes().len(); Ok(bcs::from_bytes(bytes.get(name_byte_len..).ok_or_else( || anyhow!("Failed to deserialize to {name}."), )?)?) @@ -1633,7 +1632,7 @@ impl<'a> VerificationObligation<'a> { } IotaError::InvalidSignature { - error: format!("Failed to batch verify aggregated auth sig: {}", e), + error: format!("Failed to batch verify aggregated auth sig: {e}"), } })?; Ok(()) diff --git a/crates/iota-types/src/digests.rs b/crates/iota-types/src/digests.rs index 62ed14f0362..761c588dcef 100644 --- a/crates/iota-types/src/digests.rs +++ b/crates/iota-types/src/digests.rs @@ -121,7 +121,7 @@ impl fmt::LowerHex for Digest { } for byte in self.0 { - write!(f, "{:02x}", byte)?; + write!(f, "{byte:02x}")?; } Ok(()) @@ -135,7 +135,7 @@ impl fmt::UpperHex for Digest { } for byte in self.0 { - write!(f, "{:02X}", byte)?; + write!(f, "{byte:02X}")?; } Ok(()) @@ -266,7 +266,7 @@ pub fn get_testnet_chain_identifier() -> ChainIdentifier { impl fmt::Display for ChainIdentifier { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for byte in self.0.0.0[0..4].iter() { - write!(f, "{:02x}", byte)?; + write!(f, "{byte:02x}")?; } Ok(()) diff --git a/crates/iota-types/src/dynamic_field.rs b/crates/iota-types/src/dynamic_field.rs index e4cb9b6b0cf..3733e89195a 100644 --- a/crates/iota-types/src/dynamic_field.rs +++ b/crates/iota-types/src/dynamic_field.rs @@ -321,8 +321,7 @@ where .map_err(|err| IotaError::DynamicFieldRead(err.to_string()))?; let object = object_store.get_object(&id)?.ok_or_else(|| { IotaError::DynamicFieldRead(format!( - "Dynamic field with key={:?} and ID={:?} not found on parent {:?}", - key, id, parent_id + "Dynamic field with key={key:?} and ID={id:?} not found on parent {parent_id:?}" )) })?; Ok(object) diff --git a/crates/iota-types/src/effects/effects_v1.rs b/crates/iota-types/src/effects/effects_v1.rs index 0046b2d0fb1..1740bc13272 100644 --- a/crates/iota-types/src/effects/effects_v1.rs +++ b/crates/iota-types/src/effects/effects_v1.rs @@ -565,7 +565,7 @@ impl TransactionEffectsV1 { assert_ne!(old_digest, new_digest); } _ => { - panic!("Impossible object change: {:?}, {:?}", id, change); + panic!("Impossible object change: {id:?}, {change:?}"); } } } @@ -576,9 +576,7 @@ impl TransactionEffectsV1 { for (id, _) in &self.unchanged_shared_objects { assert!( unique_ids.insert(*id), - "Duplicate object id: {:?}\n{:#?}", - id, - self + "Duplicate object id: {id:?}\n{self:#?}" ); } } diff --git a/crates/iota-types/src/error.rs b/crates/iota-types/src/error.rs index 8920af95568..33d0a191ca1 100644 --- a/crates/iota-types/src/error.rs +++ b/crates/iota-types/src/error.rs @@ -966,7 +966,7 @@ impl ExecutionError { impl std::fmt::Display for ExecutionError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "ExecutionError: {:?}", self) + write!(f, "ExecutionError: {self:?}") } } diff --git a/crates/iota-types/src/execution_status.rs b/crates/iota-types/src/execution_status.rs index 39a4571fb24..3ec761d5b14 100644 --- a/crates/iota-types/src/execution_status.rs +++ b/crates/iota-types/src/execution_status.rs @@ -34,7 +34,7 @@ pub struct CongestedObjects(pub Vec); impl fmt::Display for CongestedObjects { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { for obj in &self.0 { - write!(f, "{}, ", obj)?; + write!(f, "{obj}, ")?; } Ok(()) } @@ -355,7 +355,7 @@ impl ExecutionStatus { match self { ExecutionStatus::Success => {} ExecutionStatus::Failure { .. } => { - panic!("Unable to unwrap() on {:?}", self); + panic!("Unable to unwrap() on {self:?}"); } } } @@ -363,7 +363,7 @@ impl ExecutionStatus { pub fn unwrap_err(self) -> (ExecutionFailureStatus, Option) { match self { ExecutionStatus::Success => { - panic!("Unable to unwrap() on {:?}", self); + panic!("Unable to unwrap() on {self:?}"); } ExecutionStatus::Failure { error, command } => (error, command), } diff --git a/crates/iota-types/src/gas_coin.rs b/crates/iota-types/src/gas_coin.rs index 5c997dc459c..1c0b0a16e73 100644 --- a/crates/iota-types/src/gas_coin.rs +++ b/crates/iota-types/src/gas_coin.rs @@ -144,7 +144,7 @@ mod checked { let gas_coin: GasCoin = bcs::from_bytes(value.contents()).map_err(|err| { ExecutionError::new_with_source( ExecutionErrorKind::InvalidGasObject, - format!("Unable to deserialize gas object: {:?}", err), + format!("Unable to deserialize gas object: {err:?}"), ) })?; Ok(gas_coin) @@ -159,7 +159,7 @@ mod checked { Data::Move(obj) => obj.try_into(), Data::Package(_) => Err(ExecutionError::new_with_source( ExecutionErrorKind::InvalidGasObject, - format!("Gas object type is not a gas coin: {:?}", value), + format!("Gas object type is not a gas coin: {value:?}"), )), } } diff --git a/crates/iota-types/src/governance.rs b/crates/iota-types/src/governance.rs index 3383f0d7451..2173add142e 100644 --- a/crates/iota-types/src/governance.rs +++ b/crates/iota-types/src/governance.rs @@ -104,7 +104,7 @@ impl TryFrom<&Object> for StakedIota { Data::Move(o) => { if o.type_().is_staked_iota() { return bcs::from_bytes(o.contents()).map_err(|err| IotaError::Type { - error: format!("Unable to deserialize StakedIota object: {:?}", err), + error: format!("Unable to deserialize StakedIota object: {err:?}"), }); } } @@ -112,7 +112,7 @@ impl TryFrom<&Object> for StakedIota { } Err(IotaError::Type { - error: format!("Object type is not a StakedIota: {:?}", object), + error: format!("Object type is not a StakedIota: {object:?}"), }) } } diff --git a/crates/iota-types/src/iota_serde.rs b/crates/iota-types/src/iota_serde.rs index 0bf79037ce1..4bb81d63475 100644 --- a/crates/iota-types/src/iota_serde.rs +++ b/crates/iota-types/src/iota_serde.rs @@ -35,7 +35,7 @@ where E: Debug, D: Deserializer<'de>, { - Error::custom(format!("byte deserialization failed, cause by: {:?}", e)) + Error::custom(format!("byte deserialization failed, cause by: {e:?}")) } #[inline] @@ -44,7 +44,7 @@ where E: Debug, S: Serializer, { - S::Error::custom(format!("byte serialization failed, cause by: {:?}", e)) + S::Error::custom(format!("byte serialization failed, cause by: {e:?}")) } /// Use with serde_as to control serde for human-readable serialization and diff --git a/crates/iota-types/src/iota_system_state/iota_system_state_summary.rs b/crates/iota-types/src/iota_system_state/iota_system_state_summary.rs index 7f0178dd065..2c6567fe20b 100644 --- a/crates/iota-types/src/iota_system_state/iota_system_state_summary.rs +++ b/crates/iota-types/src/iota_system_state/iota_system_state_summary.rs @@ -900,8 +900,7 @@ where ) .map_err(|err| { IotaError::IotaSystemStateRead(format!( - "Failed to load candidate address from pool mappings: {:?}", - err + "Failed to load candidate address from pool mappings: {err:?}" )) })?; let candidate_table_id = system_state_summary.validator_candidates_id; @@ -948,8 +947,7 @@ where ) .map_err(|err| { IotaError::IotaSystemStateRead(format!( - "Failed to load candidate address from pool mappings: {:?}", - err + "Failed to load candidate address from pool mappings: {err:?}" )) })?; let candidate_table_id = system_state_summary.validator_candidates_id; diff --git a/crates/iota-types/src/iota_system_state/mod.rs b/crates/iota-types/src/iota_system_state/mod.rs index 6e12e465686..80d9b76ee63 100644 --- a/crates/iota-types/src/iota_system_state/mod.rs +++ b/crates/iota-types/src/iota_system_state/mod.rs @@ -339,8 +339,7 @@ where let field: Validator = get_dynamic_field_from_store(object_store, table_id, key).map_err(|err| { IotaError::IotaSystemStateRead(format!( - "Failed to load validator wrapper from table: {:?}", - err + "Failed to load validator wrapper from table: {err:?}" )) })?; let versioned = field.inner; @@ -351,8 +350,7 @@ where get_dynamic_field_from_store(object_store, versioned.id.id.bytes, &version) .map_err(|err| { IotaError::IotaSystemStateRead(format!( - "Failed to load inner validator from the wrapper: {:?}", - err + "Failed to load inner validator from the wrapper: {err:?}" )) })?; Ok(validator.into_iota_validator_summary()) @@ -382,8 +380,7 @@ where Ok(validator.into_iota_validator_summary()) } _ => Err(IotaError::IotaSystemStateRead(format!( - "Unsupported Validator version: {}", - version + "Unsupported Validator version: {version}" ))), } } @@ -402,8 +399,7 @@ where let validator: ValidatorType = get_dynamic_field_from_store(&object_store, table_id, &i) .map_err(|err| { IotaError::IotaSystemStateRead(format!( - "Failed to load validator from table: {:?}", - err + "Failed to load validator from table: {err:?}" )) })?; validators.push(validator); diff --git a/crates/iota-types/src/messages_consensus.rs b/crates/iota-types/src/messages_consensus.rs index 46def77b51f..e6792d65062 100644 --- a/crates/iota-types/src/messages_consensus.rs +++ b/crates/iota-types/src/messages_consensus.rs @@ -91,7 +91,7 @@ pub enum ConsensusTransactionKey { impl Debug for ConsensusTransactionKey { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - Self::Certificate(digest) => write!(f, "Certificate({:?})", digest), + Self::Certificate(digest) => write!(f, "Certificate({digest:?})"), Self::CheckpointSignature(name, seq) => { write!(f, "CheckpointSignature({:?}, {:?})", name.concise(), seq) } diff --git a/crates/iota-types/src/multisig.rs b/crates/iota-types/src/multisig.rs index 96889d78664..b46641d3a72 100644 --- a/crates/iota-types/src/multisig.rs +++ b/crates/iota-types/src/multisig.rs @@ -281,7 +281,7 @@ impl MultiSig { let index = multisig_pk .get_index(&pk) .ok_or(IotaError::IncorrectSigner { - error: format!("pk does not exist: {:?}", pk), + error: format!("pk does not exist: {pk:?}"), })?; if bitmap & (1 << index) != 0 { return Err(IotaError::InvalidSignature { diff --git a/crates/iota-types/src/object.rs b/crates/iota-types/src/object.rs index 50bbe4d5a77..70023b36ddf 100644 --- a/crates/iota-types/src/object.rs +++ b/crates/iota-types/src/object.rs @@ -529,10 +529,10 @@ impl Display for Owner { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::AddressOwner(address) => { - write!(f, "Account Address ( {} )", address) + write!(f, "Account Address ( {address} )") } Self::ObjectOwner(address) => { - write!(f, "Object ID: ( {} )", address) + write!(f, "Object ID: ( {address} )") } Self::Immutable => { write!(f, "Immutable") @@ -1106,13 +1106,13 @@ impl Display for ObjectRead { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Deleted(oref) => { - write!(f, "ObjectRead::Deleted ({:?})", oref) + write!(f, "ObjectRead::Deleted ({oref:?})") } Self::NotExists(id) => { - write!(f, "ObjectRead::NotExists ({:?})", id) + write!(f, "ObjectRead::NotExists ({id:?})") } Self::Exists(oref, _, _) => { - write!(f, "ObjectRead::Exists ({:?})", oref) + write!(f, "ObjectRead::Exists ({oref:?})") } } } @@ -1168,19 +1168,18 @@ impl Display for PastObjectRead { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::ObjectDeleted(oref) => { - write!(f, "PastObjectRead::ObjectDeleted ({:?})", oref) + write!(f, "PastObjectRead::ObjectDeleted ({oref:?})") } Self::ObjectNotExists(id) => { - write!(f, "PastObjectRead::ObjectNotExists ({:?})", id) + write!(f, "PastObjectRead::ObjectNotExists ({id:?})") } Self::VersionFound(oref, _, _) => { - write!(f, "PastObjectRead::VersionFound ({:?})", oref) + write!(f, "PastObjectRead::VersionFound ({oref:?})") } Self::VersionNotFound(object_id, version) => { write!( f, - "PastObjectRead::VersionNotFound ({:?}, asked sequence number {:?})", - object_id, version + "PastObjectRead::VersionNotFound ({object_id:?}, asked sequence number {version:?})" ) } Self::VersionTooHigh { @@ -1190,8 +1189,7 @@ impl Display for PastObjectRead { } => { write!( f, - "PastObjectRead::VersionTooHigh ({:?}, asked sequence number {:?}, latest sequence number {:?})", - object_id, asked_version, latest_version + "PastObjectRead::VersionTooHigh ({object_id:?}, asked sequence number {asked_version:?}, latest sequence number {latest_version:?})" ) } } diff --git a/crates/iota-types/src/object/bounded_visitor.rs b/crates/iota-types/src/object/bounded_visitor.rs index fd1ce09a79d..71879c08ad2 100644 --- a/crates/iota-types/src/object/bounded_visitor.rs +++ b/crates/iota-types/src/object/bounded_visitor.rs @@ -432,7 +432,7 @@ pub(crate) mod tests { let mut values = vec![]; for i in 0..WIDTH { - idents.push(format!("f{}", i)); + idents.push(format!("f{i}")); } for (i, id) in idents.iter().enumerate() { diff --git a/crates/iota-types/src/stardust/output/alias.rs b/crates/iota-types/src/stardust/output/alias.rs index c24659f7774..ef4701b5552 100644 --- a/crates/iota-types/src/stardust/output/alias.rs +++ b/crates/iota-types/src/stardust/output/alias.rs @@ -206,7 +206,7 @@ impl AliasOutput { /// Create an `AliasOutput` from BCS bytes. pub fn from_bcs_bytes(content: &[u8]) -> Result { bcs::from_bytes(content).map_err(|err| IotaError::ObjectDeserialization { - error: format!("Unable to deserialize AliasOutput object: {:?}", err), + error: format!("Unable to deserialize AliasOutput object: {err:?}"), }) } @@ -230,7 +230,7 @@ impl TryFrom<&Object> for AliasOutput { } Err(IotaError::Type { - error: format!("Object type is not an AliasOutput: {:?}", object), + error: format!("Object type is not an AliasOutput: {object:?}"), }) } } diff --git a/crates/iota-types/src/stardust/output/basic.rs b/crates/iota-types/src/stardust/output/basic.rs index 90039751e66..90c496102a8 100644 --- a/crates/iota-types/src/stardust/output/basic.rs +++ b/crates/iota-types/src/stardust/output/basic.rs @@ -186,7 +186,7 @@ impl BasicOutput { /// Create a `BasicOutput` from BCS bytes. pub fn from_bcs_bytes(content: &[u8]) -> Result { bcs::from_bytes(content).map_err(|err| IotaError::ObjectDeserialization { - error: format!("Unable to deserialize BasicOutput object: {:?}", err), + error: format!("Unable to deserialize BasicOutput object: {err:?}"), }) } @@ -238,7 +238,7 @@ impl TryFrom<&Object> for BasicOutput { } Err(IotaError::Type { - error: format!("Object type is not a BasicOutput: {:?}", object), + error: format!("Object type is not a BasicOutput: {object:?}"), }) } } diff --git a/crates/iota-types/src/stardust/output/nft.rs b/crates/iota-types/src/stardust/output/nft.rs index 0c73437d0cc..dedbe48af70 100644 --- a/crates/iota-types/src/stardust/output/nft.rs +++ b/crates/iota-types/src/stardust/output/nft.rs @@ -474,7 +474,7 @@ impl NftOutput { /// Create an `NftOutput` from BCS bytes. pub fn from_bcs_bytes(content: &[u8]) -> Result { bcs::from_bytes(content).map_err(|err| IotaError::ObjectDeserialization { - error: format!("Unable to deserialize NftOutput object: {:?}", err), + error: format!("Unable to deserialize NftOutput object: {err:?}"), }) } @@ -498,7 +498,7 @@ impl TryFrom<&Object> for NftOutput { } Err(IotaError::Type { - error: format!("Object type is not a NftOutput: {:?}", object), + error: format!("Object type is not a NftOutput: {object:?}"), }) } } diff --git a/crates/iota-types/src/storage/error.rs b/crates/iota-types/src/storage/error.rs index 75f4186611f..c1591425cf4 100644 --- a/crates/iota-types/src/storage/error.rs +++ b/crates/iota-types/src/storage/error.rs @@ -62,7 +62,7 @@ impl std::error::Error for Error { impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // TODO: change output based on kind? - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/crates/iota-types/src/timelock/timelock.rs b/crates/iota-types/src/timelock/timelock.rs index 71792182dc5..2eae4daaae5 100644 --- a/crates/iota-types/src/timelock/timelock.rs +++ b/crates/iota-types/src/timelock/timelock.rs @@ -211,7 +211,7 @@ where /// Create a `TimeLock` from BCS bytes. pub fn from_bcs_bytes(content: &'de [u8]) -> Result { bcs::from_bytes(content).map_err(|err| IotaError::ObjectDeserialization { - error: format!("Unable to deserialize TimeLock object: {:?}", err), + error: format!("Unable to deserialize TimeLock object: {err:?}"), }) } @@ -277,7 +277,7 @@ where } Err(IotaError::Type { - error: format!("Object type is not a TimeLock: {:?}", object), + error: format!("Object type is not a TimeLock: {object:?}"), }) } } diff --git a/crates/iota-types/src/timelock/timelocked_staked_iota.rs b/crates/iota-types/src/timelock/timelocked_staked_iota.rs index d67e658b34e..e2dac145c4a 100644 --- a/crates/iota-types/src/timelock/timelocked_staked_iota.rs +++ b/crates/iota-types/src/timelock/timelocked_staked_iota.rs @@ -94,8 +94,7 @@ impl TryFrom<&Object> for TimelockedStakedIota { if o.type_().is_timelocked_staked_iota() { return bcs::from_bytes(o.contents()).map_err(|err| IotaError::Type { error: format!( - "Unable to deserialize TimelockedStakedIota object: {:?}", - err + "Unable to deserialize TimelockedStakedIota object: {err:?}" ), }); } @@ -104,7 +103,7 @@ impl TryFrom<&Object> for TimelockedStakedIota { } Err(IotaError::Type { - error: format!("Object type is not a TimelockedStakedIota: {:?}", object), + error: format!("Object type is not a TimelockedStakedIota: {object:?}"), }) } } diff --git a/crates/iota-types/src/transaction.rs b/crates/iota-types/src/transaction.rs index 531440d129b..6000a28661e 100644 --- a/crates/iota-types/src/transaction.rs +++ b/crates/iota-types/src/transaction.rs @@ -1449,7 +1449,7 @@ impl Display for TransactionKind { writeln!(writer, "Transaction Kind : End of Epoch Transaction")?; } } - write!(f, "{}", writer) + write!(f, "{writer}") } } @@ -3194,7 +3194,7 @@ impl Display for CertifiedTransaction { self.auth_sig().signers_map )?; write!(writer, "{}", &self.data().intent_message().value.kind())?; - write!(f, "{}", writer) + write!(f, "{writer}") } } diff --git a/crates/iota-types/src/unit_tests/base_types_tests.rs b/crates/iota-types/src/unit_tests/base_types_tests.rs index 60ca8405c72..2a05d9aa7c6 100644 --- a/crates/iota-types/src/unit_tests/base_types_tests.rs +++ b/crates/iota-types/src/unit_tests/base_types_tests.rs @@ -77,7 +77,7 @@ fn test_signatures_serde() { let s = Signature::new_secure(&IntentMessage::new(Intent::iota_transaction(), foo), &sec1); let serialized = bcs::to_bytes(&s).unwrap(); - println!("{:?}", serialized); + println!("{serialized:?}"); let deserialized: Signature = bcs::from_bytes(&serialized).unwrap(); assert_eq!(deserialized.as_ref(), s.as_ref()); } @@ -121,7 +121,7 @@ fn test_object_id_conversions() {} #[test] fn test_object_id_display() { let id = ObjectID::from_str(SAMPLE_ADDRESS).unwrap(); - assert_eq!(format!("{:?}", id), SAMPLE_ADDRESS); + assert_eq!(format!("{id:?}"), SAMPLE_ADDRESS); } #[test] @@ -187,7 +187,7 @@ fn test_object_id_deserialize_from_json_value() { #[test] fn test_object_id_serde_json() { - let json_hex = format!("\"{}\"", SAMPLE_ADDRESS); + let json_hex = format!("\"{SAMPLE_ADDRESS}\""); let obj_id = ObjectID::from_hex_literal(SAMPLE_ADDRESS).unwrap(); @@ -214,7 +214,7 @@ fn test_object_id_serde_with_expected_value() { let json_serialized = serde_json::to_string(&object_id).unwrap(); let bcs_serialized = bcs::to_bytes(&object_id).unwrap(); - let expected_json_address = format!("\"{}\"", SAMPLE_ADDRESS); + let expected_json_address = format!("\"{SAMPLE_ADDRESS}\""); assert_eq!(expected_json_address, json_serialized); assert_eq!(object_id_vec, bcs_serialized); } @@ -227,9 +227,9 @@ fn test_object_id_zero_padding() { let obj_id_1 = ObjectID::from_str(hex).unwrap(); let obj_id_2 = ObjectID::from_str(long_hex).unwrap(); let obj_id_3 = ObjectID::from_str(long_hex_alt).unwrap(); - let obj_id_4: ObjectID = serde_json::from_str(&format!("\"{}\"", hex)).unwrap(); - let obj_id_5: ObjectID = serde_json::from_str(&format!("\"{}\"", long_hex)).unwrap(); - let obj_id_6: ObjectID = serde_json::from_str(&format!("\"{}\"", long_hex_alt)).unwrap(); + let obj_id_4: ObjectID = serde_json::from_str(&format!("\"{hex}\"")).unwrap(); + let obj_id_5: ObjectID = serde_json::from_str(&format!("\"{long_hex}\"")).unwrap(); + let obj_id_6: ObjectID = serde_json::from_str(&format!("\"{long_hex_alt}\"")).unwrap(); assert_eq!(IOTA_FRAMEWORK_ADDRESS, obj_id_1.0); assert_eq!(IOTA_FRAMEWORK_ADDRESS, obj_id_2.0); assert_eq!(IOTA_FRAMEWORK_ADDRESS, obj_id_3.0); @@ -241,7 +241,7 @@ fn test_object_id_zero_padding() { #[test] fn test_address_display() { let id = IotaAddress::from_str(SAMPLE_ADDRESS).unwrap(); - assert_eq!(format!("{:?}", id), SAMPLE_ADDRESS); + assert_eq!(format!("{id:?}"), SAMPLE_ADDRESS); } #[test] @@ -271,7 +271,7 @@ fn test_address_serde_with_expected_value() { let json_serialized = serde_json::to_string(&address).unwrap(); let bcs_serialized = bcs::to_bytes(&address).unwrap(); - assert_eq!(format!("\"{}\"", SAMPLE_ADDRESS), json_serialized); + assert_eq!(format!("\"{SAMPLE_ADDRESS}\""), json_serialized); assert_eq!(SAMPLE_ADDRESS_VEC.to_vec(), bcs_serialized); } diff --git a/crates/iota-types/src/unit_tests/crypto_tests.rs b/crates/iota-types/src/unit_tests/crypto_tests.rs index 8094ba26906..be2ab3aa2b9 100644 --- a/crates/iota-types/src/unit_tests/crypto_tests.rs +++ b/crates/iota-types/src/unit_tests/crypto_tests.rs @@ -40,7 +40,7 @@ fn serde_round_trip_authority_quorum_sign_info() { signers_map: RoaringBitmap::new(), }; let ser = serde_json::to_string(&info).unwrap(); - println!("{}", ser); + println!("{ser}"); let schema = schemars::schema_for!(AuthorityQuorumSignInfo); println!("{}", serde_json::to_string_pretty(&schema).unwrap()); @@ -88,7 +88,7 @@ fn test_proof_of_possession() { let mut msg = vec![]; msg.extend_from_slice(kp.public().as_bytes()); msg.extend_from_slice(address.as_ref()); - println!("Address: {:?}", address); + println!("Address: {address:?}"); println!("Pubkey: {:?}", Hex::encode(kp.public().as_bytes())); println!("Proof of possession: {:?}", Hex::encode(&pop)); assert!(verify_proof_of_possession(&pop, kp.public(), address).is_ok()); diff --git a/crates/iota-types/src/unit_tests/messages_tests.rs b/crates/iota-types/src/unit_tests/messages_tests.rs index 995b3b31095..70ae43bcd95 100644 --- a/crates/iota-types/src/unit_tests/messages_tests.rs +++ b/crates/iota-types/src/unit_tests/messages_tests.rs @@ -1267,8 +1267,7 @@ fn test_unique_input_objects() { assert_eq!( input_objects.len(), input_objects_map.len(), - "Duplicates in {:?}", - input_objects + "Duplicates in {input_objects:?}" ); } diff --git a/crates/iota/src/clever_error_rendering.rs b/crates/iota/src/clever_error_rendering.rs index a631cc0ed42..a6b1018e0ad 100644 --- a/crates/iota/src/clever_error_rendering.rs +++ b/crates/iota/src/clever_error_rendering.rs @@ -192,7 +192,7 @@ mod tests { let parsed: Vec<_> = corpus.into_iter().map(|c| { let (address, module_name, function_name, instruction, abort_code, command_index) = parse_abort_status_string(c).unwrap(); - format!("original abort message: {}\n address: {}\n module_name: {}\n function_name: {}\n instruction: {}\n abort_code: {}\n command_index: {}", c, address, module_name, function_name, instruction, abort_code, command_index) + format!("original abort message: {c}\n address: {address}\n module_name: {module_name}\n function_name: {function_name}\n instruction: {instruction}\n abort_code: {abort_code}\n command_index: {command_index}") }).collect(); insta::assert_snapshot!(parsed.join("\n------\n")); } diff --git a/crates/iota/src/client_commands.rs b/crates/iota/src/client_commands.rs index 745bf614588..4b9ab9a21bd 100644 --- a/crates/iota/src/client_commands.rs +++ b/crates/iota/src/client_commands.rs @@ -929,7 +929,7 @@ impl IotaClientCommands { package_path .canonicalize() .map_err(|e| IotaError::ModulePublishFailure { - error: format!("Failed to canonicalize package path: {}", e), + error: format!("Failed to canonicalize package path: {e}"), })?; let build_config = resolve_lock_file_path(build_config, Some(&package_path))?; let previous_id = if let Some(ref chain_id) = chain_id { @@ -1056,7 +1056,7 @@ impl IotaClientCommands { package_path .canonicalize() .map_err(|e| IotaError::ModulePublishFailure { - error: format!("Failed to canonicalize package path: {}", e), + error: format!("Failed to canonicalize package path: {e}"), })?; let build_config = resolve_lock_file_path(build_config, Some(&package_path))?; let previous_id = if let Some(ref chain_id) = chain_id { @@ -2038,7 +2038,7 @@ impl Display for IotaClientCommandResult { let mut table = builder.build(); let style = TableStyle::rounded(); table.with(style); - write!(f, "{}", table)? + write!(f, "{table}")? } IotaClientCommandResult::Balance(coins, with_coins) => { if coins.is_empty() { @@ -2053,7 +2053,7 @@ impl Display for IotaClientCommandResult { TableStyle::modern().get_horizontal(), )])); table.with(tabled::settings::style::BorderSpanCorrection); - write!(f, "{}", table)?; + write!(f, "{table}")?; } IotaClientCommandResult::DynamicFieldQuery(df_refs) => { let df_refs = DynamicFieldOutput { @@ -2066,7 +2066,7 @@ impl Display for IotaClientCommandResult { let mut table = json_to_table(&json_obj); let style = TableStyle::rounded().horizontals([]); table.with(style); - write!(f, "{}", table)? + write!(f, "{table}")? } IotaClientCommandResult::Gas(gas_coins) => { let gas_coins = gas_coins @@ -2112,7 +2112,7 @@ impl Display for IotaClientCommandResult { ])); table.with(tabled::settings::style::BorderSpanCorrection); } - write!(f, "{}", table)?; + write!(f, "{table}")?; } IotaClientCommandResult::NewAddress(new_address) => { let mut builder = TableBuilder::default(); @@ -2158,7 +2158,7 @@ impl Display for IotaClientCommandResult { let json_obj = json!(&object); let mut table = json_to_table(&json_obj); table.with(TableStyle::rounded().horizontals([])); - writeln!(f, "{}", table)? + writeln!(f, "{table}")? } Err(e) => writeln!(f, "Internal error, cannot read the object: {e}")?, }, @@ -2172,14 +2172,14 @@ impl Display for IotaClientCommandResult { let json_obj = json!(objs); let mut table = json_to_table(&json_obj); table.with(TableStyle::rounded().horizontals([])); - writeln!(f, "{}", table)? + writeln!(f, "{table}")? } Err(e) => write!(f, "Internal error: {e}")?, } } } IotaClientCommandResult::TransactionBlock(response) => { - write!(writer, "{}", response)?; + write!(writer, "{response}")?; } IotaClientCommandResult::RawObject(raw_object_read) => { let raw_object = match raw_object_read.object() { @@ -2191,16 +2191,16 @@ impl Display for IotaClientCommandResult { let mut temp = String::new(); let mut bcs_bytes = 0usize; for m in &p.module_map { - temp.push_str(&format!("{:?}\n", m)); + temp.push_str(&format!("{m:?}\n")); bcs_bytes += m.1.len() } - format!("{}Number of bytes: {}", temp, bcs_bytes) + format!("{temp}Number of bytes: {bcs_bytes}") } None => "Bcs field is None".to_string().red().to_string(), }, Err(err) => format!("{err}").red().to_string(), }; - writeln!(writer, "{}", raw_object)?; + writeln!(writer, "{raw_object}")?; } IotaClientCommandResult::SerializedUnsignedTransaction(tx_data) => { writeln!( @@ -2220,14 +2220,14 @@ impl Display for IotaClientCommandResult { writeln!(writer, "Client state sync complete.")?; } IotaClientCommandResult::ChainIdentifier(ci) => { - writeln!(writer, "{}", ci)?; + writeln!(writer, "{ci}")?; } IotaClientCommandResult::Switch(response) => { - write!(writer, "{}", response)?; + write!(writer, "{response}")?; } IotaClientCommandResult::ActiveAddress(response) => { match response { - Some(r) => write!(writer, "{}", r)?, + Some(r) => write!(writer, "{r}")?, None => write!(writer, "None")?, }; } @@ -2251,7 +2251,7 @@ impl Display for IotaClientCommandResult { } let mut table = builder.build(); table.with(TableStyle::rounded()); - write!(f, "{}", table)? + write!(f, "{table}")? } IotaClientCommandResult::VerifySource => { writeln!(writer, "Source verification succeeded!")?; @@ -2343,7 +2343,7 @@ impl Display for IotaClientCommandResult { table.with(tabled::settings::style::BorderSpanCorrection); - writeln!(f, "{}", table)?; + writeln!(f, "{table}")?; } IotaClientCommandResult::NoOutput => {} IotaClientCommandResult::DryRun(response) => { @@ -2627,7 +2627,7 @@ impl Display for SwitchResponse { if let Some(env) = &self.env { writeln!(writer, "Active environment switched to [{env}]")?; } - write!(f, "{}", writer) + write!(f, "{writer}") } } @@ -3141,7 +3141,7 @@ pub(crate) fn parse_display_option(s: &str) -> Result, St Ok(option) => { options.insert(option); } - Err(_) => return Err(format!("Invalid display option: {}", part)), /* Return error if + Err(_) => return Err(format!("Invalid display option: {part}")), /* Return error if * invalid */ } } diff --git a/crates/iota/src/client_ptb/ast.rs b/crates/iota/src/client_ptb/ast.rs index 705cc2bae93..a5880fa9972 100644 --- a/crates/iota/src/client_ptb/ast.rs +++ b/crates/iota/src/client_ptb/ast.rs @@ -90,7 +90,7 @@ pub fn is_keyword(s: &str) -> bool { pub fn all_keywords() -> String { KEYWORDS[..KEYWORDS.len() - 1] .iter() - .map(|x| format!("'{}'", x)) + .map(|x| format!("'{x}'")) .collect::>() .join(", ") + &format!(", or '{}'", KEYWORDS[KEYWORDS.len() - 1]) @@ -345,9 +345,9 @@ impl fmt::Display for Argument { Argument::Gas => write!(f, "gas"), Argument::Identifier(i) => write!(f, "{i}"), Argument::VariableAccess(sp!(_, head), accesses) => { - write!(f, "{}", head)?; + write!(f, "{head}")?; for sp!(_, access) in accesses { - write!(f, ".{}", access)?; + write!(f, ".{access}")?; } Ok(()) } @@ -378,7 +378,7 @@ fn delimited_list( ) -> std::fmt::Result { let mut prefix = ""; for item in items { - write!(f, "{}{}", prefix, item)?; + write!(f, "{prefix}{item}")?; prefix = sep; } Ok(()) diff --git a/crates/iota/src/client_ptb/builder.rs b/crates/iota/src/client_ptb/builder.rs index c0cac137dd2..f70b2abf9a7 100644 --- a/crates/iota/src/client_ptb/builder.rs +++ b/crates/iota/src/client_ptb/builder.rs @@ -319,7 +319,7 @@ impl<'a> PTBBuilder<'a> { for (i, command_loc) in commands.iter().enumerate() { if i == 0 { warnings.push(PTBError { - message: format!("Variable '{}' first declared here", ident), + message: format!("Variable '{ident}' first declared here"), span: *command_loc, help: None, severity: Severity::Warning, @@ -1110,7 +1110,7 @@ pub fn to_ordinal_contraction(num: usize) -> String { _ => "th", }, }; - format!("{}{}", num, suffix) + format!("{num}{suffix}") } pub(crate) fn find_did_you_means<'a>( @@ -1157,9 +1157,9 @@ pub(crate) fn display_did_you_mean + std::fmt::Display>( let len = possibles.len(); for (i, possible) in possibles.into_iter().enumerate() { if i == len - 1 && len > 1 { - strs.push(format!("or '{}'", possible)); + strs.push(format!("or '{possible}'")); } else { - strs.push(format!("'{}'", possible)); + strs.push(format!("'{possible}'")); } } diff --git a/crates/iota/src/client_ptb/ptb.rs b/crates/iota/src/client_ptb/ptb.rs index 47e7c352b0e..d56e9f8a18e 100644 --- a/crates/iota/src/client_ptb/ptb.rs +++ b/crates/iota/src/client_ptb/ptb.rs @@ -102,7 +102,7 @@ impl PTB { let rendered = build_error_reports(&source_string, errors); eprintln!("Encountered error{suffix} when parsing PTB:"); for e in rendered.iter() { - eprintln!("{:?}", e); + eprintln!("{e:?}"); } anyhow::bail!("Could not build PTB due to previous error{suffix}"); } @@ -133,7 +133,7 @@ impl PTB { eprintln!("Warning{suffix} produced when building PTB:"); let rendered = build_error_reports(&source_string, warnings); for e in rendered.iter() { - eprintln!("{:?}", e); + eprintln!("{e:?}"); } } let ptb = match res { @@ -142,7 +142,7 @@ impl PTB { eprintln!("Encountered error{suffix} when building PTB:"); let rendered = build_error_reports(&source_string, errors); for e in rendered.iter() { - eprintln!("{:?}", e); + eprintln!("{e:?}"); } anyhow::bail!("Could not build PTB due to previous error{suffix}"); } diff --git a/crates/iota/src/displays/dev_inspect.rs b/crates/iota/src/displays/dev_inspect.rs index 3ddcdf3f0bc..2dfe986c259 100644 --- a/crates/iota/src/displays/dev_inspect.rs +++ b/crates/iota/src/displays/dev_inspect.rs @@ -13,7 +13,7 @@ impl Display for Pretty<'_, DevInspectResults> { let Pretty(response) = self; if let Some(error) = &response.error { - writeln!(f, "Dev inspect failed: {}", error)?; + writeln!(f, "Dev inspect failed: {error}")?; return Ok(()); } diff --git a/crates/iota/src/displays/dry_run_tx_block.rs b/crates/iota/src/displays/dry_run_tx_block.rs index 8f4f5d3d217..107729ed254 100644 --- a/crates/iota/src/displays/dry_run_tx_block.rs +++ b/crates/iota/src/displays/dry_run_tx_block.rs @@ -32,7 +32,7 @@ impl Display for Pretty<'_, DryRunTransactionBlockResponse> { 1, TableStyle::modern().get_horizontal(), )])); - writeln!(f, "{}", table)?; + writeln!(f, "{table}")?; writeln!(f, "{}", response.effects)?; write!(f, "{}", response.events)?; @@ -74,7 +74,7 @@ impl Display for Pretty<'_, DryRunTransactionBlockResponse> { 1, TableStyle::modern().get_horizontal(), )])); - writeln!(f, "{}", table)?; + writeln!(f, "{table}")?; } if response.balance_changes.is_empty() { writeln!(f, "╭─────────────────────────────╮")?; @@ -91,7 +91,7 @@ impl Display for Pretty<'_, DryRunTransactionBlockResponse> { 1, TableStyle::modern().get_horizontal(), )])); - writeln!(f, "{}", table)?; + writeln!(f, "{table}")?; } writeln!( f, diff --git a/crates/iota/src/displays/gas_cost_summary.rs b/crates/iota/src/displays/gas_cost_summary.rs index 7a0fea44fcf..59cfe2761ba 100644 --- a/crates/iota/src/displays/gas_cost_summary.rs +++ b/crates/iota/src/displays/gas_cost_summary.rs @@ -26,6 +26,6 @@ impl Display for Pretty<'_, GasCostSummary> { Storage Rebate: {storage_rebate}\n \ Non-refundable Storage Fee: {non_refundable_storage_fee}", ); - write!(f, "{}", output) + write!(f, "{output}") } } diff --git a/crates/iota/src/displays/ptb_preview.rs b/crates/iota/src/displays/ptb_preview.rs index c6454ee7b2e..d6512bddf46 100644 --- a/crates/iota/src/displays/ptb_preview.rs +++ b/crates/iota/src/displays/ptb_preview.rs @@ -56,6 +56,6 @@ impl Display for PTBPreview<'_> { ])); table.with(tabled::settings::style::BorderSpanCorrection); - write!(f, "{}", table) + write!(f, "{table}") } } diff --git a/crates/iota/src/displays/status.rs b/crates/iota/src/displays/status.rs index debe8ee3747..cb93b220c53 100644 --- a/crates/iota/src/displays/status.rs +++ b/crates/iota/src/displays/status.rs @@ -17,6 +17,6 @@ impl Display for Pretty<'_, IotaExecutionStatus> { Failure { error } => format!("failed due to {error}"), }; - write!(f, "{}", output) + write!(f, "{output}") } } diff --git a/crates/iota/src/displays/summary.rs b/crates/iota/src/displays/summary.rs index f886f2e2360..6a122dcc18f 100644 --- a/crates/iota/src/displays/summary.rs +++ b/crates/iota/src/displays/summary.rs @@ -30,6 +30,6 @@ impl Display for Pretty<'_, Summary> { 1, TableStyle::modern().get_horizontal(), )])); - write!(f, "{}", table) + write!(f, "{table}") } } diff --git a/crates/iota/src/fire_drill.rs b/crates/iota/src/fire_drill.rs index 1fc7ad3547f..d7bca30c49b 100644 --- a/crates/iota/src/fire_drill.rs +++ b/crates/iota/src/fire_drill.rs @@ -76,8 +76,7 @@ async fn run_metadata_rotation(metadata_rotation: MetadataRotation) -> anyhow::R let account_key = read_keypair_from_file(&account_key_path)?; let config: NodeConfig = PersistedConfig::read(&iota_node_config_path).map_err(|err| { err.context(format!( - "Cannot open IOTA Node Config file at {:?}", - iota_node_config_path + "Cannot open IOTA Node Config file at {iota_node_config_path:?}" )) })?; diff --git a/crates/iota/src/generate_genesis_checkpoint.rs b/crates/iota/src/generate_genesis_checkpoint.rs index 3f73081f419..ae6fe34de2e 100644 --- a/crates/iota/src/generate_genesis_checkpoint.rs +++ b/crates/iota/src/generate_genesis_checkpoint.rs @@ -26,7 +26,7 @@ async fn main() { let account_key: AccountKeyPair = get_key_pair_from_rng(&mut rand::rngs::OsRng).1; let network_key: NetworkKeyPair = get_key_pair_from_rng(&mut rand::rngs::OsRng).1; let validator = ValidatorInfo { - name: format!("Validator {}", i), + name: format!("Validator {i}"), authority_key: authority_key.public().into(), protocol_key: protocol_key.public().clone(), account_address: IotaAddress::from(account_key.public()), diff --git a/crates/iota/src/genesis_ceremony.rs b/crates/iota/src/genesis_ceremony.rs index 06d47d8a0c7..12e4667e4ba 100644 --- a/crates/iota/src/genesis_ceremony.rs +++ b/crates/iota/src/genesis_ceremony.rs @@ -256,7 +256,7 @@ pub async fn run(cmd: Ceremony) -> Result<()> { println!("{:- { - println!("Examine Objects (total: {})", total_objects); + println!("Examine Objects (total: {total_objects})"); examine_object( &owner_map, &validator_pool_id_map, @@ -310,7 +310,7 @@ fn examine_object( } Ok(name) if name == STR_TIMELOCKED_IOTA => { for timelocked in timelocked_iota_map.values() { - println!("{:#?}", timelocked); + println!("{timelocked:#?}"); } print_divider(STR_TIMELOCKED_IOTA); } @@ -326,19 +326,19 @@ fn examine_object( } Ok(name) if name == STR_ALIAS_OUTPUT_IOTA => { for alias_output in alias_output_iota_map.values() { - println!("{:#?}", alias_output); + println!("{alias_output:#?}"); } print_divider(STR_ALIAS_OUTPUT_IOTA); } Ok(name) if name == STR_BASIC_OUTPUT_IOTA => { for basic_output in basic_output_iota_map.values() { - println!("{:#?}", basic_output); + println!("{basic_output:#?}"); } print_divider(STR_BASIC_OUTPUT_IOTA); } Ok(name) if name == STR_NFT_OUTPUT_IOTA => { for nft_output in nft_output_iota_map.values() { - println!("{:#?}", nft_output); + println!("{nft_output:#?}"); } print_divider(STR_NFT_OUTPUT_IOTA); } @@ -359,7 +359,7 @@ fn examine_object( } Ok(name) if name == STR_COIN_METADATA => { for coin_metadata in coin_metadata_map.values() { - println!("{:#?}\n", coin_metadata); + println!("{coin_metadata:#?}\n"); } print_divider("CoinMetadata"); } @@ -390,12 +390,12 @@ fn examine_total_supply( } total_iota += amount_sum; if print { - println!("Owner {:?}", owner); + println!("Owner {owner:?}"); println!( "Total Amount of Iota/StakedIota Owned: {amount_sum} NANOS or {} IOTA:", amount_sum / NANOS_PER_IOTA ); - println!("{:#?}\n", coins); + println!("{coins:#?}\n"); } } // Always print this. @@ -416,7 +416,7 @@ fn examine_total_supply( fn display_validator(validator: &IotaValidatorGenesis) { let metadata = validator.verified_metadata(); println!("Validator name: {}", metadata.name); - println!("{:#?}", metadata); + println!("{metadata:#?}"); println!("Voting Power: {}", validator.voting_power); println!("Gas Price: {}", validator.gas_price); println!("Next Epoch Gas Price: {}", validator.next_epoch_gas_price); @@ -481,7 +481,7 @@ fn display_staked_iota( validator_pool_id_map: &BTreeMap, owner_map: &BTreeMap, ) { - println!("{:#?}", staked_iota); + println!("{staked_iota:#?}"); display_staked( &staked_iota.pool_id(), &staked_iota.id(), @@ -495,7 +495,7 @@ fn display_timelocked_staked_iota( validator_pool_id_map: &BTreeMap, owner_map: &BTreeMap, ) { - println!("{:#?}", timelocked_staked_iota); + println!("{timelocked_staked_iota:#?}"); display_staked( &timelocked_staked_iota.pool_id(), &timelocked_staked_iota.id(), diff --git a/crates/iota/src/iota_commands.rs b/crates/iota/src/iota_commands.rs index 4eaa8eff576..78da0cf1eb3 100644 --- a/crates/iota/src/iota_commands.rs +++ b/crates/iota/src/iota_commands.rs @@ -556,15 +556,13 @@ impl IotaCommand { let network_config: NetworkConfig = PersistedConfig::read(&network_config_path) .map_err(|err| { err.context(format!( - "Cannot open IOTA network config file at {:?}", - network_config_path + "Cannot open IOTA network config file at {network_config_path:?}" )) })?; let bridge_committee_config: BridgeCommitteeConfig = PersistedConfig::read(&bridge_committee_config_path).map_err(|err| { err.context(format!( - "Cannot open Bridge Committee config file at {:?}", - bridge_committee_config_path + "Cannot open Bridge Committee config file at {bridge_committee_config_path:?}" )) })?; @@ -573,7 +571,7 @@ impl IotaCommand { let mut context = WalletContext::new(&config_path, None, None)?; let rgp = context.get_reference_gas_price().await?; let rpc_url = context.active_env()?.rpc(); - println!("rpc_url: {}", rpc_url); + println!("rpc_url: {rpc_url}"); let iota_bridge_client = IotaBridgeClient::new(rpc_url).await?; let bridge_arg = iota_bridge_client .get_mutable_bridge_object_arg_must_succeed() @@ -774,8 +772,7 @@ async fn start( .. } = PersistedConfig::read(&network_config_path).map_err(|err| { err.context(format!( - "Cannot open IOTA network config file at {:?}", - network_config_path + "Cannot open IOTA network config file at {network_config_path:?}" )) })?; let genesis_path = config_path.join(IOTA_GENESIS_FILENAME); @@ -822,7 +819,7 @@ async fn start( info!("Cluster started"); // the indexer requires a fullnode url with protocol specified - let fullnode_url = format!("http://{}", fullnode_url); + let fullnode_url = format!("http://{fullnode_url}"); info!("Fullnode URL: {}", fullnode_url); #[cfg(feature = "indexer")] let pg_address = format!("postgres://{pg_user}:{pg_password}@{pg_host}:{pg_port}/{pg_db_name}"); @@ -998,7 +995,7 @@ async fn genesis( // up (if --force/-f option was specified or report an // error let dir = iota_config_dir.read_dir().map_err(|err| { - anyhow!(err).context(format!("Cannot open IOTA config dir {:?}", iota_config_dir)) + anyhow!(err).context(format!("Cannot open IOTA config dir {iota_config_dir:?}")) })?; let files = dir.collect::, _>>()?; @@ -1259,13 +1256,11 @@ fn prompt_for_environment( } else { if accept_defaults { print!( - "Creating config file [{:?}] with default (Testnet) Full node server and ed25519 key scheme.", - wallet_conf_path + "Creating config file [{wallet_conf_path:?}] with default (Testnet) Full node server and ed25519 key scheme." ); } else { print!( - "Config file [{:?}] doesn't exist, do you want to connect to an IOTA Full node server [y/N]?", - wallet_conf_path + "Config file [{wallet_conf_path:?}] doesn't exist, do you want to connect to an IOTA Full node server [y/N]?" ); } if accept_defaults || matches!(read_line(), Ok(line) if line.trim().to_lowercase() == "y") { diff --git a/crates/iota/src/key_identity.rs b/crates/iota/src/key_identity.rs index 9f3a8c0f6d6..a48ad8b524e 100644 --- a/crates/iota/src/key_identity.rs +++ b/crates/iota/src/key_identity.rs @@ -36,7 +36,7 @@ impl Display for KeyIdentity { KeyIdentity::Address(x) => x.to_string(), KeyIdentity::Alias(x) => x.to_string(), }; - write!(f, "{}", v) + write!(f, "{v}") } } diff --git a/crates/iota/src/keytool.rs b/crates/iota/src/keytool.rs index b633c217a31..ebe21089c74 100644 --- a/crates/iota/src/keytool.rs +++ b/crates/iota/src/keytool.rs @@ -515,7 +515,7 @@ impl KeyToolCommand { match res { Ok(()) => output.sig_verify_result = "OK".to_string(), - Err(e) => output.sig_verify_result = format!("{:?}", e), + Err(e) => output.sig_verify_result = format!("{e:?}"), }; }; @@ -719,8 +719,7 @@ impl KeyToolCommand { }) } Err(e) => CommandOutput::Error(format!( - "Failed to read keypair at path {:?}, err: {e}", - file + "Failed to read keypair at path {file:?}, err: {e}" )), }, } @@ -1231,7 +1230,7 @@ impl Display for CommandOutput { table.with(Rotate::Left); table.with(tabled::settings::Style::rounded().horizontals([])); table.with(Modify::new(Rows::new(0..)).with(Width::wrap(160).keep_words())); - write!(formatter, "{}", table) + write!(formatter, "{table}") } CommandOutput::UpdateAlias(update) => { write!( @@ -1246,7 +1245,7 @@ impl Display for CommandOutput { let style = tabled::settings::Style::rounded().horizontals([]); table.with(style); table.array_orientation(Orientation::Column); - write!(formatter, "{}", table) + write!(formatter, "{table}") } } } diff --git a/crates/iota/src/unit_tests/keytool_tests.rs b/crates/iota/src/unit_tests/keytool_tests.rs index 283a81688ae..25a35b01ad3 100644 --- a/crates/iota/src/unit_tests/keytool_tests.rs +++ b/crates/iota/src/unit_tests/keytool_tests.rs @@ -99,7 +99,7 @@ async fn test_read_write_keystore_with_flag() { // create Secp256k1 keypair let kp_secp = IotaKeyPair::Secp256k1(get_key_pair().1); let addr_secp: IotaAddress = (&kp_secp.public()).into(); - let fp_secp = dir.path().join(format!("{}.key", addr_secp)); + let fp_secp = dir.path().join(format!("{addr_secp}.key")); let fp_secp_2 = fp_secp.clone(); // write Secp256k1 keypair to file @@ -123,7 +123,7 @@ async fn test_read_write_keystore_with_flag() { // create Ed25519 keypair let kp_ed = IotaKeyPair::Ed25519(get_key_pair().1); let addr_ed: IotaAddress = (&kp_ed.public()).into(); - let fp_ed = dir.path().join(format!("{}.key", addr_ed)); + let fp_ed = dir.path().join(format!("{addr_ed}.key")); let fp_ed_2 = fp_ed.clone(); // write Ed25519 keypair to file diff --git a/crates/iota/src/unit_tests/upgrade_compatibility_tests.rs b/crates/iota/src/unit_tests/upgrade_compatibility_tests.rs index 2ad4030aa0b..cbcc021f90d 100644 --- a/crates/iota/src/unit_tests/upgrade_compatibility_tests.rs +++ b/crates/iota/src/unit_tests/upgrade_compatibility_tests.rs @@ -180,13 +180,13 @@ fn positional_formatting() { }; let ff = FormattedField::new(&field, &[]); - assert_eq!(format!("{}", ff), "'bool' at position 999"); + assert_eq!(format!("{ff}"), "'bool' at position 999"); } fn get_packages(name: &str) -> (Vec, CompiledPackage, PathBuf) { let mut path: PathBuf = PathBuf::from(env!("CARGO_MANIFEST_DIR")); path.push("src/unit_tests/fixtures/upgrade_errors/"); - path.push(format!("{}_v1", name)); + path.push(format!("{name}_v1")); let mods_v1 = BuildConfig::new_for_testing() .build(&path) @@ -195,7 +195,7 @@ fn get_packages(name: &str) -> (Vec, CompiledPackage, PathBuf) { let mut path: PathBuf = PathBuf::from(env!("CARGO_MANIFEST_DIR")); path.push("src/unit_tests/fixtures/upgrade_errors/"); - path.push(format!("{}_v2", name)); + path.push(format!("{name}_v2")); let pkg_v2 = BuildConfig::new_for_testing().build(&path).unwrap(); diff --git a/crates/iota/src/upgrade_compatibility/formatting.rs b/crates/iota/src/upgrade_compatibility/formatting.rs index cf18c9a1a06..d9f45b92a10 100644 --- a/crates/iota/src/upgrade_compatibility/formatting.rs +++ b/crates/iota/src/upgrade_compatibility/formatting.rs @@ -129,7 +129,7 @@ pub(super) fn format_param( .join(", ") ) } - _ => format!("{}", param), + _ => format!("{param}"), }) } @@ -146,7 +146,7 @@ pub(super) fn format_list( _ => { let all_but_last = &items[..items.len() - 1].join(", "); let last = items.last().expect("unexpected empty list"); - format!("{}, and {}", all_but_last, last) + format!("{all_but_last}, and {last}") } }; if let Some((singular, plural)) = noun_singular_plural { diff --git a/crates/iota/src/upgrade_compatibility/mod.rs b/crates/iota/src/upgrade_compatibility/mod.rs index 669154ae512..6e9edb50b03 100644 --- a/crates/iota/src/upgrade_compatibility/mod.rs +++ b/crates/iota/src/upgrade_compatibility/mod.rs @@ -1335,13 +1335,13 @@ fn function_signature_mismatch_diag( format_list( new_type_param .into_iter() - .map(|t| format!("'{:?}'", t).to_lowercase()), + .map(|t| format!("'{t:?}'").to_lowercase()), Some(("constraint", "constraints")) ), format_list( old_type_param .into_iter() - .map(|t| format!("'{:?}'", t).to_lowercase()), + .map(|t| format!("'{t:?}'").to_lowercase()), None ), ), @@ -1496,11 +1496,11 @@ fn ability_mismatch_label( let missing_abilities_list: Vec = missing_abilities .into_iter() - .map(|a| format!("'{:?}'", a).to_lowercase()) + .map(|a| format!("'{a:?}'").to_lowercase()) .collect(); let extra_abilities_list: Vec = extra_abilities .into_iter() - .map(|a| format!("'{:?}'", a).to_lowercase()) + .map(|a| format!("'{a:?}'").to_lowercase()) .collect(); match ( @@ -1554,7 +1554,7 @@ fn struct_ability_mismatch_diag( let old_abilities: Vec = old_struct .abilities .into_iter() - .map(|a| format!("'{:?}'", a).to_lowercase()) + .map(|a| format!("'{a:?}'").to_lowercase()) .collect(); diags.add(Diagnostic::new( @@ -1585,7 +1585,7 @@ fn struct_ability_mismatch_diag( old_struct .abilities .into_iter() - .map(|a| format!("'{:?}'", a).to_lowercase()), + .map(|a| format!("'{a:?}'").to_lowercase()), None ), ), @@ -1802,7 +1802,7 @@ fn enum_ability_mismatch_diag( let old_abilities: Vec = old_enum .abilities .into_iter() - .map(|a| format!("'{:?}'", a).to_lowercase()) + .map(|a| format!("'{a:?}'").to_lowercase()) .collect(); let reason = if public_visibility_related_error { @@ -1836,7 +1836,7 @@ fn enum_ability_mismatch_diag( old_enum .abilities .into_iter() - .map(|a| format!("'{:?}'", a).to_lowercase()), + .map(|a| format!("'{a:?}'").to_lowercase()), None ), ), @@ -2253,7 +2253,7 @@ fn function_new_diag( Declarations::NewDeclaration, ( def_loc, - format!("New unexpected function '{}'.", function_name), + format!("New unexpected function '{function_name}'."), ), Vec::<(Loc, String)>::new(), vec![ @@ -2493,8 +2493,7 @@ fn file_format_version_downgrade_diag( ( def_loc, format!( - "Downgrading from file format version {} to {} is not supported.", - old_version, new_version + "Downgrading from file format version {old_version} to {new_version} is not supported." ), ), Vec::<(Loc, String)>::new(), diff --git a/crates/iota/src/validator_commands.rs b/crates/iota/src/validator_commands.rs index acabc7c7d1c..6a83377cc73 100644 --- a/crates/iota/src/validator_commands.rs +++ b/crates/iota/src/validator_commands.rs @@ -223,24 +223,23 @@ fn make_key_files( key: Option, ) -> Result<()> { if file_name.exists() { - println!("Use existing {:?} key file.", file_name); + println!("Use existing {file_name:?} key file."); return Ok(()); } else if is_authority_key { let (_, keypair) = get_authority_key_pair(); write_authority_keypair_to_file(&keypair, file_name.clone())?; - println!("Generated new key file: {:?}.", file_name); + println!("Generated new key file: {file_name:?}."); } else { let kp = match key { Some(key) => { println!( - "Generated new key file {:?} based on iota.keystore file.", - file_name + "Generated new key file {file_name:?} based on iota.keystore file." ); key } None => { let (_, kp, _, _) = generate_new_key(SignatureScheme::ED25519, None, None)?; - println!("Generated new key file: {:?}.", file_name); + println!("Generated new key file: {file_name:?}."); kp } }; @@ -301,13 +300,11 @@ impl IotaValidatorCommand { gas_price: iota_config::node::DEFAULT_VALIDATOR_GAS_PRICE, commission_rate: iota_config::node::DEFAULT_COMMISSION_RATE, network_address: Multiaddr::try_from(format!( - "/dns/{}/tcp/8080/http", - host_name + "/dns/{host_name}/tcp/8080/http" ))?, - p2p_address: Multiaddr::try_from(format!("/dns/{}/udp/8084", host_name))?, + p2p_address: Multiaddr::try_from(format!("/dns/{host_name}/udp/8084"))?, primary_address: Multiaddr::try_from(format!( - "/dns/{}/udp/8081", - host_name + "/dns/{host_name}/udp/8081" ))?, description, image_url, @@ -320,8 +317,7 @@ impl IotaValidatorCommand { let validator_info_bytes = serde_yaml::to_string(&validator_info)?; fs::write(validator_info_file_name.clone(), validator_info_bytes)?; println!( - "Generated validator info file: {:?}.", - validator_info_file_name + "Generated validator info file: {validator_info_file_name:?}." ); IotaValidatorCommandResponse::MakeValidatorInfo } @@ -565,8 +561,7 @@ impl IotaValidatorCommand { bail!("Address {} is not in the committee", address); } println!( - "Updating bridge committee node URL for IOTA validator: {address}, url: {}", - bridge_authority_url + "Updating bridge committee node URL for IOTA validator: {address}, url: {bridge_authority_url}" ); let bridge = bridge_client @@ -735,7 +730,7 @@ async fn get_cap_object_ref( let owner = resp.owner().unwrap(); let cap_obj_ref = resp .object_ref_if_exists() - .unwrap_or_else(|| panic!("OperationCap {} shall exist.", cap_object_id)); + .unwrap_or_else(|| panic!("OperationCap {cap_object_id} shall exist.")); if owner != Owner::AddressOwner(context.active_address()?) { anyhow::bail!( "OperationCap {} is not owned by the sender address {} but {:?}", @@ -894,7 +889,7 @@ impl Display for IotaValidatorCommandResponse { write!(writer, "{}", write_transaction_response(response)?)?; } IotaValidatorCommandResponse::SerializedPayload(response) => { - write!(writer, "Serialized payload: {}", response)?; + write!(writer, "Serialized payload: {response}")?; } IotaValidatorCommandResponse::RegisterBridgeCommittee { execution_response, @@ -909,8 +904,7 @@ impl Display for IotaValidatorCommandResponse { } else { write!( writer, - "Serialized transaction for signing: {:?}", - serialized_unsigned_transaction + "Serialized transaction for signing: {serialized_unsigned_transaction:?}" )?; } } @@ -937,7 +931,7 @@ pub fn write_transaction_response( let mut writer = String::new(); for line in lines { let colorized_line = if success { line.green() } else { line.red() }; - writeln!(writer, "{}", colorized_line)?; + writeln!(writer, "{colorized_line}")?; } Ok(writer) } @@ -949,7 +943,7 @@ impl Debug for IotaValidatorCommandResponse { Ok(s) => s, Err(err) => format!("{err}").red().to_string(), }; - write!(f, "{}", s) + write!(f, "{s}") } } diff --git a/crates/iota/tests/cli_tests.rs b/crates/iota/tests/cli_tests.rs index c16a07004de..778081d5b2b 100644 --- a/crates/iota/tests/cli_tests.rs +++ b/crates/iota/tests/cli_tests.rs @@ -626,8 +626,7 @@ async fn test_move_call_args_linter_command() -> Result<(), anyhow::Error> { let package = if let IotaClientCommandResult::TransactionBlock(response) = resp { assert!( response.status_ok().unwrap(), - "Command failed: {:?}", - response + "Command failed: {response:?}" ); assert_eq!( response.effects.as_ref().unwrap().gas_object().object_id(), @@ -2330,8 +2329,7 @@ async fn test_native_transfer() -> Result<(), anyhow::Error> { let (mut_obj1, mut_obj2) = if let IotaClientCommandResult::TransactionBlock(response) = resp { assert!( response.status_ok().unwrap(), - "Command failed: {:?}", - response + "Command failed: {response:?}" ); assert_eq!( response.effects.as_ref().unwrap().gas_object().object_id(), @@ -2471,8 +2469,8 @@ fn test_bug_1078() { )); let mut writer = String::new(); // fmt ObjectRead should not fail. - write!(writer, "{}", read).unwrap(); - write!(writer, "{:?}", read).unwrap(); + write!(writer, "{read}").unwrap(); + write!(writer, "{read:?}").unwrap(); } #[sim_test] @@ -2752,7 +2750,7 @@ async fn test_merge_coin() -> Result<(), anyhow::Error> { .execute(context) .await?; let g = if let IotaClientCommandResult::TransactionBlock(r) = resp { - assert!(r.status_ok().unwrap(), "Command failed: {:?}", r); + assert!(r.status_ok().unwrap(), "Command failed: {r:?}"); assert_eq!(r.effects.as_ref().unwrap().gas_object().object_id(), gas); let object_id = r .effects @@ -2872,7 +2870,7 @@ async fn test_split_coin() -> Result<(), anyhow::Error> { .await?; let (updated_coin, new_coins) = if let IotaClientCommandResult::TransactionBlock(r) = resp { - assert!(r.status_ok().unwrap(), "Command failed: {:?}", r); + assert!(r.status_ok().unwrap(), "Command failed: {r:?}"); assert_eq!(r.effects.as_ref().unwrap().gas_object().object_id(), gas); let updated_object_id = r .effects @@ -2938,7 +2936,7 @@ async fn test_split_coin() -> Result<(), anyhow::Error> { .await?; let (updated_coin, new_coins) = if let IotaClientCommandResult::TransactionBlock(r) = resp { - assert!(r.status_ok().unwrap(), "Command failed: {:?}", r); + assert!(r.status_ok().unwrap(), "Command failed: {r:?}"); let updated_object_id = r .effects .as_ref() @@ -3006,7 +3004,7 @@ async fn test_split_coin() -> Result<(), anyhow::Error> { .await?; let (updated_coin, new_coins) = if let IotaClientCommandResult::TransactionBlock(r) = resp { - assert!(r.status_ok().unwrap(), "Command failed: {:?}", r); + assert!(r.status_ok().unwrap(), "Command failed: {r:?}"); let updated_object_id = r .effects .as_ref() @@ -3460,7 +3458,7 @@ fn assert_dry_run(dry_run: IotaClientCommandResult, object_id: ObjectID, command "{command} dry run test failed, gas object used is not the expected one" ); } else { - panic!("{} dry run failed", command); + panic!("{command} dry run failed"); } } diff --git a/crates/iota/tests/ptb_files_tests.rs b/crates/iota/tests/ptb_files_tests.rs index 9aa5bc604af..5905c53670e 100644 --- a/crates/iota/tests/ptb_files_tests.rs +++ b/crates/iota/tests/ptb_files_tests.rs @@ -43,7 +43,7 @@ async fn test_ptb_files(path: &Path) -> datatest_stable::Result<()> { let mut results = vec![]; results.push(" === ERRORS AFTER PARSING INPUT COMMANDS === ".to_string()); for e in rendered.iter() { - results.push(format!("{:?}", e)); + results.push(format!("{e:?}")); } insta::assert_snapshot!(fname(), results.join("\n")); return Ok(()); @@ -73,7 +73,7 @@ async fn test_ptb_files(path: &Path) -> datatest_stable::Result<()> { let rendered = build_error_reports(&file_contents, warnings); results.push(" === WARNINGS === ".to_string()); for warning in rendered.iter() { - results.push(format!("{:?}", warning)); + results.push(format!("{warning:?}")); } } @@ -83,7 +83,7 @@ async fn test_ptb_files(path: &Path) -> datatest_stable::Result<()> { results.push(format!("Input {}: {}", i, stable_call_arg_display(ca))); } for (i, c) in ptb.commands.iter().enumerate() { - results.push(format!("Command {}: {}", i, c)); + results.push(format!("Command {i}: {c}")); } } @@ -93,7 +93,7 @@ async fn test_ptb_files(path: &Path) -> datatest_stable::Result<()> { results.push(" === BUILDING PTB ERRORS === ".to_string()); for e in rendered.iter() { - results.push(format!("{:?}", e)); + results.push(format!("{e:?}")); } } @@ -106,11 +106,11 @@ async fn test_ptb_files(path: &Path) -> datatest_stable::Result<()> { #[cfg(not(msim))] fn stable_call_arg_display(ca: &CallArg) -> String { match ca { - CallArg::Pure(v) => format!("Pure({:?})", v), + CallArg::Pure(v) => format!("Pure({v:?})"), CallArg::Object(oa) => match oa { ObjectArg::ImmOrOwnedObject(_) => "ImmutableOrOwnedObject".to_string(), ObjectArg::SharedObject { mutable, .. } => { - format!("SharedObject(mutable: {})", mutable) + format!("SharedObject(mutable: {mutable})") } ObjectArg::Receiving(_) => "Receiving".to_string(), }, diff --git a/crates/simulacrum/src/lib.rs b/crates/simulacrum/src/lib.rs index 4912def04dd..4c17e222d1d 100644 --- a/crates/simulacrum/src/lib.rs +++ b/crates/simulacrum/src/lib.rs @@ -713,12 +713,12 @@ mod tests { let clock = chain.store().get_clock(); let start_time_ms = clock.timestamp_ms(); - println!("clock: {:#?}", clock); + println!("clock: {clock:#?}"); for _ in 0..steps { chain.advance_clock(Duration::from_millis(1)); chain.create_checkpoint(); let clock = chain.store().get_clock(); - println!("clock: {:#?}", clock); + println!("clock: {clock:#?}"); } let end_time_ms = chain.store().get_clock().timestamp_ms(); assert_eq!(end_time_ms - start_time_ms, steps); diff --git a/crates/telemetry-subscribers/src/bin/import-trace.rs b/crates/telemetry-subscribers/src/bin/import-trace.rs index 8ad9a0c36a9..5c202d144ce 100644 --- a/crates/telemetry-subscribers/src/bin/import-trace.rs +++ b/crates/telemetry-subscribers/src/bin/import-trace.rs @@ -40,7 +40,7 @@ async fn main() { if args.dump_spans { for message in messages.iter() { for span in &message.resource_spans { - println!("{:?}", span); + println!("{span:?}"); } } return; @@ -54,10 +54,10 @@ async fn main() { .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs(); - format!("iota-node-{}", timestamp) + format!("iota-node-{timestamp}") }); - println!("importing trace with service name {:?}", service_name); + println!("importing trace with service name {service_name:?}"); for mut message in messages { println!( @@ -110,7 +110,7 @@ where .ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "Buffer underflow"))?; let msg = M::decode(msg_bytes).map_err(|e| { - io::Error::new(io::ErrorKind::InvalidData, format!("Decode error: {}", e)) + io::Error::new(io::ErrorKind::InvalidData, format!("Decode error: {e}")) })?; messages.push(msg); diff --git a/crates/telemetry-subscribers/src/lib.rs b/crates/telemetry-subscribers/src/lib.rs index feae4a61dd0..19af2bb06ed 100644 --- a/crates/telemetry-subscribers/src/lib.rs +++ b/crates/telemetry-subscribers/src/lib.rs @@ -362,7 +362,7 @@ impl TelemetryConfig { let mut directives = config.log_string.unwrap_or_else(|| "info".into()); if let Some(targets) = config.trace_target { for target in targets { - directives.push_str(&format!(",{}=trace", target)); + directives.push_str(&format!(",{target}=trace")); } } let env_filter = diff --git a/crates/telemetry-subscribers/tests/reload.rs b/crates/telemetry-subscribers/tests/reload.rs index 3bca8499eff..fcd3c507c2a 100644 --- a/crates/telemetry-subscribers/tests/reload.rs +++ b/crates/telemetry-subscribers/tests/reload.rs @@ -41,11 +41,10 @@ fn reload() { assert!( logs.contains("Should be able to see this"), - "logs: {}", - logs + "logs: {logs}" ); - assert!(!logs.contains("This won't be captured"), "logs: {}", logs); - assert!(logs.contains("Now you can see this!"), "logs: {}", logs); + assert!(!logs.contains("This won't be captured"), "logs: {logs}"); + assert!(logs.contains("Now you can see this!"), "logs: {logs}"); fs::remove_file(entry.path()).unwrap(); return; diff --git a/crates/test-cluster/src/lib.rs b/crates/test-cluster/src/lib.rs index 9d61d567b84..bdfa510e2e3 100644 --- a/crates/test-cluster/src/lib.rs +++ b/crates/test-cluster/src/lib.rs @@ -112,7 +112,7 @@ pub struct FullNodeHandle { impl FullNodeHandle { pub async fn new(iota_node: IotaNodeHandle, json_rpc_address: SocketAddr) -> Self { - let rpc_url = format!("http://{}", json_rpc_address); + let rpc_url = format!("http://{json_rpc_address}"); let rpc_client = HttpClientBuilder::default().build(&rpc_url).unwrap(); let iota_client = IotaClientBuilder::default().build(&rpc_url).await.unwrap(); @@ -575,7 +575,7 @@ impl TestCluster { let bridge_ports = self.bridge_server_ports.as_ref().unwrap(); let mut tasks = vec![]; for port in bridge_ports.iter() { - let server_url = format!("http://127.0.0.1:{}", port); + let server_url = format!("http://127.0.0.1:{port}"); tasks.push(wait_for_server_to_be_up(server_url, timeout_sec)); } join_all(tasks) @@ -620,7 +620,7 @@ impl TestCluster { match &tx.data().intent_message().value.kind() { TransactionKind::EndOfEpochTransaction(_) => (), TransactionKind::AuthenticatorStateUpdateV1(_) => break, - _ => panic!("{:?}", tx), + _ => panic!("{tx:?}"), } } }), @@ -1436,7 +1436,7 @@ impl TestClusterBuilder { .unwrap(); let server_port = get_available_port("127.0.0.1"); - let server_url = format!("http://127.0.0.1:{}", server_port); + let server_url = format!("http://127.0.0.1:{server_port}"); server_ports.push(server_port); let data = build_committee_register_transaction( validator_address, diff --git a/crates/transaction-fuzzer/src/account_universe.rs b/crates/transaction-fuzzer/src/account_universe.rs index 5ae8d3c0e02..633fe057ff6 100644 --- a/crates/transaction-fuzzer/src/account_universe.rs +++ b/crates/transaction-fuzzer/src/account_universe.rs @@ -26,14 +26,13 @@ static UNIVERSE_SIZE: Lazy = Lazy::new(|| { Ok(s) => match s.parse::() { Ok(val) => val, Err(err) => { - panic!("Could not parse universe size, aborting: {:?}", err); + panic!("Could not parse universe size, aborting: {err:?}"); } }, Err(env::VarError::NotPresent) => 30, Err(err) => { panic!( - "Could not read universe size from the environment, aborting: {:?}", - err + "Could not read universe size from the environment, aborting: {err:?}" ); } } diff --git a/crates/transaction-fuzzer/src/lib.rs b/crates/transaction-fuzzer/src/lib.rs index f13f52d3b17..6bc1570fd99 100644 --- a/crates/transaction-fuzzer/src/lib.rs +++ b/crates/transaction-fuzzer/src/lib.rs @@ -174,6 +174,6 @@ pub fn run_proptest( test_fn(test_data.data, test_data.executor) }); if result.is_err() { - panic!("test failed: {:?}", result); + panic!("test failed: {result:?}"); } } diff --git a/crates/transaction-fuzzer/src/type_arg_fuzzer.rs b/crates/transaction-fuzzer/src/type_arg_fuzzer.rs index 64af5301151..8cb4a91567e 100644 --- a/crates/transaction-fuzzer/src/type_arg_fuzzer.rs +++ b/crates/transaction-fuzzer/src/type_arg_fuzzer.rs @@ -129,7 +129,7 @@ pub fn type_factory_pt_for_tags( .move_call( package_id, Identifier::new("type_factory").unwrap(), - Identifier::new(format!("type_tags{}", len)).unwrap(), + Identifier::new(format!("type_tags{len}")).unwrap(), type_tags, vec![], ) diff --git a/crates/transaction-fuzzer/tests/pt_fuzz.rs b/crates/transaction-fuzzer/tests/pt_fuzz.rs index 61f0401e8d4..0c20aa0f325 100644 --- a/crates/transaction-fuzzer/tests/pt_fuzz.rs +++ b/crates/transaction-fuzzer/tests/pt_fuzz.rs @@ -103,8 +103,7 @@ pub fn run_pt_success( command: _, } ), - "{:?}", - status + "{status:?}" ); let new_cap = effects .mutated() diff --git a/iota-execution/cut/src/plan.rs b/iota-execution/cut/src/plan.rs index e12c963bd20..e88ce257314 100644 --- a/iota-execution/cut/src/plan.rs +++ b/iota-execution/cut/src/plan.rs @@ -749,7 +749,7 @@ mod tests { fn test_no_workspace() { let err = Workspace::read(env!("CARGO_MANIFEST_DIR")).unwrap_err(); expect!["No [workspace] found at $PATH/iota-execution/cut/Cargo.toml/Cargo.toml"] - .assert_eq(&scrub_path(&format!("{:#}", err), repo_root())); + .assert_eq(&scrub_path(&format!("{err:#}"), repo_root())); } #[test] @@ -786,7 +786,7 @@ mod tests { let err = Workspace::read(&tmp).unwrap_err(); expect!["Failed to read workspace.members: 'members' field is not an array of strings"] - .assert_eq(&scrub_path(&format!("{:#}", err), repo_root())); + .assert_eq(&scrub_path(&format!("{err:#}"), repo_root())); } #[test] @@ -805,7 +805,7 @@ mod tests { let err = Workspace::read(&tmp).unwrap_err(); expect!["Failed to read workspace.members: Canonicalizing path 'i_dont_exist': No such file or directory (os error 2)"] - .assert_eq(&scrub_path(&format!("{:#}", err), repo_root())); + .assert_eq(&scrub_path(&format!("{err:#}"), repo_root())); } #[test] @@ -1021,7 +1021,7 @@ mod tests { .unwrap_err(); expect!["Failed to find packages in $PATH: Failed to plan copy for $PATH/foo: Both member and exclude of [workspace]: $PATH/foo"] - .assert_eq(&scrub_path(&format!("{:#}", err), tmp.path())); + .assert_eq(&scrub_path(&format!("{err:#}"), tmp.path())); } #[test] @@ -1066,7 +1066,7 @@ mod tests { .unwrap_err(); expect!["Packages 'bar-latest' and 'bar' map to the same cut package name"] - .assert_eq(&format!("{:#}", err)); + .assert_eq(&format!("{err:#}")); } #[test] @@ -1111,7 +1111,7 @@ mod tests { .unwrap_err(); expect!["Packages 'foo-bar' and 'baz-bar' map to the same cut package path"] - .assert_eq(&format!("{:#}", err)); + .assert_eq(&format!("{err:#}")); } #[test] @@ -1149,7 +1149,7 @@ mod tests { .unwrap_err(); expect!["Failed to find packages in $PATH/foo: Failed to plan copy for $PATH/foo/bar: Cutting package 'foo-bar' will overwrite existing path: $PATH/baz/bar"] - .assert_eq(&scrub_path(&format!("{:#}", err), tmp.path())); + .assert_eq(&scrub_path(&format!("{err:#}"), tmp.path())); } #[test] diff --git a/iota-execution/latest/iota-adapter/src/adapter.rs b/iota-execution/latest/iota-adapter/src/adapter.rs index 5fd208d586f..8820737d3fb 100644 --- a/iota-execution/latest/iota-adapter/src/adapter.rs +++ b/iota-execution/latest/iota-adapter/src/adapter.rs @@ -208,7 +208,7 @@ mod checked { // Check that the status indicates metering timeout. if check_for_verifier_timeout(&e.major_status()) { return Err(IotaError::ModuleVerificationFailure { - error: format!("Verification timed out: {}", e), + error: format!("Verification timed out: {e}"), }); } } else if let Err(err) = diff --git a/iota-execution/latest/iota-adapter/src/programmable_transactions/context.rs b/iota-execution/latest/iota-adapter/src/programmable_transactions/context.rs index 71b60398d94..3e486b5a1c7 100644 --- a/iota-execution/latest/iota-adapter/src/programmable_transactions/context.rs +++ b/iota-execution/latest/iota-adapter/src/programmable_transactions/context.rs @@ -213,7 +213,7 @@ mod checked { .move_gas_status_mut() .set_profiler(GasProfiler::init( &vm.config().profiler_config, - format!("{}", tx_digest), + format!("{tx_digest}"), remaining_gas, )); } @@ -790,9 +790,8 @@ mod checked { ExecutionErrorKind::SharedObjectOperationNotAllowed, Some( format!( - "Shared object operation on {} not allowed: \ - cannot be frozen, transferred, or wrapped", - id + "Shared object operation on {id} not allowed: \ + cannot be frozen, transferred, or wrapped" ) .into(), ), @@ -805,8 +804,8 @@ mod checked { return Err(ExecutionError::new( ExecutionErrorKind::SharedObjectOperationNotAllowed, Some( - format!("Shared object operation on {} not allowed: \ - shared objects used by value must be re-shared if not deleted", id).into(), + format!("Shared object operation on {id} not allowed: \ + shared objects used by value must be re-shared if not deleted").into(), ), )); } @@ -1503,10 +1502,10 @@ mod checked { match self.linkage_view.get_module(module_id) { Ok(Some(bytes)) => Ok(bytes), Ok(None) => Err(PartialVMError::new(StatusCode::LINKER_ERROR) - .with_message(format!("Cannot find {:?} in data cache", module_id)) + .with_message(format!("Cannot find {module_id:?} in data cache")) .finish(Location::Undefined)), Err(err) => { - let msg = format!("Unexpected storage error: {:?}", err); + let msg = format!("Unexpected storage error: {err:?}"); Err( PartialVMError::new(StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR) .with_message(msg) diff --git a/iota-execution/latest/iota-adapter/src/programmable_transactions/execution.rs b/iota-execution/latest/iota-adapter/src/programmable_transactions/execution.rs index 7ebfdc6a079..aebb2f450b7 100644 --- a/iota-execution/latest/iota-adapter/src/programmable_transactions/execution.rs +++ b/iota-execution/latest/iota-adapter/src/programmable_transactions/execution.rs @@ -824,7 +824,7 @@ mod checked { "Missing dependencies: {}", missing_deps .into_iter() - .map(|dep| format!("{}", dep)) + .map(|dep| format!("{dep}")) .collect::>() .join(", ") ); @@ -1254,7 +1254,7 @@ mod checked { if module_ident == (&IOTA_FRAMEWORK_ADDRESS, EVENT_MODULE) { return Err(ExecutionError::new_with_source( ExecutionErrorKind::NonEntryFunctionInvoked, - format!("Cannot directly call functions in iota::{}", EVENT_MODULE), + format!("Cannot directly call functions in iota::{EVENT_MODULE}"), )); } @@ -1262,10 +1262,8 @@ mod checked { && PRIVATE_TRANSFER_FUNCTIONS.contains(&function) { let msg = format!( - "Cannot directly call iota::{m}::{f}. \ - Use the public variant instead, iota::{m}::public_{f}", - m = TRANSFER_MODULE, - f = function + "Cannot directly call iota::{TRANSFER_MODULE}::{function}. \ + Use the public variant instead, iota::{TRANSFER_MODULE}::public_{function}" ); return Err(ExecutionError::new_with_source( ExecutionErrorKind::NonEntryFunctionInvoked, @@ -1413,9 +1411,8 @@ mod checked { Value::Raw(RawValueType::Any, bytes) => { let Some(layout) = primitive_serialization_layout(context, param_ty)? else { let msg = format!( - "Non-primitive argument at index {}. If it is an object, it must be \ + "Non-primitive argument at index {idx}. If it is an object, it must be \ populated by an object", - idx, ); return Err(ExecutionError::new_with_source( ExecutionErrorKind::command_argument_error( diff --git a/iota-execution/latest/iota-adapter/src/temporary_store.rs b/iota-execution/latest/iota-adapter/src/temporary_store.rs index 447a5ce891b..ca3502232e8 100644 --- a/iota-execution/latest/iota-adapter/src/temporary_store.rs +++ b/iota-execution/latest/iota-adapter/src/temporary_store.rs @@ -879,9 +879,8 @@ impl TemporaryStore<'_> { { return Err(ExecutionError::invariant_violation(format!( "IOTA conservation failed -- no storage charges in gas summary \ - and total storage input rebate {} not equal \ - to total storage output rebate {}", - total_input_rebate, total_output_rebate, + and total storage input rebate {total_input_rebate} not equal \ + to total storage output rebate {total_output_rebate}", ))); } } else { @@ -961,9 +960,8 @@ impl TemporaryStore<'_> { } if total_input_iota != total_output_iota { return Err(ExecutionError::invariant_violation(format!( - "IOTA conservation failed: input={}, output={}, \ + "IOTA conservation failed: input={total_input_iota}, output={total_output_iota}, \ this transaction either mints or burns IOTA", - total_input_iota, total_output_iota, ))); } Ok(()) diff --git a/iota-execution/latest/iota-adapter/src/type_layout_resolver.rs b/iota-execution/latest/iota-adapter/src/type_layout_resolver.rs index 941c3cae02a..e61dc5bf6c9 100644 --- a/iota-execution/latest/iota-adapter/src/type_layout_resolver.rs +++ b/iota-execution/latest/iota-adapter/src/type_layout_resolver.rs @@ -44,7 +44,7 @@ impl LayoutResolver for TypeLayoutResolver<'_, '_> { ) -> Result { let Ok(ty) = load_type_from_struct(self.vm, &mut self.linkage_view, &[], struct_tag) else { return Err(IotaError::FailObjectLayout { - st: format!("{}", struct_tag), + st: format!("{struct_tag}"), }); }; let layout = self.vm.get_runtime().type_to_fully_annotated_layout(&ty); @@ -52,7 +52,7 @@ impl LayoutResolver for TypeLayoutResolver<'_, '_> { Ok(A::MoveTypeLayout::Struct(s)) => Ok(A::MoveDatatypeLayout::Struct(s)), Ok(A::MoveTypeLayout::Enum(e)) => Ok(A::MoveDatatypeLayout::Enum(e)), _ => Err(IotaError::FailObjectLayout { - st: format!("{}", struct_tag), + st: format!("{struct_tag}"), }), } } diff --git a/iota-execution/latest/iota-move-natives/src/object_runtime/mod.rs b/iota-execution/latest/iota-move-natives/src/object_runtime/mod.rs index ac03f0893df..610135b81a9 100644 --- a/iota-execution/latest/iota-move-natives/src/object_runtime/mod.rs +++ b/iota-execution/latest/iota-move-natives/src/object_runtime/mod.rs @@ -195,7 +195,7 @@ impl<'a> ObjectRuntime<'a> { self.metrics.excessive_new_move_object_ids ) { return Err(PartialVMError::new(StatusCode::MEMORY_LIMIT_EXCEEDED) - .with_message(format!("Creating more than {} IDs is not allowed", lim)) + .with_message(format!("Creating more than {lim} IDs is not allowed")) .with_sub_status( VMMemoryLimitExceededSubStatusCode::NEW_ID_COUNT_LIMIT_EXCEEDED as u64, )); @@ -226,7 +226,7 @@ impl<'a> ObjectRuntime<'a> { self.metrics.excessive_deleted_move_object_ids ) { return Err(PartialVMError::new(StatusCode::MEMORY_LIMIT_EXCEEDED) - .with_message(format!("Deleting more than {} IDs is not allowed", lim)) + .with_message(format!("Deleting more than {lim} IDs is not allowed")) .with_sub_status( VMMemoryLimitExceededSubStatusCode::DELETED_ID_COUNT_LIMIT_EXCEEDED as u64, )); @@ -293,7 +293,7 @@ impl<'a> ObjectRuntime<'a> { self.metrics.excessive_transferred_move_object_ids ) { return Err(PartialVMError::new(StatusCode::MEMORY_LIMIT_EXCEEDED) - .with_message(format!("Transferring more than {} IDs is not allowed", lim)) + .with_message(format!("Transferring more than {lim} IDs is not allowed")) .with_sub_status( VMMemoryLimitExceededSubStatusCode::TRANSFER_ID_COUNT_LIMIT_EXCEEDED as u64, )); @@ -512,8 +512,7 @@ impl<'a> ObjectRuntime<'a> { pub fn max_event_error(max_events: u64) -> PartialVMError { PartialVMError::new(StatusCode::MEMORY_LIMIT_EXCEEDED) .with_message(format!( - "Emitting more than {} events is not allowed", - max_events + "Emitting more than {max_events} events is not allowed" )) .with_sub_status(VMMemoryLimitExceededSubStatusCode::EVENT_COUNT_LIMIT_EXCEEDED as u64) } diff --git a/iota-execution/latest/iota-move-natives/src/object_runtime/object_store.rs b/iota-execution/latest/iota-move-natives/src/object_runtime/object_store.rs index fcada9506e3..6e7d9619d1d 100644 --- a/iota-execution/latest/iota-move-natives/src/object_runtime/object_store.rs +++ b/iota-execution/latest/iota-move-natives/src/object_runtime/object_store.rs @@ -259,8 +259,7 @@ impl Inner<'_> { ) { return Err(PartialVMError::new(StatusCode::MEMORY_LIMIT_EXCEEDED) .with_message(format!( - "Object runtime cached objects limit ({} entries) reached", - lim + "Object runtime cached objects limit ({lim} entries) reached" )) .with_sub_status( VMMemoryLimitExceededSubStatusCode::OBJECT_RUNTIME_CACHE_LIMIT_EXCEEDED @@ -513,8 +512,7 @@ impl<'a> ChildObjectStore<'a> { ) { return Err(PartialVMError::new(StatusCode::MEMORY_LIMIT_EXCEEDED) .with_message(format!( - "Object runtime store limit ({} entries) reached", - lim + "Object runtime store limit ({lim} entries) reached" )) .with_sub_status( VMMemoryLimitExceededSubStatusCode::OBJECT_RUNTIME_STORE_LIMIT_EXCEEDED @@ -561,8 +559,7 @@ impl<'a> ChildObjectStore<'a> { ) { return Err(PartialVMError::new(StatusCode::MEMORY_LIMIT_EXCEEDED) .with_message(format!( - "Object runtime store limit ({} entries) reached", - lim + "Object runtime store limit ({lim} entries) reached" )) .with_sub_status( VMMemoryLimitExceededSubStatusCode::OBJECT_RUNTIME_STORE_LIMIT_EXCEEDED as u64, diff --git a/iota-execution/latest/iota-verifier/src/entry_points_verifier.rs b/iota-execution/latest/iota-verifier/src/entry_points_verifier.rs index 4c556f64069..4ac545404c9 100644 --- a/iota-execution/latest/iota-verifier/src/entry_points_verifier.rs +++ b/iota-execution/latest/iota-verifier/src/entry_points_verifier.rs @@ -208,7 +208,7 @@ fn verify_return_type( } let abilities = view .abilities(return_ty, type_parameters) - .map_err(|e| format!("Unexpected CompiledModule error: {}", e))?; + .map_err(|e| format!("Unexpected CompiledModule error: {e}"))?; if abilities.has_drop() { Ok(()) } else { diff --git a/iota-execution/latest/iota-verifier/src/id_leak_verifier.rs b/iota-execution/latest/iota-verifier/src/id_leak_verifier.rs index 50383e4624a..101a0dad047 100644 --- a/iota-execution/latest/iota-verifier/src/id_leak_verifier.rs +++ b/iota-execution/latest/iota-verifier/src/id_leak_verifier.rs @@ -156,8 +156,7 @@ fn verify_id_leak( module.identifier_at(module.function_handle_at(func_def.function).name); let module_name = module.self_id(); verification_failure(format!( - "{} Found in {module_name}::{function_name}", - message + "{message} Found in {module_name}::{function_name}" )) } else { verification_failure(err.to_string()) @@ -313,7 +312,7 @@ fn call( let function = verifier.resolve_function(function_handle); if FRESH_ID_FUNCTIONS.contains(&function) { if return_.0.len() != 1 { - debug_assert!(false, "{:?} should have a single return value", function); + debug_assert!(false, "{function:?} should have a single return value"); return Err(PartialVMError::new(StatusCode::UNKNOWN_VERIFICATION_ERROR) .with_message("Should have a single return value".to_string()) .with_sub_status( diff --git a/iota-execution/latest/iota-verifier/src/private_generics.rs b/iota-execution/latest/iota-verifier/src/private_generics.rs index 2de2ffd081e..3d7f3154ed7 100644 --- a/iota-execution/latest/iota-verifier/src/private_generics.rs +++ b/iota-execution/latest/iota-verifier/src/private_generics.rs @@ -115,13 +115,13 @@ fn verify_private_transfer( } if !PRIVATE_TRANSFER_FUNCTIONS.contains(&fident) { // unknown function, so a bug in the implementation here - debug_assert!(false, "unknown transfer function {}", fident); - return Err(format!("Calling unknown transfer function, {}", fident)); + debug_assert!(false, "unknown transfer function {fident}"); + return Err(format!("Calling unknown transfer function, {fident}")); }; if type_arguments.len() != 1 { - debug_assert!(false, "Expected 1 type argument for {}", fident); - return Err(format!("Expected 1 type argument for {}", fident)); + debug_assert!(false, "Expected 1 type argument for {fident}"); + return Err(format!("Expected 1 type argument for {fident}")); } let type_arg = &type_arguments[0]; @@ -151,13 +151,13 @@ fn verify_private_event_emit( return Ok(()); } if fident != EVENT_FUNCTION { - debug_assert!(false, "unknown event function {}", fident); - return Err(format!("Calling unknown event function, {}", fident)); + debug_assert!(false, "unknown event function {fident}"); + return Err(format!("Calling unknown event function, {fident}")); }; if type_arguments.len() != 1 { - debug_assert!(false, "Expected 1 type argument for {}", fident); - return Err(format!("Expected 1 type argument for {}", fident)); + debug_assert!(false, "Expected 1 type argument for {fident}"); + return Err(format!("Expected 1 type argument for {fident}")); } let type_arg = &type_arguments[0]; diff --git a/iota-execution/latest/iota-verifier/src/struct_with_key_verifier.rs b/iota-execution/latest/iota-verifier/src/struct_with_key_verifier.rs index 5eb0713654a..c58fe041f80 100644 --- a/iota-execution/latest/iota-verifier/src/struct_with_key_verifier.rs +++ b/iota-execution/latest/iota-verifier/src/struct_with_key_verifier.rs @@ -36,16 +36,14 @@ fn verify_key_structs(module: &CompiledModule) -> Result<(), ExecutionError> { Some(field) => field, None => { return Err(verification_failure(format!( - "First field of struct {} must be 'id', no field found", - name + "First field of struct {name} must be 'id', no field found" ))); } }; let first_field_name = module.identifier_at(first_field.name).as_str(); if first_field_name != "id" { return Err(verification_failure(format!( - "First field of struct {} must be 'id', {} found", - name, first_field_name + "First field of struct {name} must be 'id', {first_field_name} found" ))); } // Check that the "id" field must have a struct type. @@ -54,9 +52,8 @@ fn verify_key_structs(module: &CompiledModule) -> Result<(), ExecutionError> { SignatureToken::Datatype(struct_type) => struct_type, _ => { return Err(verification_failure(format!( - "First field of struct {} must be of type {}::object::UID, \ - {:?} type found", - name, IOTA_FRAMEWORK_ADDRESS, uid_field_type + "First field of struct {name} must be of type {IOTA_FRAMEWORK_ADDRESS}::object::UID, \ + {uid_field_type:?} type found" ))); } }; @@ -72,13 +69,8 @@ fn verify_key_structs(module: &CompiledModule) -> Result<(), ExecutionError> { && uid_type_module_address == &IOTA_FRAMEWORK_ADDRESS && uid_type_module_name == OBJECT_MODULE_NAME, verification_failure(format!( - "First field of struct {} must be of type {}::object::UID, \ - {}::{}::{} type found", - name, - IOTA_FRAMEWORK_ADDRESS, - uid_type_module_address, - uid_type_module_name, - uid_type_struct_name + "First field of struct {name} must be of type {IOTA_FRAMEWORK_ADDRESS}::object::UID, \ + {uid_type_module_address}::{uid_type_module_name}::{uid_type_struct_name} type found" )) ); }