linera_ethereum/
provider.rs

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