From 726e0fce2802fa9d17e63f687585ed2732ff1a5a Mon Sep 17 00:00:00 2001 From: DogLooksGood Date: Wed, 6 Dec 2023 23:51:19 +0800 Subject: [PATCH] Fix some clippy warnings --- Cargo.lock | 2 +- api/src/effect.rs | 4 +- api/src/event.rs | 2 +- api/src/random.rs | 15 +++-- core/src/context.rs | 27 ++++----- core/src/engine.rs | 5 +- core/src/types/accounts.rs | 2 +- core/src/types/common.rs | 2 + encryptor/src/lib.rs | 2 +- transactor/src/blacklist.rs | 3 +- transactor/src/component/common.rs | 6 +- transactor/src/component/event_bus.rs | 2 +- transactor/src/component/event_loop.rs | 25 ++++---- transactor/src/component/submitter.rs | 8 +-- transactor/src/component/synchronizer.rs | 8 +-- transactor/src/component/wrapped_client.rs | 4 +- transactor/src/context.rs | 1 - transactor/src/frame.rs | 2 +- transactor/src/handle.rs | 35 ++++++------ transactor/src/reg.rs | 5 +- transactor/src/utils.rs | 4 +- transport/src/builder.rs | 2 +- transport/src/facade.rs | 3 +- transport/src/solana.rs | 60 ++++++++++---------- transport/src/solana/nft.rs | 2 +- transport/src/solana/types/state/game.rs | 16 +++--- transport/src/solana/types/state/registry.rs | 2 +- 27 files changed, 115 insertions(+), 134 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 85d5f77a..c3bbfed1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3589,7 +3589,7 @@ dependencies = [ [[package]] name = "race-storage" -version = "0.2.3" +version = "0.2.6" dependencies = [ "anyhow", "base64 0.21.0", diff --git a/api/src/effect.rs b/api/src/effect.rs index b51e6561..0f0c9433 100644 --- a/api/src/effect.rs +++ b/api/src/effect.rs @@ -318,7 +318,7 @@ impl Effect { } pub fn __checkpoint(&mut self) -> Option> { - std::mem::replace(&mut self.checkpoint, None) + self.checkpoint.take() } /// Set error. @@ -332,7 +332,7 @@ impl Effect { /// /// This is an internal function, DO NOT use in game handler. pub fn __take_error(&mut self) -> Option { - std::mem::replace(&mut self.error, None) + self.error.take() } } diff --git a/api/src/event.rs b/api/src/event.rs index fa6be3d3..25b0b718 100644 --- a/api/src/event.rs +++ b/api/src/event.rs @@ -197,7 +197,7 @@ impl std::fmt::Display for Event { Event::DrawTimeout => write!(f, "DrawTimeout"), Event::ActionTimeout { player_addr } => write!(f, "ActionTimeout for {}", player_addr), Event::SecretsReady { random_ids } => { - write!(f, "SecretsReady for {}", format!("{:?}", random_ids)) + write!(f, "SecretsReady for {:?}", random_ids) } Event::ServerLeave { server_addr, diff --git a/api/src/random.rs b/api/src/random.rs index 23259a6c..12b12f2d 100644 --- a/api/src/random.rs +++ b/api/src/random.rs @@ -351,7 +351,7 @@ impl RandomState { size, masks, owners: owners.to_owned(), - options: options.clone(), + options, status, ciphertexts, revealed: HashMap::new(), @@ -466,15 +466,14 @@ impl RandomState { } fn add_secret_share(&mut self, share: Share) { - if self + if !self .secret_shares .iter() - .find(|ss| { + .any(|ss| { ss.from_addr.eq(&share.from_addr) && ss.to_addr.eq(&share.to_addr) && ss.index == share.index }) - .is_none() { self.secret_shares.push(share); } @@ -516,7 +515,7 @@ impl RandomState { from_addr: ss.from_addr.clone(), to_addr: ss.to_addr.clone(), random_id: self.id, - index: ss.index as usize, + index: ss.index, }) .collect() } @@ -530,7 +529,7 @@ impl RandomState { .iter() .filter(|ss| ss.to_addr.is_none()) .fold(HashMap::new(), |mut acc, ss| { - acc.entry(ss.index as usize) + acc.entry(ss.index) .and_modify(|v: &mut Vec| { v.push(ss.secret.as_ref().unwrap().clone()) }) @@ -548,7 +547,7 @@ impl RandomState { .enumerate() .filter_map(|(i, c)| { if matches!(&c.owner, CipherOwner::Assigned(a) if a.eq(addr)) { - Some((i as usize, c.ciphertext.clone())) + Some((i, c.ciphertext.clone())) } else { None } @@ -562,7 +561,7 @@ impl RandomState { .enumerate() .filter_map(|(i, c)| { if c.owner == CipherOwner::Revealed { - Some((i as usize, c.ciphertext.clone())) + Some((i, c.ciphertext.clone())) } else { None } diff --git a/core/src/context.rs b/core/src/context.rs index 61f54d09..ad2a0fb0 100644 --- a/core/src/context.rs +++ b/core/src/context.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use crate::types::GameAccount; +use crate::types::{GameAccount, SettleTransferCheckpoint}; use borsh::{BorshDeserialize, BorshSerialize}; use race_api::decision::DecisionState; use race_api::effect::{Ask, Assign, Effect, Release, Reveal}; @@ -400,7 +400,7 @@ impl GameContext { if id == 0 { return Err(Error::RandomStateNotFound(id)); } - if let Some(rnd_st) = self.random_states.get(id as usize - 1) { + if let Some(rnd_st) = self.random_states.get(id - 1) { Ok(rnd_st) } else { Err(Error::RandomStateNotFound(id)) @@ -408,14 +408,14 @@ impl GameContext { } pub fn get_random_state_unchecked(&self, id: RandomId) -> &RandomState { - &self.random_states[id as usize - 1] + &self.random_states[id - 1] } pub fn get_decision_state_mut(&mut self, id: DecisionId) -> Result<&mut DecisionState> { if id == 0 { return Err(Error::InvalidDecisionId); } - if let Some(st) = self.decision_states.get_mut(id as usize - 1) { + if let Some(st) = self.decision_states.get_mut(id - 1) { Ok(st) } else { Err(Error::InvalidDecisionId) @@ -426,7 +426,7 @@ impl GameContext { if id == 0 { return Err(Error::RandomStateNotFound(id)); } - if let Some(rnd_st) = self.random_states.get_mut(id as usize - 1) { + if let Some(rnd_st) = self.random_states.get_mut(id - 1) { Ok(rnd_st) } else { Err(Error::RandomStateNotFound(id)) @@ -516,8 +516,7 @@ impl GameContext { if self .servers .iter() - .find(|s| s.addr.eq(&server.addr)) - .is_some() + .any(|s| s.addr.eq(&server.addr)) { Err(Error::ServerAlreadyJoined(server.addr.clone())) } else { @@ -690,7 +689,7 @@ impl GameContext { pub fn take_settles_and_transfers( &mut self, - ) -> Result, Vec, Vec)>> { + ) -> Result> { if let Some(checkpoint) = self.get_checkpoint() { let mut settles = None; std::mem::swap(&mut settles, &mut self.settles); @@ -814,11 +813,7 @@ impl GameContext { .list_decision_states() .iter() .filter_map(|st| { - if let Some(a) = st.get_revealed() { - Some((st.id, a.to_owned())) - } else { - None - } + st.get_revealed().map(|a| (st.id, a.to_owned())) }) .collect(); @@ -914,10 +909,8 @@ impl GameContext { self.checkpoint = Some(checkpoint_state); self.settle(settles); self.transfer(transfers); - } else { - if (!settles.is_empty()) || (!transfers.is_empty()) { - return Err(Error::SettleWithoutCheckpoint); - } + } else if (!settles.is_empty()) || (!transfers.is_empty()) { + return Err(Error::SettleWithoutCheckpoint); } if let Some(state) = handler_state { diff --git a/core/src/engine.rs b/core/src/engine.rs index 27414444..8429bbd0 100644 --- a/core/src/engine.rs +++ b/core/src/engine.rs @@ -97,11 +97,10 @@ pub fn general_handle_event( Event::Leave { player_addr } => { if !context.allow_exit { Err(Error::CantLeave) - } else if context + } else if !context .players .iter() - .find(|p| p.addr.eq(player_addr)) - .is_none() + .any(|p| p.addr.eq(player_addr)) { Err(Error::InvalidPlayerAddress) } else { diff --git a/core/src/types/accounts.rs b/core/src/types/accounts.rs index 32de0de0..49f5fdf8 100644 --- a/core/src/types/accounts.rs +++ b/core/src/types/accounts.rs @@ -155,7 +155,7 @@ impl GameAccount { access_version: game_account.access_version, settle_version: game_account.settle_version, max_players: game_account.max_players, - checkpoint: game_account.checkpoint.clone(), + checkpoint: game_account.checkpoint, } } diff --git a/core/src/types/common.rs b/core/src/types/common.rs index 0e8fdedf..87cc4b10 100644 --- a/core/src/types/common.rs +++ b/core/src/types/common.rs @@ -3,6 +3,8 @@ use borsh::{BorshDeserialize, BorshSerialize}; use serde::{Deserialize, Serialize}; pub use race_api::types::*; +pub type SettleTransferCheckpoint = (Vec, Vec, Vec); + #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum ClientMode { Player, diff --git a/encryptor/src/lib.rs b/encryptor/src/lib.rs index 69545aa6..9c291383 100644 --- a/encryptor/src/lib.rs +++ b/encryptor/src/lib.rs @@ -328,7 +328,7 @@ impl EncryptorT for Encryptor { } = signature; // TODO: We should check timestamp here. let message = [message, &u64::to_le_bytes(*timestamp)].concat(); - self.verify_raw(Some(&signer), &message, &signature) + self.verify_raw(Some(signer), &message, signature) } fn apply(&self, secret: &SecretKey, buffer: &mut [u8]) { diff --git a/transactor/src/blacklist.rs b/transactor/src/blacklist.rs index 7d6dadef..59a8cdb9 100644 --- a/transactor/src/blacklist.rs +++ b/transactor/src/blacklist.rs @@ -19,7 +19,6 @@ impl Blacklist { let lines = std::io::BufReader::new(file).lines(); if let Ok(addrs) = lines .into_iter() - .map(|l| l) .collect::, _>>() { return Blacklist { @@ -63,6 +62,6 @@ impl Blacklist { } pub fn contains_addr(&self, addr: &str) -> bool { - self.addrs.iter().find(|a| *a == addr).is_some() + self.addrs.iter().any(|a| *a == addr) } } diff --git a/transactor/src/component/common.rs b/transactor/src/component/common.rs index b58d431f..573908bc 100644 --- a/transactor/src/component/common.rs +++ b/transactor/src/component/common.rs @@ -77,7 +77,7 @@ impl Attachable for PortsHandle { } fn output(&mut self) -> Option> { if self.output_rx.is_some() { - std::mem::replace(&mut self.output_rx, None) + self.output_rx.take() } else { None } @@ -211,9 +211,7 @@ where fn start(&self, context: C) -> PortsHandle { info!("Starting component: {}", self.name()); let (ports, ports_handle_inner) = P::create(); - let join_handle = tokio::spawn(async move { - Self::run(ports, context).await - }); + let join_handle = tokio::spawn(async move { Self::run(ports, context).await }); PortsHandle::from_inner(ports_handle_inner, join_handle) } async fn run(ports: P, context: C) -> CloseReason; diff --git a/transactor/src/component/event_bus.rs b/transactor/src/component/event_bus.rs index 187282dc..4cdb442d 100644 --- a/transactor/src/component/event_bus.rs +++ b/transactor/src/component/event_bus.rs @@ -73,7 +73,7 @@ impl Default for EventBus { while let Some(msg) = rx.recv().await { let txs = attached_txs.lock().await; for t in txs.iter() { - if let Err(_) = t.send(msg.clone()).await { + if t.send(msg.clone()).await.is_err() { warn!("Failed to send message"); } } diff --git a/transactor/src/component/event_loop.rs b/transactor/src/component/event_loop.rs index a64d4ed6..6aa6879a 100644 --- a/transactor/src/component/event_loop.rs +++ b/transactor/src/component/event_loop.rs @@ -14,7 +14,6 @@ use crate::frame::EventFrame; use crate::utils::addr_shorthand; use race_core::types::{ClientMode, GameAccount}; - fn log_execution_context(ctx: &GameContext, evt: &Event) { info!("Execution context"); info!("===== State ====="); @@ -48,7 +47,7 @@ async fn handle( ) -> Option { info!( "{} Handle event: {}", - addr_shorthand(&game_context.get_game_addr()), + addr_shorthand(game_context.get_game_addr()), event ); @@ -77,7 +76,7 @@ async fn handle( ports .send(EventFrame::ContextUpdated { - context: game_context.clone(), + context: Box::new(game_context.clone()), }) .await; @@ -85,7 +84,7 @@ async fn handle( if let Some(effects) = effects { info!( "{} Send settlements: {:?}", - addr_shorthand(&game_context.get_game_addr()), + addr_shorthand(game_context.get_game_addr()), effects ); ports @@ -101,10 +100,10 @@ async fn handle( Err(e) => { warn!( "{} Handle event error: {}", - addr_shorthand(&game_context.get_game_addr()), + addr_shorthand(game_context.get_game_addr()), e.to_string() ); - log_execution_context(&game_context, &event); + log_execution_context(game_context, &event); match e { Error::WasmExecutionError(_) | Error::WasmMemoryOverflow => { return Some(CloseReason::Fault(e)) @@ -113,7 +112,7 @@ async fn handle( } } } - return None; + None } /// Take the event from clients or the pending dispatched event. @@ -241,13 +240,11 @@ impl Component for EventLoop { if matches!(event, Event::Shutdown) { ports.send(EventFrame::Shutdown).await; return CloseReason::Complete; - } else { - if let Some(close_reason) = - handle(&mut handler, &mut game_context, event, &ports, ctx.mode).await - { - ports.send(EventFrame::Shutdown).await; - return close_reason; - } + } else if let Some(close_reason) = + handle(&mut handler, &mut game_context, event, &ports, ctx.mode).await + { + ports.send(EventFrame::Shutdown).await; + return close_reason; } } EventFrame::Shutdown => { diff --git a/transactor/src/component/submitter.rs b/transactor/src/component/submitter.rs index efac9b1e..b8c35ff5 100644 --- a/transactor/src/component/submitter.rs +++ b/transactor/src/component/submitter.rs @@ -24,7 +24,7 @@ fn squash_settles(mut prev: SettleParams, next: SettleParams) -> SettleParams { } = next; prev.settles.extend(settles); prev.transfers.extend(transfers); - return SettleParams { + SettleParams { addr, settles: prev.settles, transfers: prev.transfers, @@ -33,7 +33,7 @@ fn squash_settles(mut prev: SettleParams, next: SettleParams) -> SettleParams { // Use the old settle_version settle_version: prev.settle_version, next_settle_version: prev.next_settle_version + 1, - }; + } } /// Read at most 3 settle events from channel. @@ -65,7 +65,7 @@ async fn read_settle_params(rx: &mut mpsc::Receiver) -> Vec for Submitter { join_handle.await.unwrap_or_else(|e| { CloseReason::Fault(Error::InternalError(format!( "Submitter await join handle error: {}", - e.to_string() + e ))) }) } diff --git a/transactor/src/component/synchronizer.rs b/transactor/src/component/synchronizer.rs index 0a039d15..061d2d4a 100644 --- a/transactor/src/component/synchronizer.rs +++ b/transactor/src/component/synchronizer.rs @@ -61,7 +61,7 @@ impl Component for GameSynchronizer { loop { let state = ctx .transport - .get_game_account(&ctx.game_addr, mode.clone()) + .get_game_account(&ctx.game_addr, mode) .await; if ports.is_tx_closed() { @@ -98,7 +98,7 @@ impl Component for GameSynchronizer { let frame = EventFrame::TxState { tx_state }; // When other channels are closed - if let Err(_) = ports.try_send(frame).await { + if ports.try_send(frame).await.is_err() { return CloseReason::Complete; } } @@ -149,7 +149,7 @@ impl Component for GameSynchronizer { }; // When other channels are closed - if let Err(_) = ports.try_send(frame).await { + if ports.try_send(frame).await.is_err() { return CloseReason::Complete; } } @@ -166,7 +166,7 @@ impl Component for GameSynchronizer { let frame = EventFrame::TxState { tx_state }; // When other channels are closed - if let Err(_) = ports.try_send(frame).await { + if ports.try_send(frame).await.is_err() { return CloseReason::Complete; } mode = QueryMode::Confirming; diff --git a/transactor/src/component/wrapped_client.rs b/transactor/src/component/wrapped_client.rs index 2dce7ca7..ab7ebc71 100644 --- a/transactor/src/component/wrapped_client.rs +++ b/transactor/src/component/wrapped_client.rs @@ -178,7 +178,7 @@ mod tests { .mask("transactor".to_string(), vec![vec![0], vec![0], vec![0]]) .unwrap(); - let event_frame = EventFrame::ContextUpdated { context: ctx }; + let event_frame = EventFrame::ContextUpdated { context: Box::new(ctx) }; handle.send_unchecked(event_frame).await; println!("before read event"); @@ -206,7 +206,7 @@ mod tests { let rid = ctx.init_random_state(random).unwrap(); println!("random inited"); - let event_frame = EventFrame::ContextUpdated { context: ctx }; + let event_frame = EventFrame::ContextUpdated { context: Box::new(ctx) }; handle.send_unchecked(event_frame).await; println!("before read event"); diff --git a/transactor/src/context.rs b/transactor/src/context.rs index 995c1863..96c0c3fa 100644 --- a/transactor/src/context.rs +++ b/transactor/src/context.rs @@ -96,7 +96,6 @@ impl ApplicationContext { self.encryptor .export_public_key(None) .expect("Export public key failed") - .clone() } pub fn verify(&self, arg: &[u8], signature: &Signature) -> Result<()> { diff --git a/transactor/src/frame.rs b/transactor/src/frame.rs index 6a51a6db..bf7c9b9c 100644 --- a/transactor/src/frame.rs +++ b/transactor/src/frame.rs @@ -64,7 +64,7 @@ pub enum EventFrame { settle_version: u64, }, ContextUpdated { - context: GameContext, + context: Box, }, Vote { votee: String, diff --git a/transactor/src/handle.rs b/transactor/src/handle.rs index f4c3eb0a..ece7e9a3 100644 --- a/transactor/src/handle.rs +++ b/transactor/src/handle.rs @@ -39,30 +39,30 @@ impl TransactorHandle { game_account.addr ); - let game_context = GameContext::try_new(&game_account)?; - let handler = WrappedHandler::load_by_bundle(&bundle_account, encryptor.clone()).await?; + let game_context = GameContext::try_new(game_account)?; + let handler = WrappedHandler::load_by_bundle(bundle_account, encryptor.clone()).await?; let event_bus = EventBus::default(); - let (broadcaster, broadcaster_ctx) = Broadcaster::init(&game_account); + let (broadcaster, broadcaster_ctx) = Broadcaster::init(game_account); let mut broadcaster_handle = broadcaster.start(broadcaster_ctx); let (event_loop, event_loop_ctx) = EventLoop::init(handler, game_context, ClientMode::Transactor); let mut event_loop_handle = event_loop.start(event_loop_ctx); - let (submitter, submitter_ctx) = Submitter::init(&game_account, transport.clone()); + let (submitter, submitter_ctx) = Submitter::init(game_account, transport.clone()); let mut submitter_handle = submitter.start(submitter_ctx); let (synchronizer, synchronizer_ctx) = - GameSynchronizer::init(transport.clone(), &game_account); + GameSynchronizer::init(transport.clone(), game_account); let mut connection = LocalConnection::new(encryptor.clone()); event_bus.attach(&mut connection).await; let (client, client_ctx) = WrappedClient::init( - &server_account, - &game_account, + server_account, + game_account, transport.clone(), encryptor, Arc::new(connection), @@ -119,15 +119,15 @@ impl ValidatorHandle { "Start game handle for {} with Validator mode", game_account.addr ); - let game_context = GameContext::try_new(&game_account)?; - let handler = WrappedHandler::load_by_bundle(&bundle_account, encryptor.clone()).await?; + let game_context = GameContext::try_new(game_account)?; + let handler = WrappedHandler::load_by_bundle(bundle_account, encryptor.clone()).await?; let transactor_addr = game_account .transactor_addr .as_ref() .ok_or(Error::GameNotServed)?; let transactor_account = transport - .get_server_account(&transactor_addr) + .get_server_account(transactor_addr) .await? .ok_or(Error::CantFindTransactor)?; @@ -152,8 +152,8 @@ impl ValidatorHandle { let mut subscriber_handle = subscriber.start(subscriber_context); let (client, client_ctx) = WrappedClient::init( - &server_account, - &game_account, + server_account, + game_account, transport.clone(), encryptor, connection, @@ -246,7 +246,7 @@ impl Handle { )) } } else { - return Err(Error::GameNotServed); + Err(Error::GameNotServed) } } @@ -272,16 +272,13 @@ impl Handle { if handles.is_empty() { panic!("Some where else is waiting"); } - let handles = std::mem::replace(handles, vec![]); + let handles = std::mem::take(handles); tokio::spawn(async move { let mut close_reason = CloseReason::Complete; for h in handles.into_iter() { let cr = h.wait().await; - match cr { - CloseReason::Fault(_) => { - close_reason = cr - } - _ => () + if let CloseReason::Fault(_) = cr { + close_reason = cr } } close_reason diff --git a/transactor/src/reg.rs b/transactor/src/reg.rs index 4d59f9ec..5c780321 100644 --- a/transactor/src/reg.rs +++ b/transactor/src/reg.rs @@ -68,11 +68,10 @@ pub async fn start_reg_task(context: &ApplicationContext) { transport.get_game_account(&game_reg.addr, mode).await { // We will keep registering until we become the transactor. - if game_account + if !game_account .servers .iter() - .find(|s| s.addr.eq(&server_addr)) - .is_none() + .any(|s| s.addr.eq(&server_addr)) { let server_account = transport.get_server_account(&server_addr).await.unwrap(); diff --git a/transactor/src/utils.rs b/transactor/src/utils.rs index 852d7b70..141946a9 100644 --- a/transactor/src/utils.rs +++ b/transactor/src/utils.rs @@ -7,9 +7,9 @@ pub fn base64_encode(data: &[u8]) -> String { pub fn base64_decode(data: &str) -> Result, race_api::error::Error> { let engine = base64::engine::general_purpose::STANDARD; - Ok(engine + engine .decode(data) - .map_err(|_| race_api::error::Error::DeserializeError)?) + .map_err(|_| race_api::error::Error::DeserializeError) } pub fn addr_shorthand(addr: &str) -> String { diff --git a/transport/src/builder.rs b/transport/src/builder.rs index ee01142e..69017c13 100644 --- a/transport/src/builder.rs +++ b/transport/src/builder.rs @@ -62,7 +62,7 @@ impl TransportBuilder { .keyfile .clone(), ); - self.skip_preflight = config.solana.as_ref().and_then(|c| c.skip_preflight.clone()); + self.skip_preflight = config.solana.as_ref().and_then(|c| c.skip_preflight); } ChainType::Bnb => { self.rpc = Some( diff --git a/transport/src/facade.rs b/transport/src/facade.rs index 1e94f4ae..f017f2c5 100644 --- a/transport/src/facade.rs +++ b/transport/src/facade.rs @@ -114,8 +114,7 @@ impl TransportT for FacadeTransport { if game_account .votes .iter() - .find(|v| v.voter.eq(¶ms.voter_addr)) - .is_some() + .any(|v| v.voter.eq(¶ms.voter_addr)) { Err(Error::DuplicatedVote) } else { diff --git a/transport/src/solana.rs b/transport/src/solana.rs index c5dd59b7..b00e7428 100755 --- a/transport/src/solana.rs +++ b/transport/src/solana.rs @@ -122,7 +122,7 @@ impl TransportT for SolanaTransport { .map_err(|e| TransportError::InstructionCreationError(e.to_string()))?; let create_game_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, &RaceInstruction::CreateGameAccount { params: params.into(), }, @@ -162,13 +162,13 @@ impl TransportT for SolanaTransport { let game_state = self .internal_get_game_state(&game_account_pubkey, mode) .await?; - let stake_account_pubkey = game_state.stake_account.clone(); + let stake_account_pubkey = game_state.stake_account; let (pda, _bump_seed) = Pubkey::find_program_address(&[&game_account_pubkey.to_bytes()], &self.program_id); let close_game_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, &RaceInstruction::CloseGameAccount, vec![ AccountMeta::new(payer_pubkey, true), @@ -217,7 +217,7 @@ impl TransportT for SolanaTransport { ); let init_or_update_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, &RaceInstruction::RegisterServer { params: params.into(), }, @@ -254,12 +254,12 @@ impl TransportT for SolanaTransport { .internal_get_game_state(&game_account_pubkey, mode) .await?; - let mint_pubkey = game_state.token_mint.clone(); + let mint_pubkey = game_state.token_mint; let payer_ata = get_associated_token_address(&payer_pubkey, &mint_pubkey); let is_wsol = mint_pubkey == spl_token::native_mint::id(); - let stake_account_pubkey = game_state.stake_account.clone(); + let stake_account_pubkey = game_state.stake_account; let (pda, _bump_seed) = Pubkey::find_program_address(&[game_account_pubkey.as_ref()], &self.program_id); @@ -310,7 +310,7 @@ impl TransportT for SolanaTransport { } let join_game_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, &RaceInstruction::JoinGame { params: params.into(), }, @@ -349,7 +349,7 @@ impl TransportT for SolanaTransport { .map_err(|_| TransportError::AddressCreationFailed)?; let serve_game_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, &RaceInstruction::ServeGame { params: params.into(), }, @@ -387,7 +387,7 @@ impl TransportT for SolanaTransport { println!( "Profile account pubkey: {}", - profile_account_pubkey.to_string() + profile_account_pubkey ); let mut ixs = Vec::new(); @@ -406,13 +406,13 @@ impl TransportT for SolanaTransport { } let pfp_pubkey = if let Some(ref pfp) = ¶ms.pfp { - Self::parse_pubkey(&pfp)? + Self::parse_pubkey(pfp)? } else { system_program::id() }; let init_profile_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, &RaceInstruction::CreatePlayerProfile { params: params.into(), }, @@ -508,7 +508,7 @@ impl TransportT for SolanaTransport { ]; let publish_game_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, &RaceInstruction::PublishGame { params: params.into(), }, @@ -569,7 +569,7 @@ impl TransportT for SolanaTransport { let mut accounts = vec![ AccountMeta::new_readonly(payer_pubkey, true), AccountMeta::new(Pubkey::from_str(&addr).unwrap(), false), - AccountMeta::new(game_state.stake_account.clone(), false), + AccountMeta::new(game_state.stake_account, false), AccountMeta::new_readonly(pda, false), AccountMeta::new_readonly(recipient_account_pubkey, false), AccountMeta::new_readonly(spl_token::id(), false), @@ -628,7 +628,7 @@ impl TransportT for SolanaTransport { let set_cu_limit_ix = ComputeBudgetInstruction::set_compute_unit_limit(1200000); - let settle_ix = Instruction::new_with_borsh(self.program_id.clone(), ¶ms, accounts); + let settle_ix = Instruction::new_with_borsh(self.program_id, ¶ms, accounts); let message = Message::new(&[set_cu_limit_ix, settle_ix], Some(&payer.pubkey())); let mut tx = Transaction::new_unsigned(message); @@ -653,7 +653,7 @@ impl TransportT for SolanaTransport { &self.program_id, ); let create_registry_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, &RaceInstruction::CreateRegistry { params: params.into(), }, @@ -669,7 +669,7 @@ impl TransportT for SolanaTransport { ); let blockhash = self.get_blockhash()?; let mut tx = Transaction::new_unsigned(message); - tx.sign(&[&payer, ®istry_account], blockhash); + tx.sign(&[payer, ®istry_account], blockhash); self.send_transaction(tx)?; let addr = registry_account_pubkey.to_string(); Ok(addr) @@ -683,7 +683,7 @@ impl TransportT for SolanaTransport { let cap_pubkey = if let Some(addr) = params.cap_addr.as_ref() { Self::parse_pubkey(addr)? } else { - payer_pubkey.clone() + payer_pubkey }; let mut used_id = Vec::new(); let mut init_token_accounts_ixs = Vec::new(); @@ -716,7 +716,7 @@ impl TransportT for SolanaTransport { let stake_account = Keypair::new(); let stake_addr = stake_account.pubkey(); - account_metas.push(AccountMeta::new_readonly(stake_addr.clone(), false)); + account_metas.push(AccountMeta::new_readonly(stake_addr, false)); let token_mint_pubkey = Self::parse_pubkey(&slot.token_addr)?; @@ -761,7 +761,7 @@ impl TransportT for SolanaTransport { } let create_recipient_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, &RaceInstruction::CreateRecipient { params: IxCreateRecipientParams { slots }, }, @@ -815,7 +815,7 @@ impl TransportT for SolanaTransport { ]; let register_game_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, &RaceInstruction::RegisterGame, // TODO: add is_hidden accounts, ); @@ -842,7 +842,7 @@ impl TransportT for SolanaTransport { ]; let unregister_game_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, // TODO: add is_hidden param? &RaceInstruction::UnregisterGame, accounts, @@ -921,12 +921,12 @@ impl TransportT for SolanaTransport { let stake_addrs: Vec = recipient_state .slots .iter() - .map(|s| s.stake_addr.clone()) + .map(|s| s.stake_addr) .collect(); let mut recipient_account = recipient_state.into_account(addr); // Add amount information by querying stake accounts - for i in 0..(stake_addrs.len()) { - tracing::info!("Check stake account: {}", &stake_addrs[i]); + for (i, stake_addr) in stake_addrs.iter().enumerate() { + tracing::info!("Check stake account: {}", stake_addr); let mut slot = recipient_account .slots .get_mut(i) @@ -935,7 +935,7 @@ impl TransportT for SolanaTransport { ))?; let token_data = self.client - .get_account_data(&stake_addrs[i]) + .get_account_data(stake_addr) .or(Err(Error::TransportError( "Cannot get the state of stake account".into(), )))?; @@ -1008,7 +1008,7 @@ impl TransportT for SolanaTransport { } let recipient_claim_ix = Instruction::new_with_borsh( - self.program_id.clone(), + self.program_id, &RaceInstruction::RecipientClaim, account_metas, ); @@ -1120,7 +1120,7 @@ impl SolanaTransport { }; let game_account = self .client - .get_account_with_commitment(&game_account_pubkey, commitment) + .get_account_with_commitment(game_account_pubkey, commitment) .map_err(|e| TransportError::AccountNotFound(e.to_string()))? .value .ok_or(TransportError::AccountNotFound("".to_string()))?; @@ -1138,7 +1138,7 @@ impl SolanaTransport { ) -> TransportResult { let data = self .client - .get_account_data(&recipient_account_pubkey) + .get_account_data(recipient_account_pubkey) .or(Err(TransportError::RecipientAccountNotFound))?; RecipientState::deserialize(&mut data.as_slice()) .map_err(|_| TransportError::RecipientStateDeserializeError) @@ -1168,7 +1168,7 @@ impl SolanaTransport { player_pubkey: &Pubkey, ) -> TransportResult { let profile_pubkey = - Pubkey::create_with_seed(&player_pubkey, PLAYER_PROFILE_SEED, &self.program_id) + Pubkey::create_with_seed(player_pubkey, PLAYER_PROFILE_SEED, &self.program_id) .map_err(|_| TransportError::AddressCreationFailed)?; let data = self @@ -1188,7 +1188,7 @@ impl SolanaTransport { ) -> TransportResult { let data = self .client - .get_account_data(®istry_account_pubkey) + .get_account_data(registry_account_pubkey) .or(Err(TransportError::RegistryAccountDataNotFound))?; RegistryState::deserialize(&mut data.as_slice()) diff --git a/transport/src/solana/nft.rs b/transport/src/solana/nft.rs index 29034120..d8e81385 100644 --- a/transport/src/solana/nft.rs +++ b/transport/src/solana/nft.rs @@ -41,7 +41,7 @@ pub async fn fetch_wasm_from_game_bundle(uri: &str) -> TransportResult> .to_vec(); Ok(wasm_bytes) } else { - return Err(TransportError::MetadataDeserializeError); + Err(TransportError::MetadataDeserializeError) } } diff --git a/transport/src/solana/types/state/game.rs b/transport/src/solana/types/state/game.rs index 47993ccd..b0b79c20 100644 --- a/transport/src/solana/types/state/game.rs +++ b/transport/src/solana/types/state/game.rs @@ -78,15 +78,15 @@ pub struct GameState { // game size pub max_players: u16, // game players - pub players: Box>, + pub players: Vec, // game servers (max: 10) - pub servers: Box>, + pub servers: Vec, // length of game-specific data pub data_len: u32, // serialized data of game-specific data such as sb/bb in Texas Holdem - pub data: Box>, + pub data: Vec, // game votes - pub votes: Box>, + pub votes: Vec, // unlock time pub unlock_time: Option, // the entry type @@ -94,7 +94,7 @@ pub struct GameState { // the recipient account pub recipient_addr: Pubkey, // the checkpoint state - pub checkpoint: Box>, + pub checkpoint: Vec, // the value of access version when checkpoint is set pub checkpoint_access_version: u64, } @@ -137,13 +137,13 @@ impl GameState { transactor_addr: transactor_addr.map(|pk| pk.to_string()), max_players, data_len, - data: *data, + data, deposits: Vec::new(), votes: Vec::new(), unlock_time: None, recipient_addr: recipient_addr.to_string(), - entry_type: entry_type.into(), - checkpoint: *checkpoint, + entry_type, + checkpoint, checkpoint_access_version, } } diff --git a/transport/src/solana/types/state/registry.rs b/transport/src/solana/types/state/registry.rs index 4d8fec6d..b017961f 100644 --- a/transport/src/solana/types/state/registry.rs +++ b/transport/src/solana/types/state/registry.rs @@ -17,5 +17,5 @@ pub struct RegistryState { pub is_private: bool, pub size: u16, // capacity of the registration center pub owner: Pubkey, - pub games: Box>, + pub games: Vec, }