nautilus_blockchain/hypersync/
transform.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use hypersync_client::format::Hex;
17use nautilus_core::{UnixNanos, datetime::NANOSECONDS_IN_SECOND};
18use nautilus_model::defi::{block::Block, hex::from_str_hex_to_u64};
19use ustr::Ustr;
20
21/// Converts a HyperSync block format to our internal Block type.
22pub fn transform_hypersync_block(
23    received_block: hypersync_client::simple_types::Block,
24) -> Result<Block, anyhow::Error> {
25    let number = received_block
26        .number
27        .ok_or_else(|| anyhow::anyhow!("Missing block number"))?;
28    let gas_limit = from_str_hex_to_u64(
29        received_block
30            .gas_limit
31            .ok_or_else(|| anyhow::anyhow!("Missing gas limit"))?
32            .encode_hex()
33            .as_str(),
34    )?;
35    let gas_used = from_str_hex_to_u64(
36        received_block
37            .gas_used
38            .ok_or_else(|| anyhow::anyhow!("Missing gas used"))?
39            .encode_hex()
40            .as_str(),
41    )?;
42    let timestamp = from_str_hex_to_u64(
43        received_block
44            .timestamp
45            .ok_or_else(|| anyhow::anyhow!("Missing timestamp"))?
46            .encode_hex()
47            .as_str(),
48    )?;
49
50    Ok(Block::new(
51        received_block
52            .hash
53            .ok_or_else(|| anyhow::anyhow!("Missing hash"))?
54            .to_string(),
55        received_block
56            .parent_hash
57            .ok_or_else(|| anyhow::anyhow!("Missing parent hash"))?
58            .to_string(),
59        number,
60        Ustr::from(
61            received_block
62                .miner
63                .ok_or_else(|| anyhow::anyhow!("Missing miner"))?
64                .to_string()
65                .as_str(),
66        ),
67        gas_limit,
68        gas_used,
69        UnixNanos::new(timestamp * NANOSECONDS_IN_SECOND),
70    ))
71}