diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index b3e1303d8..2228e412d 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -17,7 +17,7 @@ jobs: uses: dtolnay/rust-toolchain@stable with: components: clippy - toolchain: 1.71.0 + toolchain: 1.74.0 - name: Install toolchain (nightly) run: rustup toolchain add nightly --component rustfmt --profile minimal - uses: Swatinem/rust-cache@v2 diff --git a/Cargo.toml b/Cargo.toml index fcce618ea..64fce6acf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ resolver = "2" [workspace.package] version = "0.1.0-beta" edition = "2021" -rust-version = "1.71" +rust-version = "1.74" license = "MIT OR Apache-2.0" repository = "https://github.com/alchemyplatform/rundler" diff --git a/Dockerfile b/Dockerfile index 15b72a803..1c5f94289 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ # Adapted from https://github.com/paradigmxyz/reth/blob/main/Dockerfile # syntax=docker/dockerfile:1.4 -FROM rust:1.72.0 AS chef-builder +FROM rust:1.74.0 AS chef-builder # Install system dependencies RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list diff --git a/bin/rundler/src/cli/rpc.rs b/bin/rundler/src/cli/rpc.rs index 80980d6f9..ca59f1f8d 100644 --- a/bin/rundler/src/cli/rpc.rs +++ b/bin/rundler/src/cli/rpc.rs @@ -163,13 +163,14 @@ pub async fn run(rpc_args: RpcCliArgs, common_args: CommonArgs) -> anyhow::Resul ) .await?; - let builder = connect_with_retries_shutdown( - "builder from rpc", - &builder_url, - RemoteBuilderClient::connect, - tokio::signal::ctrl_c(), - ) - .await?; + let builder = + connect_with_retries_shutdown( + "builder from rpc", + &builder_url, + RemoteBuilderClient::connect, + tokio::signal::ctrl_c(), + ) + .await?; spawn_tasks_with_shutdown( [RpcTask::new(task_args, pool, builder).boxed()], diff --git a/bin/tools/src/bin/deploy_dev_contracts.rs b/bin/tools/src/bin/deploy_dev_contracts.rs index 1d59ee1de..49b3000f2 100644 --- a/bin/tools/src/bin/deploy_dev_contracts.rs +++ b/bin/tools/src/bin/deploy_dev_contracts.rs @@ -45,9 +45,7 @@ async fn main() -> anyhow::Result<()> { ); println!( "Paymaster private signing key: 0x{}", - hex::encode(rundler_dev::test_signing_key_bytes( - PAYMASTER_SIGNER_ACCOUNT_ID - )) + hex::encode(rundler_dev::test_signing_key_bytes(PAYMASTER_SIGNER_ACCOUNT_ID)) ); Ok(()) } diff --git a/crates/builder/src/bundle_proposer.rs b/crates/builder/src/bundle_proposer.rs index a310b272a..acfdf0a0d 100644 --- a/crates/builder/src/bundle_proposer.rs +++ b/crates/builder/src/bundle_proposer.rs @@ -595,10 +595,11 @@ where } fn emit(&self, event: BuilderEvent) { - let _ = self.event_sender.send(WithEntryPoint { - entry_point: self.entry_point.address(), - event, - }); + let _ = + self.event_sender.send(WithEntryPoint { + entry_point: self.entry_point.address(), + event, + }); } fn op_hash(&self, op: &UserOperation) -> H256 { @@ -893,9 +894,9 @@ mod tests { let op = UserOperation::default(); let bundle = simple_make_bundle(vec![MockOp { op: op.clone(), - simulation_result: Box::new(|| { - Err(SimulationError::Other(anyhow!("simulation failed"))) - }), + simulation_result: Box::new( + || Err(SimulationError::Other(anyhow!("simulation failed"))) + ), }]) .await; assert!(bundle.ops_per_aggregator.is_empty()); @@ -905,15 +906,14 @@ mod tests { #[tokio::test] async fn test_rejects_on_signature_failure() { let op = UserOperation::default(); - let bundle = simple_make_bundle(vec![MockOp { - op: op.clone(), - simulation_result: Box::new(|| { - Err(SimulationError::Violations(vec![ - SimulationViolation::InvalidSignature, - ])) - }), - }]) - .await; + let bundle = + simple_make_bundle(vec![MockOp { + op: op.clone(), + simulation_result: Box::new( + || Err(SimulationError::Violations(vec![SimulationViolation::InvalidSignature])) + ), + }]) + .await; assert!(bundle.ops_per_aggregator.is_empty()); assert_eq!(bundle.rejected_ops, vec![op]); } diff --git a/crates/builder/src/bundle_sender.rs b/crates/builder/src/bundle_sender.rs index 792b31a52..ea084b90b 100644 --- a/crates/builder/src/bundle_sender.rs +++ b/crates/builder/src/bundle_sender.rs @@ -507,10 +507,11 @@ where } fn emit(&self, event: BuilderEvent) { - let _ = self.event_sender.send(WithEntryPoint { - entry_point: self.entry_point.address(), - event, - }); + let _ = + self.event_sender.send(WithEntryPoint { + entry_point: self.entry_point.address(), + event, + }); } fn op_hash(&self, op: &UserOperation) -> H256 { diff --git a/crates/builder/src/sender/mod.rs b/crates/builder/src/sender/mod.rs index d9587597b..555a85d19 100644 --- a/crates/builder/src/sender/mod.rs +++ b/crates/builder/src/sender/mod.rs @@ -133,9 +133,9 @@ impl TransactionSenderType { ) -> Result, SenderConstructorErrors> { let sender = match self { Self::Raw => TransactionSenderEnum::Raw(RawTransactionSender::new(client, signer)), - Self::Conditional => TransactionSenderEnum::Conditional( - ConditionalTransactionSender::new(client, signer), - ), + Self::Conditional => { + TransactionSenderEnum::Conditional(ConditionalTransactionSender::new(client, signer)) + } Self::Flashbots => { if chain_id != Chain::Mainnet as u64 { return Err(SenderConstructorErrors::InvalidChainForSender( diff --git a/crates/builder/src/server/remote/client.rs b/crates/builder/src/server/remote/client.rs index 34d23e372..8afc6acbf 100644 --- a/crates/builder/src/server/remote/client.rs +++ b/crates/builder/src/server/remote/client.rs @@ -83,9 +83,9 @@ impl BuilderServer for RemoteBuilderClient { Ok((H256::from_slice(&s.transaction_hash), s.block_number)) } Some(debug_send_bundle_now_response::Result::Failure(f)) => Err(f.try_into()?), - None => Err(BuilderServerError::Other(anyhow::anyhow!( - "should have received result from builder" - )))?, + None => Err(BuilderServerError::Other( + anyhow::anyhow!("should have received result from builder") + ))?, } } @@ -103,9 +103,9 @@ impl BuilderServer for RemoteBuilderClient { match res { Some(debug_set_bundling_mode_response::Result::Success(_)) => Ok(()), Some(debug_set_bundling_mode_response::Result::Failure(f)) => Err(f.try_into()?), - None => Err(BuilderServerError::Other(anyhow::anyhow!( - "should have received result from builder" - )))?, + None => Err(BuilderServerError::Other( + anyhow::anyhow!("should have received result from builder") + ))?, } } } diff --git a/crates/builder/src/server/remote/error.rs b/crates/builder/src/server/remote/error.rs index 0b49ea6aa..4e1231549 100644 --- a/crates/builder/src/server/remote/error.rs +++ b/crates/builder/src/server/remote/error.rs @@ -45,9 +45,7 @@ impl From for ProtoBuilderError { fn from(value: BuilderServerError) -> Self { match value { BuilderServerError::UnexpectedResponse => ProtoBuilderError { - error: Some(builder_error::Error::Internal( - "Unexpected response".to_string(), - )), + error: Some(builder_error::Error::Internal("Unexpected response".to_string())), }, BuilderServerError::Other(e) => ProtoBuilderError { error: Some(builder_error::Error::Internal(e.to_string())), diff --git a/crates/builder/src/server/remote/server.rs b/crates/builder/src/server/remote/server.rs index 6c25be149..758261002 100644 --- a/crates/builder/src/server/remote/server.rs +++ b/crates/builder/src/server/remote/server.rs @@ -102,14 +102,16 @@ impl GrpcBuilder for GrpcBuilderServerImpl { _request: Request, ) -> tonic::Result> { let resp = match self.local_builder.debug_send_bundle_now().await { - Ok((hash, block_number)) => DebugSendBundleNowResponse { - result: Some(debug_send_bundle_now_response::Result::Success( - DebugSendBundleNowSuccess { - transaction_hash: hash.as_bytes().to_vec(), - block_number, - }, - )), - }, + Ok((hash, block_number)) => { + DebugSendBundleNowResponse { + result: Some(debug_send_bundle_now_response::Result::Success( + DebugSendBundleNowSuccess { + transaction_hash: hash.as_bytes().to_vec(), + block_number, + }, + )), + } + } Err(e) => { return Err(Status::internal(format!("Failed to send bundle: {e}"))); } @@ -124,9 +126,9 @@ impl GrpcBuilder for GrpcBuilderServerImpl { ) -> tonic::Result> { let resp = match self .local_builder - .debug_set_bundling_mode(request.into_inner().mode.try_into().map_err(|e| { - Status::internal(format!("Failed to convert from proto reputation {e}")) - })?) + .debug_set_bundling_mode(request.into_inner().mode.try_into().map_err( + |e| Status::internal(format!("Failed to convert from proto reputation {e}")) + )?) .await { Ok(()) => DebugSetBundlingModeResponse { @@ -135,9 +137,7 @@ impl GrpcBuilder for GrpcBuilderServerImpl { )), }, Err(e) => { - return Err(Status::internal(format!( - "Failed to set bundling mode: {e}" - ))); + return Err(Status::internal(format!("Failed to set bundling mode: {e}"))); } }; diff --git a/crates/builder/src/signer/aws.rs b/crates/builder/src/signer/aws.rs index 52f7f6455..20491f644 100644 --- a/crates/builder/src/signer/aws.rs +++ b/crates/builder/src/signer/aws.rs @@ -47,9 +47,9 @@ impl KmsSigner { if key_ids.len() > 1 { let (tx, rx) = oneshot::channel::(); - kms_guard = Some(SpawnGuard::spawn_with_guard(Self::lock_manager_loop( - redis_uri, key_ids, chain_id, ttl_millis, tx, - ))); + kms_guard = Some(SpawnGuard::spawn_with_guard( + Self::lock_manager_loop(redis_uri, key_ids, chain_id, ttl_millis, tx) + )); key_id = rx.await.context("should lock key_id")?; } else { key_id = key_ids @@ -62,10 +62,9 @@ impl KmsSigner { .await .context("should create signer")?; - let monitor_guard = SpawnGuard::spawn_with_guard(monitor_account_balance( - signer.address(), - provider.clone(), - )); + let monitor_guard = SpawnGuard::spawn_with_guard( + monitor_account_balance(signer.address(), provider.clone()) + ); Ok(Self { signer, @@ -105,9 +104,10 @@ impl KmsSigner { let lock_id = locked_id.unwrap(); let _ = locked_tx.send(kid.unwrap()); - let mut lg_opt = Some(LockGuard { - lock: lock.unwrap(), - }); + let mut lg_opt = + Some(LockGuard { + lock: lock.unwrap(), + }); loop { sleep(Duration::from_millis(ttl_millis / 10)).await; diff --git a/crates/builder/src/task.rs b/crates/builder/src/task.rs index 62daea0b8..40a5a3407 100644 --- a/crates/builder/src/task.rs +++ b/crates/builder/src/task.rs @@ -153,12 +153,13 @@ where ); let builder_handle = self.builder_builder.get_handle(); - let builder_runnder_handle = self.builder_builder.run( - manual_bundling_mode, - send_bundle_txs, - vec![self.args.entry_point_address], - shutdown_token.clone(), - ); + let builder_runnder_handle = + self.builder_builder.run( + manual_bundling_mode, + send_bundle_txs, + vec![self.args.entry_point_address], + shutdown_token.clone(), + ); let remote_handle = match self.args.remote_address { Some(addr) => { diff --git a/crates/builder/src/transaction_tracker.rs b/crates/builder/src/transaction_tracker.rs index 63c7f9229..812ffe273 100644 --- a/crates/builder/src/transaction_tracker.rs +++ b/crates/builder/src/transaction_tracker.rs @@ -665,10 +665,7 @@ mod tests { let tracker = create_tracker(sender, provider).await; let tracker_update = tracker.wait_for_update().await.unwrap(); - assert!(matches!( - tracker_update, - TrackerUpdate::StillPendingAfterWait - )); + assert!(matches!(tracker_update, TrackerUpdate::StillPendingAfterWait)); } #[tokio::test] @@ -702,10 +699,7 @@ mod tests { let _sent_transaction = tracker.send_transaction(tx.into(), &exp).await.unwrap(); let tracker_update = tracker.wait_for_update().await.unwrap(); - assert!(matches!( - tracker_update, - TrackerUpdate::LatestTxDropped { .. } - )); + assert!(matches!(tracker_update, TrackerUpdate::LatestTxDropped { .. })); } #[tokio::test] @@ -731,10 +725,7 @@ mod tests { let tracker_update = tracker.wait_for_update().await.unwrap(); - assert!(matches!( - tracker_update, - TrackerUpdate::NonceUsedForOtherTx { .. } - )); + assert!(matches!(tracker_update, TrackerUpdate::NonceUsedForOtherTx { .. })); } #[tokio::test] diff --git a/crates/dev/src/lib.rs b/crates/dev/src/lib.rs index a73094601..25b08ab11 100644 --- a/crates/dev/src/lib.rs +++ b/crates/dev/src/lib.rs @@ -497,9 +497,9 @@ struct DeterministicDeployProxy { } impl DeterministicDeployProxy { - const PROXY_ADDRESS: &str = "0x4e59b44847b379578588920ca78fbf26c0b4956c"; - const DEPLOYMENT_TRANSACTION: &str = "0xf8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222"; - const DEPLOYMENT_SIGNER: &str = "0x3fab184622dc19b6109349b94811493bf2a45362"; + const PROXY_ADDRESS: &'static str = "0x4e59b44847b379578588920ca78fbf26c0b4956c"; + const DEPLOYMENT_TRANSACTION: &'static str = "0xf8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222"; + const DEPLOYMENT_SIGNER: &'static str = "0x3fab184622dc19b6109349b94811493bf2a45362"; const DEPLOYMENT_GAS_PRICE: u64 = 100_000_000_000; const DEPLOYMENT_GAS_LIMIT: u64 = 100_000; diff --git a/crates/pool/src/chain.rs b/crates/pool/src/chain.rs index e4d542873..e8c2e3d69 100644 --- a/crates/pool/src/chain.rs +++ b/crates/pool/src/chain.rs @@ -136,12 +136,13 @@ impl Chain

{ .map(|block| block.hash) .unwrap_or_default(); loop { - let (hash, block) = block_watcher::wait_for_new_block( - &*self.provider, - block_hash, - self.settings.poll_interval, - ) - .await; + let (hash, block) = + block_watcher::wait_for_new_block( + &*self.provider, + block_hash, + self.settings.poll_interval, + ) + .await; block_hash = hash; let update = self.sync_to_block(block).await; match update { @@ -205,19 +206,20 @@ impl Chain

{ current_block_number: u64, added_blocks: VecDeque, ) -> ChainUpdate { - let mined_ops: Vec<_> = added_blocks - .iter() - .flat_map(|block| &block.ops) - .copied() - .collect(); + let mined_ops: Vec<_> = + added_blocks + .iter() + .flat_map(|block| &block.ops) + .copied() + .collect(); let reorg_depth = current_block_number + 1 - added_blocks[0].number; - let unmined_ops: Vec<_> = self - .blocks - .iter() - .skip(self.blocks.len() - reorg_depth as usize) - .flat_map(|block| &block.ops) - .copied() - .collect(); + let unmined_ops: Vec<_> = + self.blocks + .iter() + .skip(self.blocks.len() - reorg_depth as usize) + .flat_map(|block| &block.ops) + .copied() + .collect(); for _ in 0..reorg_depth { self.blocks.pop_back(); } @@ -518,11 +520,12 @@ mod tests { fn get_block_by_hash(&self, hash: H256) -> Option> { let blocks = self.blocks.read(); let number = blocks.iter().position(|block| block.hash == hash)?; - let parent_hash = if number > 0 { - blocks[number - 1].hash - } else { - H256::zero() - }; + let parent_hash = + if number > 0 { + blocks[number - 1].hash + } else { + H256::zero() + }; Some(Block { hash: Some(hash), parent_hash, @@ -812,9 +815,7 @@ mod tests { Log { address: ENTRY_POINT_ADDRESS, topics: vec![ - H256::from(utils::keccak256( - UserOperationEventFilter::abi_signature().as_bytes(), - )), + H256::from(utils::keccak256(UserOperationEventFilter::abi_signature().as_bytes())), op_hash, H256::zero(), // sender H256::zero(), // paymaster diff --git a/crates/pool/src/mempool/error.rs b/crates/pool/src/mempool/error.rs index 241fb4ec3..f255b167a 100644 --- a/crates/pool/src/mempool/error.rs +++ b/crates/pool/src/mempool/error.rs @@ -82,9 +82,6 @@ impl From for MempoolError { }; // extract violation and replace with dummy - Self::PrecheckViolation(mem::replace( - violation, - PrecheckViolation::InitCodeTooShort(0), - )) + Self::PrecheckViolation(mem::replace(violation, PrecheckViolation::InitCodeTooShort(0))) } } diff --git a/crates/pool/src/mempool/reputation.rs b/crates/pool/src/mempool/reputation.rs index f1181bafe..e5a08a8f3 100644 --- a/crates/pool/src/mempool/reputation.rs +++ b/crates/pool/src/mempool/reputation.rs @@ -266,10 +266,11 @@ impl AddressReputation { return ReputationStatus::Ok; } - let count = match self.counts.get(&address) { - Some(count) => count, - None => return ReputationStatus::Ok, - }; + let count = + match self.counts.get(&address) { + Some(count) => count, + None => return ReputationStatus::Ok, + }; let min_expected_included = count.ops_seen / self.params.min_inclusion_rate_denominator; if min_expected_included <= (count.ops_included + self.params.throttling_slack) { diff --git a/crates/pool/src/mempool/uo_pool.rs b/crates/pool/src/mempool/uo_pool.rs index f7ff5325d..98571bd0c 100644 --- a/crates/pool/src/mempool/uo_pool.rs +++ b/crates/pool/src/mempool/uo_pool.rs @@ -88,10 +88,11 @@ where } fn emit(&self, event: OpPoolEvent) { - let _ = self.event_sender.send(WithEntryPoint { - entry_point: self.config.entry_point, - event, - }); + let _ = + self.event_sender.send(WithEntryPoint { + entry_point: self.config.entry_point, + event, + }); } } @@ -750,14 +751,15 @@ mod tests { #[tokio::test] async fn precheck_error() { - let op = create_op_with_errors( - Address::random(), - 0, - 0, - Some(PrecheckViolation::InitCodeTooShort(0)), - None, - false, - ); + let op = + create_op_with_errors( + Address::random(), + 0, + 0, + Some(PrecheckViolation::InitCodeTooShort(0)), + None, + false, + ); let ops = vec![op.clone()]; let pool = create_pool(ops); diff --git a/crates/pool/src/server/local.rs b/crates/pool/src/server/local.rs index c27e96728..5dd11dcb1 100644 --- a/crates/pool/src/server/local.rs +++ b/crates/pool/src/server/local.rs @@ -119,11 +119,12 @@ impl PoolServer for LocalPoolHandle { } async fn add_op(&self, entry_point: Address, op: UserOperation) -> PoolResult { - let req = ServerRequestKind::AddOp { - entry_point, - op, - origin: OperationOrigin::Local, - }; + let req = + ServerRequestKind::AddOp { + entry_point, + op, + origin: OperationOrigin::Local, + }; let resp = self.send(req).await?; match resp { ServerResponse::AddOp { hash } => Ok(hash), @@ -286,9 +287,9 @@ where } fn get_pool(&self, entry_point: Address) -> PoolResult<&Arc> { - self.mempools.get(&entry_point).ok_or_else(|| { - PoolServerError::MempoolError(MempoolError::UnknownEntryPoint(entry_point)) - }) + self.mempools.get(&entry_point).ok_or_else( + || PoolServerError::MempoolError(MempoolError::UnknownEntryPoint(entry_point)) + ) } fn get_ops( @@ -572,11 +573,12 @@ mod tests { let ep = Address::random(); let state = setup(HashMap::from([(ep, Arc::new(mock_pool))])); - let hash1 = state - .handle - .add_op(ep, UserOperation::default()) - .await - .unwrap(); + let hash1 = + state + .handle + .add_op(ep, UserOperation::default()) + .await + .unwrap(); assert_eq!(hash0, hash1); } diff --git a/crates/pool/src/server/remote/client.rs b/crates/pool/src/server/remote/client.rs index ce72e52a0..bbae18f02 100644 --- a/crates/pool/src/server/remote/client.rs +++ b/crates/pool/src/server/remote/client.rs @@ -148,9 +148,9 @@ impl PoolServer for RemotePoolClient { match res { Some(add_op_response::Result::Success(s)) => Ok(H256::from_slice(&s.hash)), Some(add_op_response::Result::Failure(f)) => Err(f.try_into()?), - None => Err(PoolServerError::Other(anyhow::anyhow!( - "should have received result from op pool" - )))?, + None => Err( + PoolServerError::Other(anyhow::anyhow!("should have received result from op pool")) + )?, } } @@ -180,9 +180,9 @@ impl PoolServer for RemotePoolClient { .map(|res| res.map_err(PoolServerError::from)) .collect(), Some(get_ops_response::Result::Failure(f)) => Err(f.try_into()?), - None => Err(PoolServerError::Other(anyhow::anyhow!( - "should have received result from op pool" - )))?, + None => Err( + PoolServerError::Other(anyhow::anyhow!("should have received result from op pool")) + )?, } } @@ -201,9 +201,9 @@ impl PoolServer for RemotePoolClient { match res { Some(remove_ops_response::Result::Success(_)) => Ok(()), Some(remove_ops_response::Result::Failure(f)) => Err(f.try_into()?), - None => Err(PoolServerError::Other(anyhow::anyhow!( - "should have received result from op pool" - )))?, + None => Err( + PoolServerError::Other(anyhow::anyhow!("should have received result from op pool")) + )?, } } @@ -222,9 +222,9 @@ impl PoolServer for RemotePoolClient { match res { Some(remove_entities_response::Result::Success(_)) => Ok(()), Some(remove_entities_response::Result::Failure(f)) => Err(f.try_into()?), - None => Err(PoolServerError::Other(anyhow::anyhow!( - "should have received result from op pool" - )))?, + None => Err( + PoolServerError::Other(anyhow::anyhow!("should have received result from op pool")) + )?, } } @@ -250,9 +250,9 @@ impl PoolServer for RemotePoolClient { match res { Some(update_entities_response::Result::Success(_)) => Ok(()), Some(update_entities_response::Result::Failure(f)) => Err(f.try_into()?), - None => Err(PoolServerError::Other(anyhow::anyhow!( - "should have received result from op pool" - )))?, + None => Err( + PoolServerError::Other(anyhow::anyhow!("should have received result from op pool")) + )?, } } @@ -268,22 +268,22 @@ impl PoolServer for RemotePoolClient { match res { Some(debug_clear_state_response::Result::Success(_)) => Ok(()), Some(debug_clear_state_response::Result::Failure(f)) => Err(f.try_into()?), - None => Err(PoolServerError::Other(anyhow::anyhow!( - "should have received result from op pool" - )))?, + None => Err( + PoolServerError::Other(anyhow::anyhow!("should have received result from op pool")) + )?, } } async fn debug_dump_mempool(&self, entry_point: Address) -> PoolResult> { - let res = self - .op_pool_client - .clone() - .debug_dump_mempool(DebugDumpMempoolRequest { - entry_point: entry_point.as_bytes().to_vec(), - }) - .await? - .into_inner() - .result; + let res = + self.op_pool_client + .clone() + .debug_dump_mempool(DebugDumpMempoolRequest { + entry_point: entry_point.as_bytes().to_vec(), + }) + .await? + .into_inner() + .result; match res { Some(debug_dump_mempool_response::Result::Success(s)) => s @@ -293,9 +293,9 @@ impl PoolServer for RemotePoolClient { .map(|res| res.map_err(PoolServerError::from)) .collect(), Some(debug_dump_mempool_response::Result::Failure(f)) => Err(f.try_into()?), - None => Err(PoolServerError::Other(anyhow::anyhow!( - "should have received result from op pool" - )))?, + None => Err( + PoolServerError::Other(anyhow::anyhow!("should have received result from op pool")) + )?, } } @@ -321,9 +321,9 @@ impl PoolServer for RemotePoolClient { match res { Some(debug_set_reputation_response::Result::Success(_)) => Ok(()), Some(debug_set_reputation_response::Result::Failure(f)) => Err(f.try_into()?), - None => Err(PoolServerError::Other(anyhow::anyhow!( - "should have received result from op pool" - )))?, + None => Err( + PoolServerError::Other(anyhow::anyhow!("should have received result from op pool")) + )?, } } @@ -346,9 +346,9 @@ impl PoolServer for RemotePoolClient { .map(|res| res.map_err(PoolServerError::from)) .collect(), Some(debug_dump_reputation_response::Result::Failure(f)) => Err(f.try_into()?), - None => Err(PoolServerError::Other(anyhow::anyhow!( - "should have received result from op pool" - )))?, + None => Err( + PoolServerError::Other(anyhow::anyhow!("should have received result from op pool")) + )?, } } diff --git a/crates/pool/src/server/remote/error.rs b/crates/pool/src/server/remote/error.rs index 8772bffd3..271b86f37 100644 --- a/crates/pool/src/server/remote/error.rs +++ b/crates/pool/src/server/remote/error.rs @@ -59,11 +59,13 @@ impl From for ProtoMempoolError { fn from(value: PoolServerError) -> Self { match value { PoolServerError::MempoolError(e) => e.into(), - PoolServerError::UnexpectedResponse => ProtoMempoolError { - error: Some(mempool_error::Error::Internal( - "unexpected response from pool server".to_string(), - )), - }, + PoolServerError::UnexpectedResponse => { + ProtoMempoolError { + error: Some(mempool_error::Error::Internal( + "unexpected response from pool server".to_string(), + )), + } + } PoolServerError::Other(e) => ProtoMempoolError { error: Some(mempool_error::Error::Internal(e.to_string())), }, @@ -119,11 +121,13 @@ impl From for ProtoMempoolError { MempoolError::Other(e) => ProtoMempoolError { error: Some(mempool_error::Error::Internal(e.to_string())), }, - MempoolError::OperationAlreadyKnown => ProtoMempoolError { - error: Some(mempool_error::Error::OperationAlreadyKnown( - OperationAlreadyKnownError {}, - )), - }, + MempoolError::OperationAlreadyKnown => { + ProtoMempoolError { + error: Some( + mempool_error::Error::OperationAlreadyKnown(OperationAlreadyKnownError {}) + ), + } + } MempoolError::ReplacementUnderpriced(fee, priority_fee) => ProtoMempoolError { error: Some(mempool_error::Error::ReplacementUnderpriced( ReplacementUnderpricedError { @@ -132,25 +136,27 @@ impl From for ProtoMempoolError { }, )), }, - MempoolError::MaxOperationsReached(ops, addr) => ProtoMempoolError { - error: Some(mempool_error::Error::MaxOperationsReached( - MaxOperationsReachedError { - num_ops: ops as u64, - sender_address: addr.as_bytes().to_vec(), - }, - )), - }, - MempoolError::EntityThrottled(entity) => ProtoMempoolError { - error: Some(mempool_error::Error::EntityThrottled( - EntityThrottledError { - entity: Some((&entity).into()), - }, - )), - }, + MempoolError::MaxOperationsReached(ops, addr) => { + ProtoMempoolError { + error: Some(mempool_error::Error::MaxOperationsReached( + MaxOperationsReachedError { + num_ops: ops as u64, + sender_address: addr.as_bytes().to_vec(), + }, + )), + } + } + MempoolError::EntityThrottled(entity) => { + ProtoMempoolError { + error: Some(mempool_error::Error::EntityThrottled( + EntityThrottledError { + entity: Some((&entity).into()), + }, + )), + } + } MempoolError::DiscardedOnInsert => ProtoMempoolError { - error: Some(mempool_error::Error::DiscardedOnInsert( - DiscardedOnInsertError {}, - )), + error: Some(mempool_error::Error::DiscardedOnInsert(DiscardedOnInsertError {})), }, MempoolError::PrecheckViolation(violation) => ProtoMempoolError { error: Some(mempool_error::Error::PrecheckViolation(violation.into())), @@ -197,15 +203,17 @@ impl From for ProtoPrecheckViolationError { ), } } - PrecheckViolation::ExistingSenderWithInitCode(addr) => ProtoPrecheckViolationError { - violation: Some( - precheck_violation_error::Violation::ExistingSenderWithInitCode( - ExistingSenderWithInitCode { - sender_address: addr.as_bytes().to_vec(), - }, + PrecheckViolation::ExistingSenderWithInitCode(addr) => { + ProtoPrecheckViolationError { + violation: Some( + precheck_violation_error::Violation::ExistingSenderWithInitCode( + ExistingSenderWithInitCode { + sender_address: addr.as_bytes().to_vec(), + }, + ), ), - ), - }, + } + } PrecheckViolation::FactoryIsNotContract(addr) => ProtoPrecheckViolationError { violation: Some(precheck_violation_error::Violation::FactoryIsNotContract( FactoryIsNotContract { @@ -389,9 +397,9 @@ impl From for ProtoSimulationViolationError { fn from(value: SimulationViolation) -> Self { match value { SimulationViolation::InvalidSignature => ProtoSimulationViolationError { - violation: Some(simulation_violation_error::Violation::InvalidSignature( - InvalidSignature {}, - )), + violation: Some( + simulation_violation_error::Violation::InvalidSignature(InvalidSignature {}) + ), }, SimulationViolation::UnintendedRevertWithMessage(et, reason, maybe_address) => { ProtoSimulationViolationError { @@ -424,26 +432,30 @@ impl From for ProtoSimulationViolationError { entity, contract_addr, precompile_addr, - ) => ProtoSimulationViolationError { - violation: Some( - simulation_violation_error::Violation::UsedForbiddenPrecompile( - UsedForbiddenPrecompile { - entity: Some((&entity).into()), - contract_address: contract_addr.as_bytes().to_vec(), - precompile_address: precompile_addr.as_bytes().to_vec(), - }, + ) => { + ProtoSimulationViolationError { + violation: Some( + simulation_violation_error::Violation::UsedForbiddenPrecompile( + UsedForbiddenPrecompile { + entity: Some((&entity).into()), + contract_address: contract_addr.as_bytes().to_vec(), + precompile_address: precompile_addr.as_bytes().to_vec(), + }, + ), ), - ), - }, - SimulationViolation::FactoryCalledCreate2Twice(addr) => ProtoSimulationViolationError { - violation: Some( - simulation_violation_error::Violation::FactoryCalledCreate2Twice( - FactoryCalledCreate2Twice { - factory_address: addr.as_bytes().to_vec(), - }, + } + } + SimulationViolation::FactoryCalledCreate2Twice(addr) => { + ProtoSimulationViolationError { + violation: Some( + simulation_violation_error::Violation::FactoryCalledCreate2Twice( + FactoryCalledCreate2Twice { + factory_address: addr.as_bytes().to_vec(), + }, + ), ), - ), - }, + } + } SimulationViolation::InvalidStorageAccess(entity, slot) => { ProtoSimulationViolationError { violation: Some(simulation_violation_error::Violation::InvalidStorageAccess( @@ -473,11 +485,13 @@ impl From for ProtoSimulationViolationError { }, )), }, - SimulationViolation::DidNotRevert => ProtoSimulationViolationError { - violation: Some(simulation_violation_error::Violation::DidNotRevert( - DidNotRevert {}, - )), - }, + SimulationViolation::DidNotRevert => { + ProtoSimulationViolationError { + violation: Some( + simulation_violation_error::Violation::DidNotRevert(DidNotRevert {}) + ), + } + } SimulationViolation::WrongNumberOfPhases(num_phases) => ProtoSimulationViolationError { violation: Some(simulation_violation_error::Violation::WrongNumberOfPhases( WrongNumberOfPhases { num_phases }, @@ -519,9 +533,9 @@ impl From for ProtoSimulationViolationError { } } SimulationViolation::CodeHashChanged => ProtoSimulationViolationError { - violation: Some(simulation_violation_error::Violation::CodeHashChanged( - CodeHashChanged {}, - )), + violation: Some( + simulation_violation_error::Violation::CodeHashChanged(CodeHashChanged {}) + ), }, SimulationViolation::AggregatorValidationFailed => ProtoSimulationViolationError { violation: Some( @@ -666,15 +680,15 @@ mod tests { #[test] fn test_simulation_error() { - let error = MempoolError::SimulationViolation(SimulationViolation::UnintendedRevert( - rundler_types::EntityType::Aggregator, - )); + let error = MempoolError::SimulationViolation( + SimulationViolation::UnintendedRevert(rundler_types::EntityType::Aggregator) + ); let proto_error: ProtoMempoolError = error.into(); let error2 = proto_error.try_into().unwrap(); match error2 { - MempoolError::SimulationViolation(SimulationViolation::UnintendedRevert( - rundler_types::EntityType::Aggregator, - )) => {} + MempoolError::SimulationViolation( + SimulationViolation::UnintendedRevert(rundler_types::EntityType::Aggregator) + ) => {} _ => panic!("wrong error type"), } } diff --git a/crates/pool/src/server/remote/server.rs b/crates/pool/src/server/remote/server.rs index a6e5c9302..e90f7acb7 100644 --- a/crates/pool/src/server/remote/server.rs +++ b/crates/pool/src/server/remote/server.rs @@ -113,18 +113,19 @@ impl OpPool for OpPoolImpl { &self, _request: Request, ) -> Result> { - let resp = match self.local_pool.get_supported_entry_points().await { - Ok(entry_points) => GetSupportedEntryPointsResponse { - chain_id: self.chain_id, - entry_points: entry_points - .into_iter() - .map(|ep| ep.as_bytes().to_vec()) - .collect(), - }, - Err(e) => { - return Err(Status::internal(format!("Failed to get entry points: {e}"))); - } - }; + let resp = + match self.local_pool.get_supported_entry_points().await { + Ok(entry_points) => GetSupportedEntryPointsResponse { + chain_id: self.chain_id, + entry_points: entry_points + .into_iter() + .map(|ep| ep.as_bytes().to_vec()) + .collect(), + }, + Err(e) => { + return Err(Status::internal(format!("Failed to get entry points: {e}"))); + } + }; Ok(Response::new(resp)) } @@ -136,16 +137,18 @@ impl OpPool for OpPoolImpl { let proto_op = req .op .ok_or_else(|| Status::invalid_argument("Operation is required in AddOpRequest"))?; - let uo = proto_op.try_into().map_err(|e| { - Status::invalid_argument(format!("Failed to convert to UserOperation: {e}")) - })?; + let uo = proto_op.try_into().map_err( + |e| Status::invalid_argument(format!("Failed to convert to UserOperation: {e}")) + )?; let resp = match self.local_pool.add_op(ep, uo).await { - Ok(hash) => AddOpResponse { - result: Some(add_op_response::Result::Success(AddOpSuccess { - hash: hash.as_bytes().to_vec(), - })), - }, + Ok(hash) => { + AddOpResponse { + result: Some(add_op_response::Result::Success(AddOpSuccess { + hash: hash.as_bytes().to_vec(), + })), + } + } Err(error) => AddOpResponse { result: Some(add_op_response::Result::Failure(error.into())), }, @@ -221,9 +224,7 @@ impl OpPool for OpPoolImpl { let resp = match self.local_pool.remove_entities(ep, entities).await { Ok(_) => RemoveEntitiesResponse { - result: Some(remove_entities_response::Result::Success( - RemoveEntitiesSuccess {}, - )), + result: Some(remove_entities_response::Result::Success(RemoveEntitiesSuccess {})), }, Err(error) => RemoveEntitiesResponse { result: Some(remove_entities_response::Result::Failure(error.into())), @@ -244,15 +245,13 @@ impl OpPool for OpPoolImpl { .iter() .map(|eu| eu.try_into()) .collect::, _>>() - .map_err(|e| { - Status::internal(format!("Failed to convert to proto entity update: {}", e)) - })?; + .map_err( + |e| Status::internal(format!("Failed to convert to proto entity update: {}", e)) + )?; let resp = match self.local_pool.update_entities(ep, entity_updates).await { Ok(_) => UpdateEntitiesResponse { - result: Some(update_entities_response::Result::Success( - UpdateEntitiesSuccess {}, - )), + result: Some(update_entities_response::Result::Success(UpdateEntitiesSuccess {})), }, Err(error) => UpdateEntitiesResponse { result: Some(update_entities_response::Result::Failure(error.into())), @@ -266,16 +265,17 @@ impl OpPool for OpPoolImpl { &self, _request: Request, ) -> Result> { - let resp = match self.local_pool.debug_clear_state().await { - Ok(_) => DebugClearStateResponse { - result: Some(debug_clear_state_response::Result::Success( - DebugClearStateSuccess {}, - )), - }, - Err(error) => DebugClearStateResponse { - result: Some(debug_clear_state_response::Result::Failure(error.into())), - }, - }; + let resp = + match self.local_pool.debug_clear_state().await { + Ok(_) => DebugClearStateResponse { + result: Some( + debug_clear_state_response::Result::Success(DebugClearStateSuccess {}) + ), + }, + Err(error) => DebugClearStateResponse { + result: Some(debug_clear_state_response::Result::Failure(error.into())), + }, + }; Ok(Response::new(resp)) } @@ -311,9 +311,9 @@ impl OpPool for OpPoolImpl { let ep = self.get_entry_point(&req.entry_point)?; let reps = if req.reputations.is_empty() { - return Err(Status::invalid_argument( - "Reputation is required in DebugSetReputationRequest", - )); + return Err( + Status::invalid_argument("Reputation is required in DebugSetReputationRequest") + ); } else { req.reputations }; @@ -322,16 +322,18 @@ impl OpPool for OpPoolImpl { .into_iter() .map(|r| r.try_into()) .collect::, _>>() - .map_err(|e| { - Status::internal(format!("Failed to convert from proto reputation {e}")) - })?; + .map_err( + |e| Status::internal(format!("Failed to convert from proto reputation {e}")), + )?; let resp = match self.local_pool.debug_set_reputations(ep, reps).await { - Ok(_) => DebugSetReputationResponse { - result: Some(debug_set_reputation_response::Result::Success( - DebugSetReputationSuccess {}, - )), - }, + Ok(_) => { + DebugSetReputationResponse { + result: Some(debug_set_reputation_response::Result::Success( + DebugSetReputationSuccess {}, + )), + } + } Err(error) => DebugSetReputationResponse { result: Some(debug_set_reputation_response::Result::Failure(error.into())), }, @@ -356,9 +358,7 @@ impl OpPool for OpPoolImpl { )), }, Err(error) => DebugDumpReputationResponse { - result: Some(debug_dump_reputation_response::Result::Failure( - error.into(), - )), + result: Some(debug_dump_reputation_response::Result::Failure(error.into())), }, }; @@ -385,9 +385,7 @@ impl OpPool for OpPoolImpl { Ok(new_heads) => new_heads, Err(error) => { tracing::error!("Failed to subscribe to new blocks: {error}"); - return Err(Status::internal(format!( - "Failed to subscribe to new blocks: {error}" - ))); + return Err(Status::internal(format!("Failed to subscribe to new blocks: {error}"))); } }; diff --git a/crates/pool/src/task.rs b/crates/pool/src/task.rs index 29b80d16b..53ae2a308 100644 --- a/crates/pool/src/task.rs +++ b/crates/pool/src/task.rs @@ -153,11 +153,12 @@ impl PoolTask { ) -> anyhow::Result> { // Reputation manager - let reputation = Arc::new(HourlyMovingAverageReputation::new( - ReputationParams::bundler_default(), - pool_config.blocklist.clone(), - pool_config.allowlist.clone(), - )); + let reputation = + Arc::new(HourlyMovingAverageReputation::new( + ReputationParams::bundler_default(), + pool_config.blocklist.clone(), + pool_config.allowlist.clone(), + )); // Start reputation manager let reputation_runner = Arc::clone(&reputation); tokio::spawn(async move { reputation_runner.run().await }); diff --git a/crates/provider/src/ethers/entry_point.rs b/crates/provider/src/ethers/entry_point.rs index 23b89d196..51e0d2567 100644 --- a/crates/provider/src/ethers/entry_point.rs +++ b/crates/provider/src/ethers/entry_point.rs @@ -160,11 +160,12 @@ fn get_handle_ops_call( beneficiary: Address, gas: U256, ) -> FunctionCall, M, ()> { - let call = - if ops_per_aggregator.len() == 1 && ops_per_aggregator[0].aggregator == Address::zero() { - entry_point.handle_ops(ops_per_aggregator.swap_remove(0).user_ops, beneficiary) - } else { - entry_point.handle_aggregated_ops(ops_per_aggregator, beneficiary) - }; + let call = if ops_per_aggregator.len() == 1 + && ops_per_aggregator[0].aggregator == Address::zero() + { + entry_point.handle_ops(ops_per_aggregator.swap_remove(0).user_ops, beneficiary) + } else { + entry_point.handle_aggregated_ops(ops_per_aggregator, beneficiary) + }; call.gas(gas) } diff --git a/crates/provider/src/ethers/provider.rs b/crates/provider/src/ethers/provider.rs index 9ddabfe68..62ddd1df7 100644 --- a/crates/provider/src/ethers/provider.rs +++ b/crates/provider/src/ethers/provider.rs @@ -172,11 +172,12 @@ impl Provider for EthersProvider { gas_cap: u64, ) -> ProviderResult { let aggregator = IAggregator::new(aggregator_address, self); - let result = aggregator - .validate_user_op_signature(user_op) - .gas(gas_cap) - .call() - .await; + let result = + aggregator + .validate_user_op_signature(user_op) + .gas(gas_cap) + .call() + .await; match result { Ok(sig) => Ok(AggregatorOut::SuccessWithInfo(AggregatorSimOut { @@ -208,10 +209,11 @@ impl Provider for EthersProvider { .context("should get calldata for entry point handle ops")?; let arb_node = NodeInterface::new(ARBITRUM_NITRO_NODE_INTERFACE_ADDRESS, self); - let gas = arb_node - .gas_estimate_l1_component(entry_point_address, false, data) - .call() - .await?; + let gas = + arb_node + .gas_estimate_l1_component(entry_point_address, false, data) + .call() + .await?; Ok(U256::from(gas.0)) } diff --git a/crates/rpc/src/debug.rs b/crates/rpc/src/debug.rs index e722fceef..5dcbb2592 100644 --- a/crates/rpc/src/debug.rs +++ b/crates/rpc/src/debug.rs @@ -142,13 +142,13 @@ where reputations: Vec, entry_point: Address, ) -> RpcResult { - let _ = self - .pool - .debug_set_reputations( - entry_point, - reputations.into_iter().map(Into::into).collect(), - ) - .await; + let _ = + self.pool + .debug_set_reputations( + entry_point, + reputations.into_iter().map(Into::into).collect(), + ) + .await; Ok("ok".to_string()) } diff --git a/crates/rpc/src/eth/api.rs b/crates/rpc/src/eth/api.rs index ca5f2474d..44d2d3112 100644 --- a/crates/rpc/src/eth/api.rs +++ b/crates/rpc/src/eth/api.rs @@ -188,9 +188,7 @@ where hash: H256, ) -> EthResult> { if hash == H256::zero() { - return Err(EthRpcError::InvalidParams( - "Missing/invalid userOpHash".to_string(), - )); + return Err(EthRpcError::InvalidParams("Missing/invalid userOpHash".to_string())); } // Get event associated with hash (need to check all entry point addresses associated with this API) @@ -251,9 +249,7 @@ where hash: H256, ) -> EthResult> { if hash == H256::zero() { - return Err(EthRpcError::InvalidParams( - "Missing/invalid userOpHash".to_string(), - )); + return Err(EthRpcError::InvalidParams("Missing/invalid userOpHash".to_string())); } // Get event associated with hash (need to check all entry point addresses associated with this API) @@ -411,9 +407,9 @@ where } if !is_ref_user_op(&logs[end_idx]) { - return Err(EthRpcError::Internal(anyhow::anyhow!( - "fatal: no user ops found in tx receipt ({start_idx},{end_idx})" - ))); + return Err(EthRpcError::Internal( + anyhow::anyhow!("fatal: no user ops found in tx receipt ({start_idx},{end_idx})") + )); } let start_idx = if start_idx == 0 { 0 } else { start_idx + 1 }; @@ -424,17 +420,17 @@ where logs: &[Log], user_op_hash: H256, ) -> EthResult> { - let revert_reason_evt: Option = logs - .iter() - .filter(|l| l.topics.len() > 1 && l.topics[1] == user_op_hash) - .map_while(|l| { - UserOperationRevertReasonFilter::decode_log(&RawLog { - topics: l.topics.clone(), - data: l.data.to_vec(), + let revert_reason_evt: Option = + logs.iter() + .filter(|l| l.topics.len() > 1 && l.topics[1] == user_op_hash) + .map_while(|l| { + UserOperationRevertReasonFilter::decode_log(&RawLog { + topics: l.topics.clone(), + data: l.data.to_vec(), + }) + .ok() }) - .ok() - }) - .next(); + .next(); Ok(revert_reason_evt.map(|r| r.revert_reason.to_string())) } @@ -450,9 +446,7 @@ where ) -> EthResult> { // initial call wasn't to an entrypoint, so we need to trace the transaction to find the user operation let trace_options = GethDebugTracingOptions { - tracer: Some(GethDebugTracerType::BuiltInTracer( - GethDebugBuiltInTracerType::CallTracer, - )), + tracer: Some(GethDebugTracerType::BuiltInTracer(GethDebugBuiltInTracerType::CallTracer)), ..Default::default() }; let trace = self diff --git a/crates/rpc/src/eth/error.rs b/crates/rpc/src/eth/error.rs index fad91c4bc..9b5d969ea 100644 --- a/crates/rpc/src/eth/error.rs +++ b/crates/rpc/src/eth/error.rs @@ -207,10 +207,12 @@ impl From for EthRpcError { EntityType::Paymaster, reason, Some(paymaster), - ) => Self::PaymasterValidationRejected(PaymasterValidationRejectedData { - paymaster, - reason, - }), + ) => { + Self::PaymasterValidationRejected(PaymasterValidationRejectedData { + paymaster, + reason, + }) + } SimulationViolation::UnintendedRevertWithMessage(_, reason, _) => { Self::EntryPointValidationRejected(reason) } diff --git a/crates/rpc/src/task.rs b/crates/rpc/src/task.rs index 25e319295..e5732c2ae 100644 --- a/crates/rpc/src/task.rs +++ b/crates/rpc/src/task.rs @@ -116,13 +116,14 @@ where .layer(ProxyGetRequestLayer::new("/health", "system_health")?) .timeout(self.args.rpc_timeout); - let server = ServerBuilder::default() - .set_logger(RpcMetricsLogger) - .set_middleware(service_builder) - .max_connections(self.args.max_connections) - .http_only() - .build(addr) - .await?; + let server = + ServerBuilder::default() + .set_logger(RpcMetricsLogger) + .set_middleware(service_builder) + .max_connections(self.args.max_connections) + .http_only() + .build(addr) + .await?; let handle = server.start(module); info!("Started RPC server"); diff --git a/crates/sim/build.rs b/crates/sim/build.rs index 7447c13c5..1126e94ba 100644 --- a/crates/sim/build.rs +++ b/crates/sim/build.rs @@ -45,9 +45,7 @@ fn run_command( Err(e) => { if let ErrorKind::NotFound = e.kind() { let program = command.get_program().to_str().unwrap(); - Err(format!( - "{program} not installed. See instructions at {install_page_url}" - ))?; + Err(format!("{program} not installed. See instructions at {install_page_url}"))?; } Err(e)? } diff --git a/crates/sim/src/estimation/estimation.rs b/crates/sim/src/estimation/estimation.rs index f095057a0..b3377cc20 100644 --- a/crates/sim/src/estimation/estimation.rs +++ b/crates/sim/src/estimation/estimation.rs @@ -200,9 +200,7 @@ impl GasEstimatorImpl { .await .context("failed to run initial guess")?; if gas_used.success { - Err(anyhow!( - "simulateHandleOp succeeded, but should always revert" - ))?; + Err(anyhow!("simulateHandleOp succeeded, but should always revert"))?; } if let Some(message) = self .entry_point @@ -349,18 +347,14 @@ impl GasEstimatorImpl { { // This should never happen, but if it does, bail so we // don't end up in an infinite loop! - Err(anyhow!( - "estimateCallGas should make progress each time it is called" - ))?; + Err(anyhow!("estimateCallGas should make progress each time it is called"))?; } is_continuation = true; min_gas = min_gas.max(continuation.min_gas); max_gas = max_gas.min(continuation.max_gas); num_rounds += continuation.num_rounds; } else { - Err(anyhow!( - "estimateCallGas revert should be a Result or a Continuation" - ))?; + Err(anyhow!("estimateCallGas revert should be a Result or a Continuation"))?; } } } @@ -624,13 +618,14 @@ mod tests { }); provider.expect_call().returning(|_a, _b| { - let result_data: Bytes = GasUsedResult { - gas_used: U256::from(20000), - success: false, - result: Bytes::new(), - } - .encode() - .into(); + let result_data: Bytes = + GasUsedResult { + gas_used: U256::from(20000), + success: false, + result: Bytes::new(), + } + .encode() + .into(); let json_rpc_error = JsonRpcError { code: -32000, @@ -642,10 +637,11 @@ mod tests { let (estimator, _) = create_estimator(entry, provider); let user_op = demo_user_op(); - let estimation = estimator - .binary_search_verification_gas(&user_op, H256::zero()) - .await - .unwrap(); + let estimation = + estimator + .binary_search_verification_gas(&user_op, H256::zero()) + .await + .unwrap(); let pre_op_gas: U256 = 10000.into(); let gas_used: U256 = 20000.into(); @@ -713,10 +709,7 @@ mod tests { .await .err(); - assert!(matches!( - estimation, - Some(GasEstimationError::RevertInValidation(..)) - )); + assert!(matches!(estimation, Some(GasEstimationError::RevertInValidation(..)))); } #[tokio::test] @@ -754,13 +747,14 @@ mod tests { // the success field should not be true as the // call should always revert provider.expect_call().returning(|_a, _b| { - let result_data: Bytes = GasUsedResult { - gas_used: U256::from(20000), - success: true, - result: Bytes::new(), - } - .encode() - .into(); + let result_data: Bytes = + GasUsedResult { + gas_used: U256::from(20000), + success: true, + result: Bytes::new(), + } + .encode() + .into(); let json_rpc_error = JsonRpcError { code: -32000, @@ -804,13 +798,14 @@ mod tests { }); provider.expect_call().returning(|_a, _b| { - let result_data: Bytes = GasUsedResult { - gas_used: U256::from(20000), - success: false, - result: Bytes::new(), - } - .encode() - .into(); + let result_data: Bytes = + GasUsedResult { + gas_used: U256::from(20000), + success: false, + result: Bytes::new(), + } + .encode() + .into(); let json_rpc_error = JsonRpcError { code: -32000, @@ -853,13 +848,14 @@ mod tests { .returning(|_a, _b, _c, _d, _e, _f| Err(anyhow!("Invalid spoof error"))); provider.expect_call().returning(|_a, _b| { - let result_data: Bytes = GasUsedResult { - gas_used: U256::from(20000), - success: false, - result: Bytes::new(), - } - .encode() - .into(); + let result_data: Bytes = + GasUsedResult { + gas_used: U256::from(20000), + success: false, + result: Bytes::new(), + } + .encode() + .into(); let json_rpc_error = JsonRpcError { code: -32000, @@ -987,16 +983,14 @@ mod tests { let (estimator, _) = create_estimator(entry, provider); let user_op = demo_user_op(); - let estimation = estimator - .estimate_call_gas(&user_op, H256::zero()) - .await - .err() - .unwrap(); - - assert!(matches!( - estimation, - GasEstimationError::RevertInCallWithBytes(_) - )); + let estimation = + estimator + .estimate_call_gas(&user_op, H256::zero()) + .await + .err() + .unwrap(); + + assert!(matches!(estimation, GasEstimationError::RevertInCallWithBytes(_))); } #[tokio::test] @@ -1092,13 +1086,14 @@ mod tests { .expect_get_latest_block_hash() .returning(|| Ok(H256::zero())); provider.expect_call().returning(|_a, _b| { - let result_data: Bytes = GasUsedResult { - gas_used: U256::from(100000), - success: false, - result: Bytes::new(), - } - .encode() - .into(); + let result_data: Bytes = + GasUsedResult { + gas_used: U256::from(100000), + success: false, + result: Bytes::new(), + } + .encode() + .into(); let json_rpc_error = JsonRpcError { code: -32000, @@ -1163,13 +1158,14 @@ mod tests { .expect_get_latest_block_hash() .returning(|| Ok(H256::zero())); provider.expect_call().returning(|_a, _b| { - let result_data: Bytes = GasUsedResult { - gas_used: U256::from(100000), - success: false, - result: Bytes::new(), - } - .encode() - .into(); + let result_data: Bytes = + GasUsedResult { + gas_used: U256::from(100000), + success: false, + result: Bytes::new(), + } + .encode() + .into(); let json_rpc_error = JsonRpcError { code: -32000, @@ -1192,9 +1188,6 @@ mod tests { let user_op = demo_user_op_optional_gas(); let estimation = estimator.estimate_op_gas(user_op).await.err(); - assert!(matches!( - estimation, - Some(GasEstimationError::RevertInValidation(..)) - )); + assert!(matches!(estimation, Some(GasEstimationError::RevertInValidation(..)))); } } diff --git a/crates/sim/src/gas/gas.rs b/crates/sim/src/gas/gas.rs index 494a410bc..bc6875406 100644 --- a/crates/sim/src/gas/gas.rs +++ b/crates/sim/src/gas/gas.rs @@ -372,11 +372,12 @@ where let mut max_oracle = MaxOracle::new(); max_oracle.add(ProviderOracle::new(provider.clone())); - let config = FeeHistoryOracleConfig { - minimum_fee, - percentile: 33.0, - ..Default::default() - }; + let config = + FeeHistoryOracleConfig { + minimum_fee, + percentile: 33.0, + ..Default::default() + }; max_oracle.add(FeeHistoryOracle::new(provider, config)); Arc::new(Box::new(max_oracle)) diff --git a/crates/sim/src/gas/oracle.rs b/crates/sim/src/gas/oracle.rs index 7f35033dc..157e56611 100644 --- a/crates/sim/src/gas/oracle.rs +++ b/crates/sim/src/gas/oracle.rs @@ -327,11 +327,12 @@ mod tests { #[test] fn test_calculate_estimate_from_rewards_small() { - let reward = vec![ - vec![U256::from(300)], - vec![U256::from(100)], - vec![U256::from(200)], - ]; + let reward = + vec![ + vec![U256::from(300)], + vec![U256::from(100)], + vec![U256::from(200)], + ]; let fee = calculate_estimate_from_rewards(&reward); assert_eq!(fee, U256::from(200)); } diff --git a/crates/sim/src/precheck.rs b/crates/sim/src/precheck.rs index 0921ac040..7cdf10af8 100644 --- a/crates/sim/src/precheck.rs +++ b/crates/sim/src/precheck.rs @@ -157,17 +157,13 @@ impl PrecheckerImpl { let len = op.init_code.len(); if len == 0 { if !sender_exists { - violations.push(PrecheckViolation::SenderIsNotContractAndNoInitCode( - op.sender, - )); + violations.push(PrecheckViolation::SenderIsNotContractAndNoInitCode(op.sender)); } } else { if len < 20 { violations.push(PrecheckViolation::InitCodeTooShort(len)); } else if !factory_exists { - violations.push(PrecheckViolation::FactoryIsNotContract( - op.factory().unwrap(), - )) + violations.push(PrecheckViolation::FactoryIsNotContract(op.factory().unwrap())) } if sender_exists { violations.push(PrecheckViolation::ExistingSenderWithInitCode(op.sender)); @@ -213,11 +209,12 @@ impl PrecheckerImpl { // if preVerificationGas is dynamic, then allow for the percentage buffer // and check if the preVerificationGas is at least the minimum. - let min_pre_verification_gas = if chain::is_dynamic_pvg(chain_id) { - math::percent(min_pre_verification_gas, self.settings.fee_accept_percent) - } else { - min_pre_verification_gas - }; + let min_pre_verification_gas = + if chain::is_dynamic_pvg(chain_id) { + math::percent(min_pre_verification_gas, self.settings.fee_accept_percent) + } else { + min_pre_verification_gas + }; if op.pre_verification_gas < min_pre_verification_gas { violations.push(PrecheckViolation::PreVerificationGasTooLow( op.pre_verification_gas, @@ -268,9 +265,7 @@ impl PrecheckerImpl { } = async_data; if !op.paymaster_and_data.is_empty() { let Some(paymaster) = op.paymaster() else { - return Some(PrecheckViolation::PaymasterTooShort( - op.paymaster_and_data.len(), - )); + return Some(PrecheckViolation::PaymasterTooShort(op.paymaster_and_data.len())); }; if !paymaster_exists { return Some(PrecheckViolation::PaymasterIsNotContract(paymaster)); @@ -641,14 +636,15 @@ mod tests { }; async_data.min_pre_verification_gas = 1_000.into(); - let op = UserOperation { - max_fee_per_gas: math::percent(5000, settings.fee_accept_percent).into(), - max_priority_fee_per_gas: get_min_max_priority_fee_per_gas(Chain::Optimism as u64) - - U256::from(1), - pre_verification_gas: 1_000.into(), - call_gas_limit: MIN_CALL_GAS_LIMIT, - ..Default::default() - }; + let op = + UserOperation { + max_fee_per_gas: math::percent(5000, settings.fee_accept_percent).into(), + max_priority_fee_per_gas: get_min_max_priority_fee_per_gas(Chain::Optimism as u64) + - U256::from(1), + pre_verification_gas: 1_000.into(), + call_gas_limit: MIN_CALL_GAS_LIMIT, + ..Default::default() + }; let res = prechecker.check_gas(&op, get_test_async_data()); let mut expected = ArrayVec::::new(); diff --git a/crates/sim/src/simulation/mempool.rs b/crates/sim/src/simulation/mempool.rs index 2e8994367..2a9047856 100644 --- a/crates/sim/src/simulation/mempool.rs +++ b/crates/sim/src/simulation/mempool.rs @@ -312,13 +312,14 @@ mod tests { let addr = Address::random(); let contract = Address::random(); let precompile = Address::random(); - let entry = AllowlistEntry::new( - AllowEntity::Address(addr), - AllowRule::ForbiddenPrecompile { - contract, - precompile, - }, - ); + let entry = + AllowlistEntry::new( + AllowEntity::Address(addr), + AllowRule::ForbiddenPrecompile { + contract, + precompile, + }, + ); let violation = SimulationViolation::UsedForbiddenPrecompile( Entity { @@ -368,13 +369,14 @@ mod tests { }, ); - let violation = SimulationViolation::InvalidStorageAccess( - Entity { - kind: EntityType::Account, - address: entity_addr, - }, - slot, - ); + let violation = + SimulationViolation::InvalidStorageAccess( + Entity { + kind: EntityType::Account, + address: entity_addr, + }, + slot, + ); assert!(entry.is_allowed(&violation)); let violation = SimulationViolation::InvalidStorageAccess( @@ -417,10 +419,11 @@ mod tests { let entry = AllowlistEntry::new(AllowEntity::Address(entity_addr), AllowRule::CallWithValue); - let violation = SimulationViolation::CallHadValue(Entity { - kind: EntityType::Account, - address: entity_addr, - }); + let violation = + SimulationViolation::CallHadValue(Entity { + kind: EntityType::Account, + address: entity_addr, + }); assert!(entry.is_allowed(&violation)); let violation = SimulationViolation::CallHadValue(Entity { @@ -570,76 +573,78 @@ mod tests { let mempool1 = H256::random(); let mempool2 = H256::random(); let contract = Address::random(); - let mempools = HashMap::from([ - (mempool0, MempoolConfig::default()), - ( - mempool1, - MempoolConfig { - allowlist: vec![ - AllowlistEntry::new( - AllowEntity::Type(EntityType::Account), - AllowRule::ForbiddenOpcode { - contract, - opcode: Opcode::GAS, - }, - ), - AllowlistEntry::new( - AllowEntity::Type(EntityType::Account), - AllowRule::ForbiddenOpcode { - contract, - opcode: Opcode::BASEFEE, - }, - ), - ], - }, - ), - ( - mempool2, - MempoolConfig { - allowlist: vec![ - AllowlistEntry::new( - AllowEntity::Type(EntityType::Account), - AllowRule::ForbiddenOpcode { - contract, - opcode: Opcode::BLOCKHASH, - }, - ), - AllowlistEntry::new( - AllowEntity::Type(EntityType::Account), - AllowRule::ForbiddenOpcode { - contract, - opcode: Opcode::GAS, - }, - ), - AllowlistEntry::new( - AllowEntity::Type(EntityType::Account), - AllowRule::ForbiddenOpcode { - contract, - opcode: Opcode::BASEFEE, - }, - ), - ], - }, - ), - ]); - let violations = [ - SimulationViolation::UsedForbiddenOpcode( - Entity { - kind: EntityType::Account, - address: Address::random(), - }, - contract, - ViolationOpCode(Opcode::GAS), - ), - SimulationViolation::UsedForbiddenOpcode( - Entity { - kind: EntityType::Account, - address: Address::random(), - }, - contract, - ViolationOpCode(Opcode::BASEFEE), - ), - ]; + let mempools = + HashMap::from([ + (mempool0, MempoolConfig::default()), + ( + mempool1, + MempoolConfig { + allowlist: vec![ + AllowlistEntry::new( + AllowEntity::Type(EntityType::Account), + AllowRule::ForbiddenOpcode { + contract, + opcode: Opcode::GAS, + }, + ), + AllowlistEntry::new( + AllowEntity::Type(EntityType::Account), + AllowRule::ForbiddenOpcode { + contract, + opcode: Opcode::BASEFEE, + }, + ), + ], + }, + ), + ( + mempool2, + MempoolConfig { + allowlist: vec![ + AllowlistEntry::new( + AllowEntity::Type(EntityType::Account), + AllowRule::ForbiddenOpcode { + contract, + opcode: Opcode::BLOCKHASH, + }, + ), + AllowlistEntry::new( + AllowEntity::Type(EntityType::Account), + AllowRule::ForbiddenOpcode { + contract, + opcode: Opcode::GAS, + }, + ), + AllowlistEntry::new( + AllowEntity::Type(EntityType::Account), + AllowRule::ForbiddenOpcode { + contract, + opcode: Opcode::BASEFEE, + }, + ), + ], + }, + ), + ]); + let violations = + [ + SimulationViolation::UsedForbiddenOpcode( + Entity { + kind: EntityType::Account, + address: Address::random(), + }, + contract, + ViolationOpCode(Opcode::GAS), + ), + SimulationViolation::UsedForbiddenOpcode( + Entity { + kind: EntityType::Account, + address: Address::random(), + }, + contract, + ViolationOpCode(Opcode::BASEFEE), + ), + ]; match match_mempools(&mempools, &violations) { MempoolMatchResult::Matches(mempools) => { diff --git a/crates/sim/src/simulation/simulation.rs b/crates/sim/src/simulation/simulation.rs index c4acfcb60..f393c2323 100644 --- a/crates/sim/src/simulation/simulation.rs +++ b/crates/sim/src/simulation/simulation.rs @@ -179,12 +179,13 @@ where let last_entity = entity_type_from_simulation_phase(tracer_out.phases.len() - 1).unwrap(); if let Ok(failed_op) = FailedOp::decode_hex(revert_data) { - let entity_addr = match last_entity { - EntityType::Factory => factory_address, - EntityType::Paymaster => paymaster_address, - EntityType::Account => Some(sender_address), - _ => None, - }; + let entity_addr = + match last_entity { + EntityType::Factory => factory_address, + EntityType::Paymaster => paymaster_address, + EntityType::Account => Some(sender_address), + _ => None, + }; Err(vec![SimulationViolation::UnintendedRevertWithMessage( last_entity, failed_op.reason, @@ -194,13 +195,14 @@ where let Ok(entry_point_out) = ValidationOutput::decode_hex(revert_data) else { Err(vec![SimulationViolation::UnintendedRevert(last_entity)])? }; - let entity_infos = EntityInfos::new( - factory_address, - sender_address, - paymaster_address, - &entry_point_out, - self.sim_settings, - ); + let entity_infos = + EntityInfos::new( + factory_address, + sender_address, + paymaster_address, + &entry_point_out, + self.sim_settings, + ); let is_unstaked_wallet_creation = entity_infos .get(EntityType::Factory) .filter(|factory| !factory.is_staked) @@ -291,9 +293,9 @@ where for precompile in &phase.forbidden_precompiles_used { let (contract, precompile) = parse_combined_tracer_str(precompile)?; - violations.push(SimulationViolation::UsedForbiddenPrecompile( - entity, contract, precompile, - )); + violations.push( + SimulationViolation::UsedForbiddenPrecompile(entity, contract, precompile) + ); } let mut needs_stake = entity.kind == EntityType::Paymaster && !entry_point_out.return_info.paymaster_context.is_empty(); @@ -352,9 +354,7 @@ where violations.push(SimulationViolation::OutOfGas(entity)); } for &address in &phase.undeployed_contract_accesses { - violations.push(SimulationViolation::AccessedUndeployedContract( - entity, address, - )) + violations.push(SimulationViolation::AccessedUndeployedContract(entity, address)) } } @@ -372,16 +372,15 @@ where let factory = entity_infos.get(EntityType::Factory); match factory { Some(factory) => { - violations.push(SimulationViolation::FactoryCalledCreate2Twice( - factory.address, - )); + violations + .push(SimulationViolation::FactoryCalledCreate2Twice(factory.address)); } None => { // weird case where CREATE2 is called > 1, but there isn't a factory // defined. This should never happen, blame the violation on the entry point. - violations.push(SimulationViolation::FactoryCalledCreate2Twice( - self.entry_point_address, - )); + violations.push( + SimulationViolation::FactoryCalledCreate2Twice(self.entry_point_address) + ); } } } @@ -428,14 +427,15 @@ where violations.push(SimulationViolation::CodeHashChanged) } } - let aggregator = match aggregator_out { - AggregatorOut::NotNeeded => None, - AggregatorOut::SuccessWithInfo(info) => Some(info), - AggregatorOut::ValidationReverted => { - violations.push(SimulationViolation::AggregatorValidationFailed); - None - } - }; + let aggregator = + match aggregator_out { + AggregatorOut::NotNeeded => None, + AggregatorOut::SuccessWithInfo(info) => Some(info), + AggregatorOut::ValidationReverted => { + violations.push(SimulationViolation::AggregatorValidationFailed); + None + } + }; if !violations.is_empty() { return Err(violations.into()); diff --git a/crates/task/src/block_watcher.rs b/crates/task/src/block_watcher.rs index 153352f36..228cd6c6e 100644 --- a/crates/task/src/block_watcher.rs +++ b/crates/task/src/block_watcher.rs @@ -31,12 +31,13 @@ pub async fn wait_for_new_block( poll_interval: Duration, ) -> (H256, Block) { loop { - let block = retry::with_unlimited_retries( - "watch latest block", - || provider.get_block(BlockNumber::Latest), - UnlimitedRetryOpts::default(), - ) - .await; + let block = + retry::with_unlimited_retries( + "watch latest block", + || provider.get_block(BlockNumber::Latest), + UnlimitedRetryOpts::default(), + ) + .await; let Some(block) = block else { error!("Latest block should be present when waiting for new block."); continue; @@ -62,12 +63,13 @@ pub async fn wait_for_new_block_number( poll_interval: Duration, ) -> u64 { loop { - let block_number = retry::with_unlimited_retries( - "watch latest block number", - || provider.get_block_number(), - UnlimitedRetryOpts::default(), - ) - .await; + let block_number = + retry::with_unlimited_retries( + "watch latest block number", + || provider.get_block_number(), + UnlimitedRetryOpts::default(), + ) + .await; if last_block_number < block_number { return block_number; } diff --git a/crates/task/src/task.rs b/crates/task/src/task.rs index ab6c0342b..5dd579bb9 100644 --- a/crates/task/src/task.rs +++ b/crates/task/src/task.rs @@ -38,15 +38,16 @@ pub async fn spawn_tasks_with_shutdown( let shutdown_token = CancellationToken::new(); let mut shutdown_scope = Some(shutdown_scope); - let handles = tasks.into_iter().map(|task| { - let st = shutdown_token.clone(); - let ss = shutdown_scope.clone(); - async move { - let ret = task.run(st).await; - drop(ss); - ret - } - }); + let handles = + tasks.into_iter().map(|task| { + let st = shutdown_token.clone(); + let ss = shutdown_scope.clone(); + async move { + let ret = task.run(st).await; + drop(ss); + ret + } + }); tokio::select! { res = try_join_all(handles) => { error!("Task exited unexpectedly: {res:?}"); diff --git a/crates/types/build.rs b/crates/types/build.rs index 6b124e65b..5cf61afc3 100644 --- a/crates/types/build.rs +++ b/crates/types/build.rs @@ -80,9 +80,7 @@ fn run_command( Err(e) => { if let ErrorKind::NotFound = e.kind() { let program = command.get_program().to_str().unwrap(); - Err(format!( - "{program} not installed. See instructions at {install_page_url}" - ))?; + Err(format!("{program} not installed. See instructions at {install_page_url}"))?; } Err(e)? }