Skip to main content

taskfast_agent/
wallet.rs

1// SPDX-License-Identifier: MIT
2//! Wallet keygen, registration with TaskFast, and balance polling.
3//!
4//! Replaces `cast wallet new` + the `scripts/init.sh` wallet provisioning
5//! block. Five entry points, each one step of the flow:
6//!
7//!   - [`generate_signer`] — `alloy` in-process keygen (replaces `cast wallet new`).
8//!   - [`register_wallet`] — `POST /agents/me/wallet` with the validated address.
9//!   - [`decode_wei`]      — hex wei → [`U256`]; the server returns `"0x0"` for zero.
10//!   - [`fetch_balance_once`] — one-shot `GET /agents/me/wallet/balance`.
11//!   - [`poll_balance`]    — repeats `fetch_balance_once` until the balance
12//!     meets [`PollOptions::min_balance`] or [`PollOptions::timeout`] elapses.
13//!
14//! Hex decoding is the single invariant this layer adds on top of the
15//! generated client: the server's wire shape is a hex string, but every
16//! caller downstream wants a numeric comparison, so we centralize the
17//! conversion here and surface a typed error rather than letting each
18//! caller roll its own parser.
19
20use std::time::Duration;
21
22use alloy_primitives::U256;
23use alloy_signer_local::PrivateKeySigner;
24use taskfast_client::api::types::{
25    WalletBalance, WalletSetupRequest, WalletSetupRequestTempoWalletAddress, WalletSetupResponse,
26};
27use taskfast_client::{map_api_error, Error, Result, TaskFastClient};
28use tokio::time::{sleep, Instant};
29
30/// Generate a fresh secp256k1 signer via `alloy_signer_local`.
31///
32/// The returned [`PrivateKeySigner`] owns the only copy of the private key;
33/// callers are responsible for persisting it (keystore, OS keyring, env).
34pub fn generate_signer() -> PrivateKeySigner {
35    PrivateKeySigner::random()
36}
37
38/// `POST /agents/me/wallet` — tells TaskFast about the agent's wallet address.
39///
40/// The address string is validated against the 0x+40-hex pattern *before*
41/// the HTTP call via the generated newtype, so a bad address fails locally
42/// as [`Error::Validation`] rather than surfacing as a 422 after a round-trip.
43pub async fn register_wallet(
44    client: &TaskFastClient,
45    address: &str,
46) -> Result<WalletSetupResponse> {
47    let validated =
48        WalletSetupRequestTempoWalletAddress::try_from(address).map_err(|e| Error::Validation {
49            code: "invalid_wallet_address".into(),
50            message: e.to_string(),
51        })?;
52    let body = WalletSetupRequest {
53        tempo_wallet_address: validated,
54    };
55    match client.inner().register_agent_wallet(&body).await {
56        Ok(v) => Ok(v.into_inner()),
57        Err(e) => Err(map_api_error(e).await),
58    }
59}
60
61/// Parse a hex-encoded wei string into a [`U256`].
62///
63/// Accepts an optional `0x`/`0X` prefix. Empty strings and non-hex bytes are
64/// protocol violations on the server's part — we surface them as
65/// [`Error::Server`] so init.sh-style callers abort instead of spinning.
66pub fn decode_wei(hex: &str) -> Result<U256> {
67    let trimmed = hex
68        .strip_prefix("0x")
69        .or_else(|| hex.strip_prefix("0X"))
70        .unwrap_or(hex);
71    if trimmed.is_empty() {
72        return Err(Error::Server(
73            "decode_wei: expected hex digits, got empty string".into(),
74        ));
75    }
76    if !trimmed.chars().all(|c| c.is_ascii_hexdigit()) {
77        return Err(Error::Server(format!(
78            "decode_wei: non-hex characters in {hex:?}"
79        )));
80    }
81    U256::from_str_radix(trimmed, 16)
82        .map_err(|e| Error::Server(format!("decode_wei: {e} (input {hex:?})")))
83}
84
85/// One-shot `GET /agents/me/wallet/balance` returning decoded wei.
86///
87/// A missing `available_balance` field is treated as zero (server contract
88/// allows it to be absent when the wallet is not yet indexed).
89pub async fn fetch_balance_once(client: &TaskFastClient) -> Result<U256> {
90    let resp: WalletBalance = match client.inner().get_wallet_balance().await {
91        Ok(v) => v.into_inner(),
92        Err(e) => return Err(map_api_error(e).await),
93    };
94    match resp.available_balance.as_deref() {
95        Some(s) => decode_wei(s),
96        None => Ok(U256::ZERO),
97    }
98}
99
100/// Knobs for [`poll_balance`]. Defaults mirror `scripts/init.sh`:
101/// 10 s between polls, 120 s total, `>= 1 wei` counts as funded.
102#[derive(Debug, Clone, Copy)]
103pub struct PollOptions {
104    pub min_balance: U256,
105    pub timeout: Duration,
106    pub poll_interval: Duration,
107}
108
109impl Default for PollOptions {
110    fn default() -> Self {
111        Self {
112            min_balance: U256::from(1u8),
113            timeout: Duration::from_mins(2),
114            poll_interval: Duration::from_secs(10),
115        }
116    }
117}
118
119/// Poll the balance endpoint until it meets `min_balance` or we time out.
120///
121/// Always performs at least one fetch before checking the clock — a tight
122/// timeout with a funded wallet still succeeds. Network/auth errors bubble
123/// up on the first occurrence (we don't silently swallow them to keep
124/// polling; a bad API key will never start working).
125pub async fn poll_balance(client: &TaskFastClient, opts: PollOptions) -> Result<U256> {
126    let start = Instant::now();
127    loop {
128        let balance = fetch_balance_once(client).await?;
129        if balance >= opts.min_balance {
130            return Ok(balance);
131        }
132        if start.elapsed() >= opts.timeout {
133            return Err(Error::Server(format!(
134                "wallet::poll_balance: timeout after {:?} (last balance {})",
135                opts.timeout, balance
136            )));
137        }
138        sleep(opts.poll_interval).await;
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn decode_wei_accepts_zero_variants() {
148        assert_eq!(decode_wei("0x0").unwrap(), U256::ZERO);
149        assert_eq!(decode_wei("0X0").unwrap(), U256::ZERO);
150        assert_eq!(decode_wei("0").unwrap(), U256::ZERO);
151        assert_eq!(
152            decode_wei("0x0000000000000000000000000000000000000000000000000000000000000000")
153                .unwrap(),
154            U256::ZERO
155        );
156    }
157
158    #[test]
159    fn decode_wei_accepts_prefixed_and_bare_hex() {
160        assert_eq!(decode_wei("0x1").unwrap(), U256::from(1u8));
161        assert_eq!(decode_wei("ff").unwrap(), U256::from(255u16));
162        assert_eq!(decode_wei("0xFF").unwrap(), U256::from(255u16));
163    }
164
165    #[test]
166    fn decode_wei_accepts_u256_max() {
167        let max_hex = format!("0x{}", "f".repeat(64));
168        assert_eq!(decode_wei(&max_hex).unwrap(), U256::MAX);
169    }
170
171    #[test]
172    fn decode_wei_rejects_empty_and_non_hex() {
173        assert!(matches!(decode_wei(""), Err(Error::Server(_))));
174        assert!(matches!(decode_wei("0x"), Err(Error::Server(_))));
175        assert!(matches!(decode_wei("0xzz"), Err(Error::Server(_))));
176        assert!(matches!(decode_wei("hello"), Err(Error::Server(_))));
177    }
178
179    #[test]
180    fn generate_signer_yields_distinct_keys() {
181        let a = generate_signer();
182        let b = generate_signer();
183        assert_ne!(a.address(), b.address());
184    }
185}