From dd811fd49d56a36da6c3ad8371661faad7f956d2 Mon Sep 17 00:00:00 2001 From: Warm Beer Date: Tue, 10 Dec 2024 16:43:05 +0100 Subject: [PATCH] fix: add rate limit to get market price RPC calls --- autonomi/src/client/quote.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/autonomi/src/client/quote.rs b/autonomi/src/client/quote.rs index 3f48587552..f707076369 100644 --- a/autonomi/src/client/quote.rs +++ b/autonomi/src/client/quote.rs @@ -9,12 +9,16 @@ use super::{data::CostError, Client}; use ant_evm::payment_vault::get_market_price; use ant_evm::{Amount, PaymentQuote, QuotePayment}; +use ant_networking::target_arch::{sleep, Duration, Instant}; use ant_networking::{Network, NetworkError}; use ant_protocol::{storage::ChunkAddress, NetworkAddress}; use libp2p::PeerId; use std::collections::HashMap; use xor_name::XorName; +// set rate limit to 10 req/s +const TIME_BETWEEN_RPC_CALLS_IN_MS: u64 = 100; + /// A quote for a single address pub struct QuoteForAddress(pub(crate) Vec<(PeerId, PaymentQuote, Amount)>); @@ -63,15 +67,34 @@ impl Client { .collect(); let raw_quotes_per_addr = futures::future::try_join_all(futures).await?; + debug!("Fetched store quotes: {raw_quotes_per_addr:?}"); + // choose the quotes to pay for each address let mut quotes_to_pay_per_addr = HashMap::new(); for (content_addr, raw_quotes) in raw_quotes_per_addr { // ask smart contract for the market price let mut prices = vec![]; + + // rate limit + let mut maybe_last_call: Option = None; + for (peer, quote) in raw_quotes { // NB TODO @mick we need to batch this smart contract call + // check if we have to wait for the rate limit + if let Some(last_call) = maybe_last_call { + let elapsed = Instant::now() - last_call; + let time_to_sleep_ms = + TIME_BETWEEN_RPC_CALLS_IN_MS as u128 - elapsed.as_millis(); + if time_to_sleep_ms > 0 { + sleep(Duration::from_millis(time_to_sleep_ms as u64)).await; + } + } + let price = get_market_price(&self.evm_network, quote.quoting_metrics.clone()).await?; + + maybe_last_call = Some(Instant::now()); + prices.push((peer, quote, price)); }