Skip to content

Commit

Permalink
fix: add rate limit to get market price RPC calls
Browse files Browse the repository at this point in the history
  • Loading branch information
mickvandijke committed Dec 10, 2024
1 parent 61e9b94 commit 61f0f22
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions autonomi/src/client/quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 2 req/s
const TIME_BETWEEN_RPC_CALLS_IN_MS: u64 = 500;

/// A quote for a single address
pub struct QuoteForAddress(pub(crate) Vec<(PeerId, PaymentQuote, Amount)>);

Expand Down Expand Up @@ -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<Instant> = 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));
}

Expand Down

0 comments on commit 61f0f22

Please sign in to comment.