use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use starknet::core::types::Felt;
use tracing::{debug, warn};
use crate::data::DataSource;
use crate::data::pathfinder::{PathfinderClient, TxByHashData};
use crate::data::types::{
AddressTxSummary, ContractCallSummary, ExecutionStatus, SnReceipt, SnTransaction,
};
use crate::decode::AbiRegistry;
use crate::decode::functions::{RawCall, parse_multicall};
use crate::decode::outside_execution::detect_outside_execution;
use crate::utils::{felt_to_u64, felt_to_u128};
pub fn format_endpoint_names(tx: &SnTransaction, abi_reg: &AbiRegistry) -> String {
let calls = match tx {
SnTransaction::Invoke(i) => parse_multicall(&i.calldata),
_ => return String::new(),
};
format_selector_names(calls.iter().map(|c| c.selector), abi_reg)
}
pub fn tx_called_contracts(tx: &SnTransaction) -> Vec<Felt> {
let calls = match tx {
SnTransaction::Invoke(i) => parse_multicall(&i.calldata),
_ => return Vec::new(),
};
dedupe_preserve_order(calls.into_iter().map(|c| c.contract_address))
}
fn dedupe_preserve_order(items: impl IntoIterator<Item = Felt>) -> Vec<Felt> {
let mut out: Vec<Felt> = Vec::new();
for item in items {
if !out.contains(&item) {
out.push(item);
}
}
out
}
pub fn oe_inner_targets(calls: &[RawCall], abi_reg: &AbiRegistry) -> Vec<Felt> {
let mut out: Vec<Felt> = Vec::new();
for call in calls {
let resolved_name = call
.function_name
.clone()
.or_else(|| abi_reg.get_selector_name(&call.selector));
if let Some((oe, _method)) = detect_outside_execution(call, resolved_name.as_deref()) {
for ic in &oe.inner_calls {
if !out.contains(&ic.contract_address) {
out.push(ic.contract_address);
}
}
}
}
out
}
pub fn format_selector_name_or_hex(selector: &Felt, abi_reg: &AbiRegistry) -> String {
abi_reg.get_selector_name(selector).unwrap_or_else(|| {
let hex = format!("{:#x}", selector);
if hex.len() > 10 {
format!("{}…", &hex[..10])
} else {
hex
}
})
}
pub fn format_selector_names(
selectors: impl Iterator<Item = Felt>,
abi_reg: &AbiRegistry,
) -> String {
let names: Vec<String> = selectors
.map(|sel| format_selector_name_or_hex(&sel, abi_reg))
.collect();
if names.is_empty() {
return String::new();
}
if names.len() <= 3 {
names.join(", ")
} else {
format!("{}, … +{}", names[..3].join(", "), names.len() - 3)
}
}
pub async fn prewarm_abis(addresses: impl IntoIterator<Item = Felt>, abi_reg: &AbiRegistry) {
use futures::stream::StreamExt;
futures::stream::iter(addresses)
.for_each_concurrent(16, |a| async move {
let _ = abi_reg.get_abi_for_address(&a).await;
})
.await;
}
pub async fn resolve_class_hash_at(
address: Felt,
block: u64,
ds: &Arc<dyn DataSource>,
pf: Option<&Arc<PathfinderClient>>,
) -> Option<Felt> {
let mut history = ds.load_cached_class_history(&address);
let reaches_back = history
.last()
.map(|e| e.block_number <= block)
.unwrap_or(false);
let validated_through_target = ds
.load_class_history_max_block(&address)
.map(|max_block| max_block >= block)
.unwrap_or(false);
let cache_covers = reaches_back && validated_through_target;
if !cache_covers && let Some(pf) = pf {
match pf.get_class_history(address).await {
Ok(entries) => {
if !entries.is_empty() {
let latest = ds.latest_block_hint().await.unwrap_or(0);
ds.save_class_history(&address, &entries);
if latest > 0 {
ds.save_class_history_max_block(&address, latest);
}
history = entries;
}
}
Err(e) => {
debug!(address = %format!("{:#x}", address), error = %e, "pf-query class-history fetch failed");
}
}
}
for entry in &history {
if entry.block_number <= block {
if let Ok(felt) = Felt::from_hex(&entry.class_hash) {
return Some(felt);
}
warn!(class_hash = %entry.class_hash, "Bad class_hash hex in class_history");
break;
}
}
match ds.get_class_hash_at(address, block).await {
Ok(ch) => Some(ch),
Err(e) => {
debug!(address = %format!("{:#x}", address), block, error = %e, "RPC get_class_hash_at failed");
None
}
}
}
pub async fn prewarm_abis_at(
addresses: impl IntoIterator<Item = Felt>,
block: u64,
ds: &Arc<dyn DataSource>,
pf: Option<&Arc<PathfinderClient>>,
abi_reg: &AbiRegistry,
) -> HashMap<Felt, Felt> {
let addrs: Vec<Felt> = addresses.into_iter().collect();
let resolutions = futures::future::join_all(
addrs
.iter()
.copied()
.map(|a| async move { (a, resolve_class_hash_at(a, block, ds, pf).await) }),
)
.await;
let mut addr_to_class: HashMap<Felt, Felt> = HashMap::new();
let mut unique_classes: HashSet<Felt> = HashSet::new();
for (addr, class_opt) in resolutions {
if let Some(ch) = class_opt {
addr_to_class.insert(addr, ch);
unique_classes.insert(ch);
}
}
let class_futs: Vec<_> = unique_classes
.iter()
.copied()
.map(|ch| async move {
let _ = abi_reg.get_abi_for_class(&ch).await;
})
.collect();
futures::future::join_all(class_futs).await;
addr_to_class
}
pub fn receipt_status(receipt: Option<&SnReceipt>) -> String {
receipt
.map(|r| match &r.execution_status {
ExecutionStatus::Succeeded => "OK",
ExecutionStatus::Reverted(_) => "REV",
ExecutionStatus::Unknown => "?",
})
.unwrap_or("?")
.to_string()
}
pub fn extract_nonce_tip(tx: &SnTransaction) -> (u64, u64) {
match tx {
SnTransaction::Invoke(i) => (i.nonce.map(|n| felt_to_u64(&n)).unwrap_or(0), i.tip),
SnTransaction::Declare(d) => (0, d.tip),
SnTransaction::DeployAccount(da) => {
(da.nonce.map(|n| felt_to_u64(&n)).unwrap_or(0), da.tip)
}
_ => (0, 0),
}
}
pub fn build_tx_summary(
hash: Felt,
tx: &SnTransaction,
receipt: Option<&SnReceipt>,
block_number: u64,
timestamp: u64,
abi_reg: &AbiRegistry,
) -> AddressTxSummary {
let fee_fri = receipt.map(|r| felt_to_u128(&r.actual_fee)).unwrap_or(0);
let status = receipt_status(receipt);
let (nonce, tip) = extract_nonce_tip(tx);
let calls = match tx {
SnTransaction::Invoke(i) => parse_multicall(&i.calldata),
_ => Vec::new(),
};
let endpoint_names = format_selector_names(calls.iter().map(|c| c.selector), abi_reg);
let mut called_contracts = dedupe_preserve_order(calls.iter().map(|c| c.contract_address));
for addr in oe_inner_targets(&calls, abi_reg) {
if !called_contracts.contains(&addr) {
called_contracts.push(addr);
}
}
AddressTxSummary {
hash,
nonce,
block_number,
timestamp,
endpoint_names,
total_fee_fri: fee_fri,
tip,
tx_type: tx.type_name().to_string(),
status,
sender: Some(tx.sender()),
called_contracts,
}
}
pub fn normalize_pf_tx_type(pf_type: &str) -> String {
if let Some(idx) = pf_type.rfind("_V")
&& pf_type[idx + 2..].chars().all(|c| c.is_ascii_digit())
&& !pf_type[idx + 2..].is_empty()
{
return pf_type[..idx].to_string();
}
pf_type.to_string()
}
pub fn build_tx_summary_from_pf_data(
pf_tx: &TxByHashData,
abi_reg: &AbiRegistry,
) -> Option<AddressTxSummary> {
let hash = Felt::from_hex(&pf_tx.hash).ok()?;
let sender = Felt::from_hex(&pf_tx.sender).ok()?;
let fee_fri = u128::from_str_radix(pf_tx.actual_fee.trim_start_matches("0x"), 16).unwrap_or(0);
let tx_type = normalize_pf_tx_type(&pf_tx.tx_type);
let (endpoint_names, called_contracts) = if tx_type == "INVOKE" {
let calldata: Vec<Felt> = pf_tx
.calldata
.iter()
.filter_map(|h| Felt::from_hex(h).ok())
.collect();
let calls = parse_multicall(&calldata);
let names = format_selector_names(calls.iter().map(|c| c.selector), abi_reg);
let mut contracts = dedupe_preserve_order(calls.iter().map(|c| c.contract_address));
for addr in oe_inner_targets(&calls, abi_reg) {
if !contracts.contains(&addr) {
contracts.push(addr);
}
}
(names, contracts)
} else {
(String::new(), Vec::new())
};
Some(AddressTxSummary {
hash,
nonce: pf_tx.nonce.unwrap_or(0),
block_number: pf_tx.block_number,
timestamp: pf_tx.block_timestamp,
endpoint_names,
total_fee_fri: fee_fri,
tip: pf_tx.tip,
tx_type,
status: pf_tx.status.clone(),
sender: Some(sender),
called_contracts,
})
}
pub fn pf_tx_target_addresses(pf_tx: &TxByHashData) -> Vec<Felt> {
if normalize_pf_tx_type(&pf_tx.tx_type) != "INVOKE" {
return Vec::new();
}
let calldata: Vec<Felt> = pf_tx
.calldata
.iter()
.filter_map(|h| Felt::from_hex(h).ok())
.collect();
dedupe_preserve_order(
parse_multicall(&calldata)
.into_iter()
.map(|c| c.contract_address),
)
}
pub async fn backfill_timestamps(
summaries: &mut [AddressTxSummary],
ds: &Arc<dyn DataSource>,
pf: Option<&Arc<PathfinderClient>>,
) {
let blocks_needing_ts: HashSet<u64> = summaries
.iter()
.filter(|s| s.timestamp == 0 && s.block_number > 0)
.map(|s| s.block_number)
.collect();
if blocks_needing_ts.is_empty() {
return;
}
let ts_map = fetch_block_timestamps(blocks_needing_ts, ds, pf).await;
for s in summaries.iter_mut() {
if s.timestamp == 0
&& let Some(&ts) = ts_map.get(&s.block_number)
{
s.timestamp = ts;
}
}
}
pub async fn backfill_call_timestamps(
calls: &mut [ContractCallSummary],
ds: &Arc<dyn DataSource>,
pf: Option<&Arc<PathfinderClient>>,
) {
let blocks_needing_ts: HashSet<u64> = calls
.iter()
.filter(|c| c.timestamp == 0 && c.block_number > 0)
.map(|c| c.block_number)
.collect();
if blocks_needing_ts.is_empty() {
return;
}
let ts_map = fetch_block_timestamps(blocks_needing_ts, ds, pf).await;
for c in calls.iter_mut() {
if c.timestamp == 0
&& let Some(&ts) = ts_map.get(&c.block_number)
{
c.timestamp = ts;
}
}
}
pub(super) async fn fetch_block_timestamps(
block_numbers: HashSet<u64>,
ds: &Arc<dyn DataSource>,
pf: Option<&Arc<PathfinderClient>>,
) -> HashMap<u64, u64> {
use futures::stream::{self, StreamExt};
let mut ts_map: HashMap<u64, u64> = HashMap::new();
if let Some(pf) = pf {
let min = *block_numbers.iter().min().unwrap();
let max = *block_numbers.iter().max().unwrap();
match pf.get_block_timestamps(min, max).await {
Ok(entries) => {
debug!(
requested = block_numbers.len(),
returned = entries.len(),
range = format!("{min}..={max}"),
"Fetched block timestamps from pf-query"
);
for e in entries {
if block_numbers.contains(&e.block_number) {
ts_map.insert(e.block_number, e.timestamp);
}
}
}
Err(e) => {
warn!(error = %e, "pf-query block-timestamps failed, falling back to RPC");
}
}
}
let missing: Vec<u64> = block_numbers
.iter()
.copied()
.filter(|bn| !ts_map.contains_key(bn))
.collect();
if missing.is_empty() {
return ts_map;
}
let rpc_map: HashMap<u64, u64> = stream::iter(missing)
.map(|bn| {
let ds_blk = Arc::clone(ds);
async move { (bn, ds_blk.get_block(bn).await) }
})
.buffer_unordered(10)
.filter_map(|(bn, r)| async move { r.ok().map(|b| (bn, b.timestamp)) })
.collect()
.await;
ts_map.extend(rpc_map);
ts_map
}