Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added nicer API for Provider mocking #1151

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

PlamenHristov
Copy link

@PlamenHristov PlamenHristov commented Aug 17, 2024

Motivation

I want to able to mock the Provider for Subscription<T> in an easier way like so

...
#[derive(Clone)]
pub struct MockProvider<P, T, N>
{
    inner: Arc<P>,
    from_block: u64,
    to_block: u64,
    _phantom: PhantomData<(T, N)>,
}

...

#[async_trait::async_trait]
impl<P: Provider<T, N> + 'static, T: Transport + Clone, N: Network> Provider<T, N> for MockProvider<P, T, N> {
    fn root(&self) -> &RootProvider<T, N> {
        self.inner.root()
    }
    async fn subscribe_blocks(&self) -> TransportResult<Subscription<Block>> {
        let (tx, rx) = broadcast::channel(100);
        let from_block = self.from_block;
        let to_block = self.to_block;
        let inner = self.inner.clone();

        tokio::spawn(async move {
            for block_number in from_block..=to_block {
                if let Some(block) = inner
                    .get_block_by_number(BlockNumberOrTag::Number(block_number), false)
                    .await
                    .ok()
                {
                    let serialized_block = RawValue::from_string(serde_json::to_string(&block).unwrap()).unwrap();
                    if tx.send(serialized_block).is_err() {
                        break;
                    }
                }
            }
        });

        Ok(rx.into())
    }
}

Solution

impl<T> From<broadcast::Receiver<Box<RawValue>>> for Subscription<T> {
    fn from(rx: broadcast::Receiver<Box<RawValue>>) -> Self {
        Self { inner: RawSubscription { rx, local_id: B256::ZERO }, _pd: std::marker::PhantomData }
    }
}

PR Checklist

  • Added Tests
  • Added Documentation
  • Breaking changes

@PlamenHristov PlamenHristov changed the title Added nicer API for Provider Mocking Added nicer API for Provider mocking Aug 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant