Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
saefstroem committed May 10, 2024
2 parents 57bcb64 + f784e61 commit 255ef92
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
7 changes: 3 additions & 4 deletions src/gateway/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ use log4rs::{
};
use reqwest::{Client, Url};
use sled::Tree;
use tokio::sync::Mutex;

use crate::{
common::{get_unix_time_millis, get_unix_time_seconds, DatabaseError},
Expand Down Expand Up @@ -54,7 +53,7 @@ pub type Wei = U256;

// Type alias for the invoice callback function
pub type AsyncCallback =
Arc<Mutex<dyn Fn(Invoice) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>>;
Arc<dyn Fn(Invoice) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;

impl PaymentGateway {
/// Creates a new payment gateway.
Expand Down Expand Up @@ -93,9 +92,9 @@ impl PaymentGateway {

// Wrap the callback in Arc<Mutex<>> to allow sharing across threads and state mutation
// We have to create a pinned box to prevent the future from being moved around in heap memory.
let callback = Arc::new(Mutex::new(move |invoice: Invoice| {
let callback = Arc::new(move |invoice: Invoice| {
Box::pin(callback(invoice)) as Pin<Box<dyn Future<Output = ()> + Send>>
}));
});

// Setup logging
let logfile = FileAppender::builder()
Expand Down
19 changes: 18 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,25 @@ mod tests {
types::{Invoice, PaymentMethod},
};

struct Foo {
bar: std::sync::Mutex<i64>,
}

impl Foo {
async fn increase(&self) {
*self.bar.lock().unwrap() += 1;
}
}

fn setup_test_gateway(db_path: &str) -> PaymentGateway {
async fn callback(_invoice: Invoice) {}
let foo = std::sync::Arc::new(Foo {
bar: Default::default(),
});
let foo_clone = foo.clone();
let callback = move |_| {
let foo = foo_clone.clone();
async move { foo.increase().await }
};
PaymentGateway::new(
"https://123.com",
"0xdac17f958d2ee523a2206206994597c13d831ec7".to_string(),
Expand Down
3 changes: 1 addition & 2 deletions src/poller/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,7 @@ pub async fn poll_payments(gateway: PaymentGateway) {
delete_invoice(&gateway.tree, entry.0).await;
let mut invoice = entry.1;
invoice.paid_at_timestamp = get_unix_time_seconds();
let lock = gateway.config.callback.lock().await;
(*lock)(invoice).await; // Execute callback function
(gateway.config.callback)(invoice).await;// Execute callback function
}
// To prevent rate limitations on certain Web3 RPC's we sleep here for the specified amount.
tokio::time::sleep(std::time::Duration::from_millis(
Expand Down

0 comments on commit 255ef92

Please sign in to comment.