Skip to main content

taskfast_cli/
tempo_session.rs

1// SPDX-License-Identifier: MIT
2//! Deep Tempo transaction and wallet signing session module.
3//!
4//! Encapsulates keystore handling, address validation, RPC client binding,
5//! ERC-20 allowances/balances, and automatically serializes every mutating
6//! transaction broadcast under the exclusive [`wallet_lock`].
7
8use std::path::PathBuf;
9use std::time::Duration;
10
11use alloy_primitives::{Address, Bytes, TxHash, U256};
12use alloy_signer_local::PrivateKeySigner;
13use alloy_sol_types::SolCall;
14
15use taskfast_agent::chain::{decode_u256, IERC20};
16use taskfast_agent::tempo_rpc::{sign_and_broadcast_tx, TempoRpcClient};
17use taskfast_chains::tempo::TEMPO_MAINNET_CHAIN_ID;
18
19use crate::cmd::CmdError;
20use crate::wallet_lock::{self, WalletGuard};
21use crate::Network;
22
23#[cfg(test)]
24use std::collections::HashMap;
25#[cfg(test)]
26use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
27#[cfg(test)]
28use std::sync::{Arc, Mutex};
29
30/// Default receipt timeouts and polling interval across all on-chain commands.
31pub const DEFAULT_RECEIPT_TIMEOUT_MAINNET: Duration = Duration::from_mins(3);
32pub const DEFAULT_RECEIPT_TIMEOUT_TESTNET: Duration = Duration::from_mins(1);
33pub const RECEIPT_POLL_INTERVAL: Duration = Duration::from_secs(2);
34
35/// Default receipt timeout given a chain ID.
36pub fn default_receipt_timeout_for_chain_id(chain_id: u64) -> Duration {
37    if chain_id == TEMPO_MAINNET_CHAIN_ID {
38        DEFAULT_RECEIPT_TIMEOUT_MAINNET
39    } else {
40        DEFAULT_RECEIPT_TIMEOUT_TESTNET
41    }
42}
43
44/// Default receipt timeout given an abstract Network.
45pub fn default_receipt_timeout_for_network(network: Network) -> Duration {
46    match network {
47        Network::Mainnet => DEFAULT_RECEIPT_TIMEOUT_MAINNET,
48        Network::Testnet => DEFAULT_RECEIPT_TIMEOUT_TESTNET,
49    }
50}
51
52/// In-process mock RPC adapter for hermetic tests without WireMock scaffolding.
53#[cfg(test)]
54#[derive(Debug)]
55pub struct MockTempoRpc {
56    pub chain_id: AtomicU64,
57    pub balances: Mutex<HashMap<(Address, Address), U256>>,
58    pub allowances: Mutex<HashMap<(Address, Address, Address), U256>>,
59    pub broadcast_delay: Mutex<Option<Duration>>,
60    pub active_broadcasts: AtomicUsize,
61    pub max_concurrent_broadcasts: AtomicUsize,
62    pub receipts: Mutex<HashMap<TxHash, bool>>,
63    pub sent_transactions: Mutex<Vec<(Address, Bytes)>>,
64    nonce: AtomicU64,
65}
66
67#[cfg(test)]
68impl Default for MockTempoRpc {
69    fn default() -> Self {
70        Self {
71            chain_id: AtomicU64::new(42427),
72            balances: Mutex::new(HashMap::new()),
73            allowances: Mutex::new(HashMap::new()),
74            broadcast_delay: Mutex::new(None),
75            active_broadcasts: AtomicUsize::new(0),
76            max_concurrent_broadcasts: AtomicUsize::new(0),
77            receipts: Mutex::new(HashMap::new()),
78            sent_transactions: Mutex::new(Vec::new()),
79            nonce: AtomicU64::new(1),
80        }
81    }
82}
83
84#[cfg(test)]
85impl MockTempoRpc {
86    pub fn new() -> Self {
87        Self::default()
88    }
89
90    pub fn set_balance(&self, token: Address, account: Address, balance: U256) {
91        self.balances
92            .lock()
93            .unwrap()
94            .insert((token, account), balance);
95    }
96
97    pub fn set_allowance(&self, token: Address, owner: Address, spender: Address, allowance: U256) {
98        self.allowances
99            .lock()
100            .unwrap()
101            .insert((token, owner, spender), allowance);
102    }
103
104    pub fn set_broadcast_delay(&self, delay: Duration) {
105        *self.broadcast_delay.lock().unwrap() = Some(delay);
106    }
107}
108
109/// Backend variant for RPC operations: live HTTP client or in-process mock.
110#[derive(Clone, Debug)]
111pub(crate) enum TempoRpcBackend {
112    Client(TempoRpcClient),
113    #[cfg(test)]
114    Mock(Arc<MockTempoRpc>),
115}
116
117/// Deep session wrapping a signer, keystore file lock, and RPC transport.
118#[derive(Clone, Debug)]
119pub struct TempoSession {
120    signer: PrivateKeySigner,
121    keystore_path: Option<PathBuf>,
122    backend: TempoRpcBackend,
123    receipt_timeout: Duration,
124}
125
126impl TempoSession {
127    /// Create a new session with a live RPC client.
128    pub fn new(
129        signer: PrivateKeySigner,
130        keystore_path: Option<PathBuf>,
131        rpc: TempoRpcClient,
132        receipt_timeout: Duration,
133    ) -> Self {
134        Self {
135            signer,
136            keystore_path,
137            backend: TempoRpcBackend::Client(rpc),
138            receipt_timeout,
139        }
140    }
141
142    /// Create a new session with an in-process mock adapter for testing.
143    #[cfg(test)]
144    pub fn from_mock(
145        signer: PrivateKeySigner,
146        keystore_path: Option<PathBuf>,
147        mock: Arc<MockTempoRpc>,
148        receipt_timeout: Duration,
149    ) -> Self {
150        Self {
151            signer,
152            keystore_path,
153            backend: TempoRpcBackend::Mock(mock),
154            receipt_timeout,
155        }
156    }
157
158    pub fn signer(&self) -> &PrivateKeySigner {
159        &self.signer
160    }
161
162    pub fn address(&self) -> Address {
163        self.signer.address()
164    }
165
166    /// Acquire the exclusive wallet lock for the keystore path, if configured.
167    pub fn acquire_lock(&self) -> Result<Option<WalletGuard>, CmdError> {
168        if let Some(ref path) = self.keystore_path {
169            Ok(Some(wallet_lock::acquire(path)?))
170        } else {
171            Ok(None)
172        }
173    }
174
175    /// Read-only call impersonating an explicit sender (TIP-20 privacy compliance).
176    pub async fn eth_call_from(
177        &self,
178        from: Address,
179        to: Address,
180        calldata: &Bytes,
181    ) -> Result<Vec<u8>, CmdError> {
182        match &self.backend {
183            TempoRpcBackend::Client(client) => client
184                .eth_call_from(from, to, calldata)
185                .await
186                .map_err(|e| CmdError::Server(format!("eth_call: {e}"))),
187            #[cfg(test)]
188            TempoRpcBackend::Mock(mock) => {
189                if let Ok(call) = IERC20::balanceOfCall::abi_decode(calldata) {
190                    let bal = mock
191                        .balances
192                        .lock()
193                        .unwrap()
194                        .get(&(to, call.account))
195                        .copied()
196                        .unwrap_or(U256::ZERO);
197                    return Ok(bal.to_be_bytes::<32>().to_vec());
198                }
199                if let Ok(call) = IERC20::allowanceCall::abi_decode(calldata) {
200                    let allow = mock
201                        .allowances
202                        .lock()
203                        .unwrap()
204                        .get(&(to, call.owner, call.spender))
205                        .copied()
206                        .unwrap_or(U256::ZERO);
207                    return Ok(allow.to_be_bytes::<32>().to_vec());
208                }
209                Ok(vec![0u8; 32])
210            }
211        }
212    }
213
214    /// Query ERC-20 balance for an account.
215    pub async fn erc20_balance_of(
216        &self,
217        token: Address,
218        account: Address,
219    ) -> Result<U256, CmdError> {
220        let calldata: Bytes = IERC20::balanceOfCall { account }.abi_encode().into();
221        let raw = self.eth_call_from(account, token, &calldata).await?;
222        decode_u256(&raw).map_err(CmdError::Decode)
223    }
224
225    /// Query ERC-20 allowance for (owner, spender).
226    pub async fn erc20_allowance(
227        &self,
228        token: Address,
229        owner: Address,
230        spender: Address,
231    ) -> Result<U256, CmdError> {
232        let calldata: Bytes = IERC20::allowanceCall { owner, spender }.abi_encode().into();
233        let raw = self.eth_call_from(owner, token, &calldata).await?;
234        decode_u256(&raw).map_err(CmdError::Decode)
235    }
236
237    /// Send a mutating transaction under the exclusive wallet lock without waiting for receipt.
238    pub async fn send_transaction(&self, to: Address, calldata: Bytes) -> Result<TxHash, CmdError> {
239        let _guard = self.acquire_lock()?;
240        self.broadcast_internal(to, calldata)
241            .await
242            .map_err(|e| CmdError::Server(format!("tempo rpc: {e}")))
243    }
244
245    /// Send a mutating transaction under the exclusive wallet lock and wait for receipt.
246    pub async fn send_transaction_and_wait(
247        &self,
248        to: Address,
249        calldata: Bytes,
250        action: &str,
251        revert_suffix: Option<&str>,
252    ) -> Result<TxHash, CmdError> {
253        let _guard = self.acquire_lock()?;
254        let (broadcast_msg, receipt_msg, tx_prefix) = if action.is_empty() {
255            (
256                "broadcast failed".to_string(),
257                "receipt".to_string(),
258                "tx".to_string(),
259            )
260        } else {
261            (
262                format!("{action} broadcast failed"),
263                format!("{action} receipt"),
264                format!("{action} tx"),
265            )
266        };
267        let tx_hash = self
268            .broadcast_internal(to, calldata)
269            .await
270            .map_err(|e| CmdError::Server(format!("{broadcast_msg}: {e}")))?;
271        let ok = self
272            .wait_for_receipt_internal(tx_hash)
273            .await
274            .map_err(|e| CmdError::Server(format!("{receipt_msg}: {e}")))?;
275        if !ok {
276            let suffix = revert_suffix.unwrap_or("");
277            return Err(CmdError::Server(format!(
278                "{tx_prefix} {tx_hash:#x} reverted on-chain{suffix}"
279            )));
280        }
281        Ok(tx_hash)
282    }
283
284    /// Unified ERC-20 allowance check: checks current allowance and sends `approve` if needed.
285    pub async fn ensure_allowance(
286        &self,
287        token: Address,
288        spender: Address,
289        required: U256,
290    ) -> Result<Option<TxHash>, CmdError> {
291        let current_allowance = self.erc20_allowance(token, self.address(), spender).await?;
292        if current_allowance >= required {
293            return Ok(None);
294        }
295        let approve_calldata: Bytes = IERC20::approveCall {
296            spender,
297            amount: required,
298        }
299        .abi_encode()
300        .into();
301        let approve_hash = self
302            .send_transaction_and_wait(token, approve_calldata, "approve", None)
303            .await?;
304        let new_allowance = self.erc20_allowance(token, self.address(), spender).await?;
305        if new_allowance < required {
306            return Err(CmdError::Server(format!(
307                "allowance still {new_allowance} after approve tx {approve_hash:#x} (needed {required})"
308            )));
309        }
310        Ok(Some(approve_hash))
311    }
312
313    async fn broadcast_internal(&self, to: Address, calldata: Bytes) -> Result<TxHash, String> {
314        match &self.backend {
315            TempoRpcBackend::Client(client) => {
316                sign_and_broadcast_tx(client, &self.signer, to, calldata)
317                    .await
318                    .map_err(|e| e.to_string())
319            }
320            #[cfg(test)]
321            TempoRpcBackend::Mock(mock) => {
322                let active = mock.active_broadcasts.fetch_add(1, Ordering::SeqCst) + 1;
323                mock.max_concurrent_broadcasts
324                    .fetch_max(active, Ordering::SeqCst);
325
326                let delay = *mock.broadcast_delay.lock().unwrap();
327                if let Some(d) = delay {
328                    tokio::time::sleep(d).await;
329                }
330                if let Ok(call) = IERC20::approveCall::abi_decode(&calldata) {
331                    mock.allowances
332                        .lock()
333                        .unwrap()
334                        .insert((to, self.address(), call.spender), call.amount);
335                }
336                mock.sent_transactions
337                    .lock()
338                    .unwrap()
339                    .push((to, calldata.clone()));
340                let nonce = mock.nonce.fetch_add(1, Ordering::SeqCst);
341                let mut data = calldata.to_vec();
342                data.extend_from_slice(&nonce.to_be_bytes());
343                let hash = alloy_primitives::keccak256(&data);
344
345                mock.active_broadcasts.fetch_sub(1, Ordering::SeqCst);
346                Ok(TxHash::from(hash))
347            }
348        }
349    }
350
351    async fn wait_for_receipt_internal(&self, tx_hash: TxHash) -> Result<bool, String> {
352        match &self.backend {
353            TempoRpcBackend::Client(client) => client
354                .wait_for_receipt(tx_hash, self.receipt_timeout, RECEIPT_POLL_INTERVAL)
355                .await
356                .map_err(|e| e.to_string()),
357            #[cfg(test)]
358            TempoRpcBackend::Mock(mock) => {
359                let ok = mock
360                    .receipts
361                    .lock()
362                    .unwrap()
363                    .get(&tx_hash)
364                    .copied()
365                    .unwrap_or(true);
366                Ok(ok)
367            }
368        }
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    fn test_signer() -> PrivateKeySigner {
377        PrivateKeySigner::random()
378    }
379
380    #[tokio::test]
381    async fn test_mock_balance_and_allowance() {
382        let signer = test_signer();
383        let mock = Arc::new(MockTempoRpc::new());
384        let token = Address::repeat_byte(0x01);
385        let spender = Address::repeat_byte(0x02);
386        mock.set_balance(token, signer.address(), U256::from(5000));
387        mock.set_allowance(token, signer.address(), spender, U256::from(1000));
388
389        let session = TempoSession::from_mock(signer, None, mock, Duration::from_secs(10));
390
391        let bal = session
392            .erc20_balance_of(token, session.address())
393            .await
394            .unwrap();
395        assert_eq!(bal, U256::from(5000));
396
397        let allow = session
398            .erc20_allowance(token, session.address(), spender)
399            .await
400            .unwrap();
401        assert_eq!(allow, U256::from(1000));
402
403        // When required <= current allowance, ensure_allowance returns Ok(None)
404        let tx = session
405            .ensure_allowance(token, spender, U256::from(800))
406            .await
407            .unwrap();
408        assert!(tx.is_none());
409
410        // When required > current allowance, ensure_allowance broadcasts approve and returns Ok(Some)
411        let tx = session
412            .ensure_allowance(token, spender, U256::from(2000))
413            .await
414            .unwrap();
415        assert!(tx.is_some());
416
417        let new_allow = session
418            .erc20_allowance(token, session.address(), spender)
419            .await
420            .unwrap();
421        assert_eq!(new_allow, U256::from(2000));
422    }
423
424    #[test]
425    fn test_concurrency_serialization_under_wallet_lock() {
426        let tmp = tempfile::TempDir::new().unwrap();
427        let keystore_file = tmp.path().join("keystore.json");
428        std::fs::write(&keystore_file, "{}").unwrap();
429
430        let mock = Arc::new(MockTempoRpc::new());
431        // Set broadcast delay so a concurrent broadcast must wait
432        mock.set_broadcast_delay(Duration::from_millis(50));
433
434        let mut threads = Vec::new();
435        for _ in 0..4 {
436            let signer = test_signer();
437            let session = TempoSession::from_mock(
438                signer,
439                Some(keystore_file.clone()),
440                mock.clone(),
441                Duration::from_secs(5),
442            );
443
444            let handle = std::thread::spawn(move || {
445                let rt = tokio::runtime::Builder::new_current_thread()
446                    .enable_all()
447                    .build()
448                    .unwrap();
449                rt.block_on(async move {
450                    session
451                        .send_transaction(Address::repeat_byte(0x05), Bytes::from_static(b"test"))
452                        .await
453                })
454            });
455            threads.push(handle);
456        }
457
458        for h in threads {
459            let res = h.join().unwrap();
460            assert!(res.is_ok());
461        }
462
463        // Under wallet_lock, max concurrency MUST be 1!
464        assert_eq!(
465            mock.max_concurrent_broadcasts.load(Ordering::SeqCst),
466            1,
467            "wallet_lock must serialize concurrent broadcasts so max concurrency is 1"
468        );
469        assert_eq!(mock.sent_transactions.lock().unwrap().len(), 4);
470    }
471}