Skip to content
This repository has been archived by the owner on Oct 11, 2024. It is now read-only.

Commit

Permalink
chore: clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
akorchyn committed Sep 9, 2024
1 parent af95aeb commit b440b9e
Show file tree
Hide file tree
Showing 18 changed files with 88 additions and 75 deletions.
2 changes: 1 addition & 1 deletion examples/account_key_pooling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::sync::Arc;
///
/// This is an example of how to use account key pooling to send multiple transactions
/// using different keys.
use near::{signer::Signer, Account, Contract, NetworkConfig, Tokens};
use near::{signer::Signer, Account, NetworkConfig, Tokens};
use near_sdk::NearToken;

#[tokio::main]
Expand Down
2 changes: 1 addition & 1 deletion src/account/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl Account {
)
}

pub fn create_account() -> CreateAccountBuilder {
pub const fn create_account() -> CreateAccountBuilder {
CreateAccountBuilder
}
}
30 changes: 19 additions & 11 deletions src/common/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,18 +91,23 @@ pub type MultiQueryBuilder<T> = MultiRpcBuilder<T, RpcQueryRequest, BlockReferen

pub type ValidatorQueryBuilder<T> = RpcBuilder<T, RpcValidatorRequest, EpochReference>;

pub struct MultiRpcBuilder<ResponseHandler, Method, Reference> {
pub struct MultiRpcBuilder<ResponseHandler, Method, Reference>
where
Reference: Send + Sync,
ResponseHandler: Send + Sync,
{
reference: Reference,
requests: Vec<Arc<dyn QueryCreator<Method, RpcReference = Reference>>>,
requests: Vec<Arc<dyn QueryCreator<Method, RpcReference = Reference> + Send + Sync>>,
handler: ResponseHandler,
}

impl<Handler, Method: RpcMethod, Reference> MultiRpcBuilder<Handler, Method, Reference>
impl<Handler, Method, Reference> MultiRpcBuilder<Handler, Method, Reference>
where
Handler: ResponseHandler<QueryResponse = Method::Response, Method = Method>,
Method: RpcMethod + 'static,
Handler: ResponseHandler<QueryResponse = Method::Response, Method = Method> + Send + Sync,
Method: RpcMethod + Send + Sync + 'static,
Method::Response: Send + Sync,
Method::Error: std::fmt::Display + std::fmt::Debug + Sync + Send,
Reference: Clone,
Reference: Clone + Send + Sync,
{
pub fn new(handler: Handler, reference: Reference) -> Self {
Self {
Expand All @@ -114,7 +119,7 @@ where

pub fn add_query(
mut self,
request: Arc<dyn QueryCreator<Method, RpcReference = Reference>>,
request: Arc<dyn QueryCreator<Method, RpcReference = Reference> + Send + Sync>,
) -> Self {
self.requests.push(request);
self
Expand Down Expand Up @@ -177,9 +182,12 @@ pub struct RpcBuilder<Handler, Method, Reference> {

impl<Handler, Method, Reference> RpcBuilder<Handler, Method, Reference>
where
Handler: ResponseHandler<QueryResponse = Method::Response, Method = Method>,
Handler: ResponseHandler<QueryResponse = Method::Response, Method = Method> + Send + Sync,
Method: RpcMethod + Send + Sync + 'static,
Method::Response: Send + Sync,
Method: RpcMethod + 'static,
Method::Error: std::fmt::Display + std::fmt::Debug + Sync + Send,
Reference: Send + Sync,
{
pub fn new(
request: impl QueryCreator<Method, RpcReference = Reference> + 'static + Send + Sync,
Expand Down Expand Up @@ -285,7 +293,7 @@ where
}

impl<Handlers> MultiQueryHandler<Handlers> {
pub fn new(handlers: Handlers) -> Self {
pub const fn new(handlers: Handlers) -> Self {
Self { handlers }
}
}
Expand Down Expand Up @@ -334,11 +342,11 @@ where
}

#[derive(Default, Debug, Clone)]
pub struct CallResultHandler<Response>(pub PhantomData<Response>);
pub struct CallResultHandler<Response: Send + Sync>(pub PhantomData<Response>);

impl<Response> ResponseHandler for CallResultHandler<Response>
where
Response: DeserializeOwned,
Response: DeserializeOwned + Send + Sync,
{
type Response = Data<Response>;
type QueryResponse = RpcQueryResponse;
Expand Down
6 changes: 3 additions & 3 deletions src/common/secret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ where
self
}

pub fn word_count(mut self, word_count: usize) -> Self {
pub const fn word_count(mut self, word_count: usize) -> Self {
self.word_count = Some(word_count);
self
}
Expand Down Expand Up @@ -102,7 +102,7 @@ where
let signer = Signer::seed_phrase_with_hd_path(
master_seed_phrase.clone(),
self.hd_path
.unwrap_or(DEFAULT_HD_PATH.parse().expect("Valid HD path")),
.unwrap_or_else(|| DEFAULT_HD_PATH.parse().expect("Valid HD path")),
self.passphrase,
)?;

Expand All @@ -120,7 +120,7 @@ where
let hd_path = self
.hd_path
.clone()
.unwrap_or(DEFAULT_HD_PATH.parse().expect("Valid HD path"));
.unwrap_or_else(|| DEFAULT_HD_PATH.parse().expect("Valid HD path"));
let passphrase = self.passphrase.clone();
let (seed_phrase, next) = self.generate_seed_phrase()?;

Expand Down
18 changes: 9 additions & 9 deletions src/common/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,24 +47,24 @@ pub enum TransactionableOrSigned<Signed> {
impl<Signed> TransactionableOrSigned<Signed> {
pub fn signed(self) -> Option<Signed> {
match self {
TransactionableOrSigned::Signed((signed, _)) => Some(signed),
TransactionableOrSigned::Transactionable(_) => None,
Self::Signed((signed, _)) => Some(signed),
Self::Transactionable(_) => None,
}
}
}

impl<S> TransactionableOrSigned<S> {
pub fn transactionable(self) -> Box<dyn Transactionable> {
match self {
TransactionableOrSigned::Transactionable(tr) => tr,
TransactionableOrSigned::Signed((_, tr)) => tr,
Self::Transactionable(tr) => tr,
Self::Signed((_, tr)) => tr,
}
}
}

impl From<SignedTransaction> for PrepopulateTransaction {
fn from(tr: SignedTransaction) -> Self {
PrepopulateTransaction {
Self {
signer_id: tr.transaction.signer_id().clone(),
receiver_id: tr.transaction.receiver_id().clone(),
actions: tr.transaction.take_actions(),
Expand Down Expand Up @@ -93,12 +93,12 @@ impl ExecuteSignedTransaction {
ExecuteMetaTransaction::from_box(self.tr.transactionable(), self.signer)
}

pub fn with_retries(mut self, retries: u8) -> Self {
pub const fn with_retries(mut self, retries: u8) -> Self {
self.retries = retries;
self
}

pub fn with_sleep_duration(mut self, sleep_duration: std::time::Duration) -> Self {
pub const fn with_sleep_duration(mut self, sleep_duration: std::time::Duration) -> Self {
self.sleep_duration = sleep_duration;
self
}
Expand Down Expand Up @@ -255,7 +255,7 @@ impl ExecuteMetaTransaction {
}
}

pub fn tx_live_for(mut self, tx_live_for: BlockHeight) -> Self {
pub const fn tx_live_for(mut self, tx_live_for: BlockHeight) -> Self {
self.tx_live_for = Some(tx_live_for);
self
}
Expand Down Expand Up @@ -392,7 +392,7 @@ impl ExecuteMetaTransaction {
}
}

pub fn is_critical_error(
pub const fn is_critical_error(
err: &near_jsonrpc_client::errors::JsonRpcError<
near_jsonrpc_client::methods::broadcast_tx_commit::RpcTransactionError,
>,
Expand Down
16 changes: 8 additions & 8 deletions src/common/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::errors::DecimalNumberParsingError;
/// If the string slice has invalid chars, it will return the error `DecimalNumberParsingError::InvalidNumber`.
///
/// If the whole part of the number has a value more than the `u64` maximum value, it will return the error `DecimalNumberParsingError::LongWhole`.
pub(crate) fn parse_decimal_number(
pub fn parse_decimal_number(
s: &str,
pref_const: u128,
) -> Result<u128, DecimalNumberParsingError> {
Expand Down Expand Up @@ -56,17 +56,17 @@ pub(crate) fn parse_decimal_number(
mod tests {
use super::*;

const TEST: [(u128, &'static str, u128); 6] = [
(129380_000_001u128, "129.380000001", 10u128.pow(9)),
const TEST: [(u128, &str, u128); 6] = [
(129_380_000_001_u128, "129.380000001", 10u128.pow(9)),
(
12938_000_000_100_000_000u128,
12_938_000_000_100_000_000_u128,
"12938000000.1",
10u128.pow(9),
),
(129380_000_001u128, "0.129380000001", 10u128.pow(12)),
(129380_000_001_000u128, "129.380000001000", 10u128.pow(12)),
(9488129380_000_001u128, "9488.129380000001", 10u128.pow(12)),
(129380_000_001u128, "00.129380000001", 10u128.pow(12)),
(129_380_000_001_u128, "0.129380000001", 10u128.pow(12)),
(129_380_000_001_000_u128, "129.380000001000", 10u128.pow(12)),
(9_488_129_380_000_001_u128, "9488.129380000001", 10u128.pow(12)),
(129_380_000_001_u128, "00.129380000001", 10u128.pow(12)),
];

#[test]
Expand Down
2 changes: 1 addition & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl NetworkConfig {
}

pub fn testnet() -> Self {
NetworkConfig {
Self {
network_name: "testnet".to_string(),
rpc_url: "https://archival-rpc.testnet.near.org".parse().unwrap(),
rpc_api_key: None,
Expand Down
10 changes: 5 additions & 5 deletions src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl Contract {
}
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct DeployContractBuilder {
contract: AccountId,
code: Vec<u8>,
Expand Down Expand Up @@ -154,7 +154,7 @@ pub struct CallFunctionBuilder {
}

impl CallFunctionBuilder {
pub fn read_only<Response: DeserializeOwned>(
pub fn read_only<Response: Send + Sync + DeserializeOwned>(
self,
) -> QueryBuilder<CallResultHandler<Response>> {
let request = near_primitives::views::QueryRequest::CallFunction {
Expand Down Expand Up @@ -202,12 +202,12 @@ impl ContractTransactBuilder {
}
}

pub fn gas(mut self, gas: NearGas) -> Self {
pub const fn gas(mut self, gas: NearGas) -> Self {
self.gas = Some(gas);
self
}

pub fn deposit(mut self, deposit: NearToken) -> Self {
pub const fn deposit(mut self, deposit: NearToken) -> Self {
self.deposit = Some(deposit);
self
}
Expand All @@ -228,7 +228,7 @@ impl ContractTransactBuilder {
let tx: ConstructTransaction = if let Some(preaction) = self.pre_action {
Transaction::construct(signer_id, self.contract).add_action(preaction)
} else {
Transaction::construct(signer_id.clone(), self.contract)
Transaction::construct(signer_id, self.contract)
};

tx.add_action(Action::FunctionCall(Box::new(FunctionCallAction {
Expand Down
2 changes: 1 addition & 1 deletion src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ impl From<near_ledger::NEARLedgerError> for LedgerError {
}

#[derive(thiserror::Error, Debug)]
pub enum SecretBuilderkError<E: std::fmt::Debug + std::fmt::Display> {
pub enum SecretBuilderkError<E: std::fmt::Debug> {
#[error("Public key is not available")]
PublicKeyIsNotAvailable,
#[error(transparent)]
Expand Down
9 changes: 6 additions & 3 deletions src/fastnear.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ pub struct StakingResponse {
pools: Vec<StakingPool>,
}

pub struct FastNearBuilder<T: DeserializeOwned, PostProcessed> {
pub struct FastNearBuilder<T: DeserializeOwned + Send + Sync, PostProcessed> {
query: String,
post_process: Box<dyn Fn(T) -> PostProcessed + Send + Sync>,
_response: std::marker::PhantomData<T>,
}

impl<T: DeserializeOwned> FastNearBuilder<T, T> {
impl<T: DeserializeOwned + Send + Sync> FastNearBuilder<T, T> {
pub fn new(query: String) -> Self {
Self {
query,
Expand All @@ -31,7 +31,10 @@ impl<T: DeserializeOwned> FastNearBuilder<T, T> {
}
}

impl<T: DeserializeOwned, PostProcessed> FastNearBuilder<T, PostProcessed> {
impl<T, PostProcessed> FastNearBuilder<T, PostProcessed>
where
T: DeserializeOwned + Send + Sync,
{
pub fn with_postprocess<F>(query: String, func: F) -> Self
where
F: Fn(T) -> PostProcessed + Send + Sync + 'static,
Expand Down
2 changes: 1 addition & 1 deletion src/signer/keystore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl SignerTrait for KeystoreSigner {

// TODO: fix this. Well the search is a bit suboptimal, but it's not a big deal for now
let secret = Self::get_secret_key(&tr.signer_id, &public_key, "mainnet")
.or(Self::get_secret_key(&tr.signer_id, &public_key, "testnet"))
.or_else(|_| Self::get_secret_key(&tr.signer_id, &public_key, "testnet"))
.map_err(|_| SignerError::SecretKeyIsNotAvailable)?;

let mut transaction = Transaction::new_v0(
Expand Down
2 changes: 1 addition & 1 deletion src/signer/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub struct LedgerSigner {
}

impl LedgerSigner {
pub fn new(hd_path: BIP32Path) -> Self {
pub const fn new(hd_path: BIP32Path) -> Self {
Self { hd_path }
}
}
Expand Down
33 changes: 16 additions & 17 deletions src/signer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub struct AccountKeyPair {
}

impl AccountKeyPair {
fn load_access_key_file(path: &Path) -> Result<AccountKeyPair, AccessKeyFileError> {
fn load_access_key_file(path: &Path) -> Result<Self, AccessKeyFileError> {
let data = std::fs::read_to_string(path)?;
Ok(serde_json::from_str(&data)?)
}
Expand Down Expand Up @@ -193,7 +193,7 @@ impl Signer {
}

#[cfg(feature = "ledger")]
pub fn ledger_with_hd_path(hd_path: BIP32Path) -> ledger::LedgerSigner {
pub const fn ledger_with_hd_path(hd_path: BIP32Path) -> ledger::LedgerSigner {
ledger::LedgerSigner::new(hd_path)
}

Expand All @@ -215,12 +215,14 @@ impl Signer {

pub async fn get_public_key(&self) -> Result<PublicKey, SignerError> {
let index = self.current_public_key.fetch_add(1, Ordering::SeqCst);
let pool = self.pool.read().await;
let public_key = pool
.keys()
.nth(index % pool.len())
.ok_or(SignerError::PublicKeyIsNotAvailable)?;
Ok(public_key.clone())
let public_key = {
let pool = self.pool.read().await;
pool.keys()
.nth(index % pool.len())
.ok_or(SignerError::PublicKeyIsNotAvailable)?
.clone()
};
Ok(public_key)
}

pub async fn sign_meta(
Expand All @@ -233,11 +235,9 @@ impl Signer {
) -> Result<SignedDelegateAction, MetaSignError> {
let signer = self.pool.read().await;

let signer = signer
.get(&public_key)
.ok_or(SignerError::PublicKeyIsNotAvailable)?;

signer
.get(&public_key)
.ok_or(SignerError::PublicKeyIsNotAvailable)?
.sign_meta(tr, public_key, nonce, block_hash, max_block_height)
.await
}
Expand All @@ -251,11 +251,10 @@ impl Signer {
) -> Result<SignedTransaction, SignerError> {
let pool = self.pool.read().await;

let signer = pool
.get(&public_key)
.ok_or(SignerError::PublicKeyIsNotAvailable)?;

signer.sign(tr, public_key, nonce, block_hash).await
pool.get(&public_key)
.ok_or(SignerError::PublicKeyIsNotAvailable)?
.sign(tr, public_key, nonce, block_hash)
.await
}
}

Expand Down
Loading

0 comments on commit b440b9e

Please sign in to comment.