use futures::StreamExt;
use moonproof_indexer_client::{subscribe_contract_actions, BlockOffset};
use moonproof_utils::rt::{spawn_task, Task};
use moonproof_utils::StateCell;
use tokio::sync::watch;
use crate::error::{ContractRuntimeError, Result};
use crate::state_fold::fold_contract_actions;
use moonproof_runtime::state::{contract_address_to_hex, ContractRuntimeState};
pub struct Watcher {
state: StateCell<ContractRuntimeState>,
task: Task<Result<()>>,
}
impl Watcher {
pub async fn current(&self) -> ContractRuntimeState {
self.state.current().await
}
#[must_use]
pub fn watch(&self) -> watch::Receiver<ContractRuntimeState> {
self.state.changes()
}
pub async fn join(self) -> Result<()> {
self.task
.join()
.await
.map_err(|e| ContractRuntimeError::Provider {
provider: "sync::Watcher::join",
message: format!("driver task join failed: {e}"),
})?
}
pub fn abort(&self) {
self.task.abort();
}
}
pub async fn spawn(
indexer_http_url: impl Into<String>,
initial_state: ContractRuntimeState,
start_offset: Option<BlockOffset>,
) -> Result<Watcher> {
let url = indexer_http_url.into();
let address_hex = initial_state.address_hex();
let address = *initial_state.address();
let subscription = subscribe_contract_actions(&url, &address_hex, start_offset)
.await
.map_err(|e| {
ContractRuntimeError::Indexer(format!(
"open contractActions subscription for {}: {e}",
contract_address_to_hex(&address),
))
})?;
let cell = StateCell::new(initial_state);
let driver_cell = cell.clone();
let task: Task<Result<()>> = spawn_task(async move {
let mut stream = subscription;
while let Some(tick_res) = stream.next().await {
let tick = tick_res.map_err(|e| {
ContractRuntimeError::Indexer(format!("contractActions stream error: {e}"))
})?;
driver_cell
.apply::<_, ContractRuntimeError>(|old| fold_contract_actions(old, [tick]))
.await?;
}
Ok(())
});
Ok(Watcher { state: cell, task })
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn watcher_exposes_current_state_and_joins_its_task() {
use moonproof_ledger::base_crypto::hash::HashOutput;
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::onchain_runtime::state::{
ContractMaintenanceAuthority, ContractState, EntryPointBuf, StateValue,
};
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
let op_key: EntryPointBuf = b"noop"[..].into();
let state = ContractState::<InMemoryDB>::new(
StateValue::Null,
StorageHashMap::new().insert(op_key, moonproof_ledger::contract_operation(None)),
ContractMaintenanceAuthority::default(),
);
let address = ContractAddress(HashOutput([0xabu8; 32]));
let runtime_state = ContractRuntimeState::new(address, state);
let task = spawn_task(async { Ok(()) as Result<()> });
let watcher = Watcher {
state: StateCell::new(runtime_state),
task,
};
assert_eq!(watcher.watch().borrow().address(), &address);
watcher.join().await.unwrap();
}
}