Skip to content

Commit

Permalink
chore: small refactor (hybrid) (#404)
Browse files Browse the repository at this point in the history
* chore: small refactor (hybrid)

* fmt

* lint

* rename hybrid_history.rs

* rename
  • Loading branch information
carneiro-cw authored Mar 19, 2024
1 parent 2d1eb52 commit eac1f9f
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 158 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,41 @@ use std::collections::HashMap;
use std::sync::Arc;

use anyhow::Context;
use indexmap::IndexMap;
use sqlx::types::BigDecimal;
use sqlx::FromRow;
use sqlx::Pool;
use sqlx::Postgres;

use crate::eth::primitives::Account;
use crate::eth::primitives::Address;
use crate::eth::primitives::Block;
use crate::eth::primitives::BlockNumber;
use crate::eth::primitives::Bytes;
use crate::eth::primitives::ExecutionAccountChanges;
use crate::eth::primitives::Hash;
use crate::eth::primitives::LogMined;
use crate::eth::primitives::Nonce;
use crate::eth::primitives::Slot;
use crate::eth::primitives::SlotIndex;
use crate::eth::primitives::SlotValue;
use crate::eth::primitives::StoragePointInTime;
use crate::eth::primitives::TransactionMined;
use crate::eth::primitives::Wei;

#[derive(Debug)]
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
pub struct SlotInfo {
pub value: SlotValue,
}

#[derive(Debug)]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct AccountInfo {
pub balance: Wei,
pub nonce: Nonce,
pub bytecode: Option<Bytes>,
pub slots: HashMap<SlotIndex, SlotInfo>,
}

#[derive(Debug)]
pub struct HybridHistory {
pub hybrid_accounts_slots: HashMap<Address, AccountInfo>,
pub pool: Arc<Pool<Postgres>>,
}

#[derive(FromRow)]
struct AccountRow {
address: Vec<u8>,
Expand All @@ -52,22 +52,19 @@ struct SlotRow {
value: Option<Vec<u8>>,
}

impl HybridHistory {
pub async fn new(pool: Arc<Pool<Postgres>>) -> Result<Self, sqlx::Error> {
// Initialize the structure
let mut history = HybridHistory {
hybrid_accounts_slots: HashMap::new(),
pool,
};

history.load_latest_data().await?;

Ok(history)
}
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct HybridStorageState {
pub accounts: HashMap<Address, AccountInfo>,
pub transactions: HashMap<Hash, TransactionMined>,
pub blocks_by_number: IndexMap<BlockNumber, Arc<Block>>,
pub blocks_by_hash: IndexMap<Hash, Arc<Block>>,
pub logs: Vec<LogMined>,
}

impl HybridStorageState {
//XXX TODO use a fixed block_number during load, in order to avoid sync problem
// e.g other instance moving forward and this query getting incongruous data
async fn load_latest_data(&mut self) -> Result<(), sqlx::Error> {
pub async fn load_latest_data(&mut self, pool: &Pool<Postgres>) -> Result<(), sqlx::Error> {
let account_rows = sqlx::query_as!(
AccountRow,
"
Expand All @@ -83,7 +80,7 @@ impl HybridHistory {
block_number DESC
"
)
.fetch_all(&*self.pool)
.fetch_all(pool)
.await?;

let mut accounts: HashMap<Address, AccountInfo> = HashMap::new();
Expand Down Expand Up @@ -117,7 +114,7 @@ impl HybridHistory {
block_number DESC
"
)
.fetch_all(&*self.pool)
.fetch_all(pool)
.await?;

for slot_row in slot_rows {
Expand All @@ -132,7 +129,7 @@ impl HybridHistory {
}
}

self.hybrid_accounts_slots = accounts;
self.accounts = accounts;

Ok(())
}
Expand All @@ -142,7 +139,7 @@ impl HybridHistory {
for change in changes {
let address = change.address.clone(); // Assuming Address is cloneable and the correct type.

let account_info_entry = self.hybrid_accounts_slots.entry(address).or_insert_with(|| AccountInfo {
let account_info_entry = self.accounts.entry(address).or_insert_with(|| AccountInfo {
balance: Wei::ZERO, // Initialize with default values.
nonce: Nonce::ZERO,
bytecode: None,
Expand Down Expand Up @@ -171,9 +168,15 @@ impl HybridHistory {
Ok(())
}

pub async fn get_slot_at_point(&self, address: &Address, slot_index: &SlotIndex, point_in_time: &StoragePointInTime) -> anyhow::Result<Option<Slot>> {
pub async fn get_slot_at_point(
&self,
address: &Address,
slot_index: &SlotIndex,
point_in_time: &StoragePointInTime,
pool: &Pool<Postgres>,
) -> anyhow::Result<Option<Slot>> {
let slot = match point_in_time {
StoragePointInTime::Present => self.hybrid_accounts_slots.get(address).map(|account_info| {
StoragePointInTime::Present => self.accounts.get(address).map(|account_info| {
let value = account_info.slots.get(slot_index).map(|slot_info| slot_info.value.clone()).unwrap_or_default();
Slot {
index: slot_index.clone(),
Expand All @@ -199,7 +202,7 @@ impl HybridHistory {
slot_index as _,
number as _
)
.fetch_optional(&*self.pool)
.fetch_optional(pool)
.await
.context("failed to select slot")?,
};
Expand Down
Loading

0 comments on commit eac1f9f

Please sign in to comment.