Skip to main content

linera_ethereum/
provider.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A simplified JSON-RPC provider for accessing an Ethereum node over HTTP.
5
6use alloy::transports::http::reqwest::{header::CONTENT_TYPE, Client};
7use async_lock::Mutex;
8use async_trait::async_trait;
9
10use crate::{client::JsonRpcClient, common::EthereumServiceError};
11
12/// The Ethereum endpoint and its provider used for accessing the Ethereum node.
13pub struct EthereumClientSimplified {
14    /// The URL of the Ethereum node.
15    pub url: String,
16    /// The counter used to generate JSON-RPC request IDs.
17    pub id: Mutex<u64>,
18}
19
20#[async_trait]
21impl JsonRpcClient for EthereumClientSimplified {
22    type Error = EthereumServiceError;
23
24    async fn get_id(&self) -> u64 {
25        let mut id = self.id.lock().await;
26        *id += 1;
27        *id
28    }
29
30    async fn request_inner(&self, payload: Vec<u8>) -> Result<Vec<u8>, Self::Error> {
31        let res = Client::new()
32            .post(self.url.clone())
33            .body(payload)
34            .header(CONTENT_TYPE, "application/json")
35            .send()
36            .await?;
37        let body = res.bytes().await?;
38        Ok(body.as_ref().to_vec())
39    }
40}
41
42impl EthereumClientSimplified {
43    /// Connects to an existing Ethereum node and creates an `EthereumClientSimplified`
44    /// if successful.
45    pub fn new(url: String) -> Self {
46        let id = Mutex::new(1);
47        Self { url, id }
48    }
49}