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/// Outcome of `POST /agents/me/wallet`. Idempotent re-registration surfaces
31/// as [`WalletRegistration::AlreadyConfigured`] so callers can treat
32/// it as success without branching on a typed `Error`.
33#[derive(Debug)]
34pub enum WalletRegistration {
35    /// 200 happy path — full wallet envelope returned by the server.
36    Configured(WalletSetupResponse),
37    /// 409 `wallet_already_configured` — server has no body to return; caller
38    /// already has a wallet on file.
39    AlreadyConfigured,
40}
41
42/// Generate a fresh secp256k1 signer via `alloy_signer_local`.
43///
44/// The returned [`PrivateKeySigner`] owns the only copy of the private key;
45/// callers are responsible for persisting it (keystore, OS keyring, env).
46pub fn generate_signer() -> PrivateKeySigner {
47    PrivateKeySigner::random()
48}
49
50/// `POST /agents/me/wallet` — tells TaskFast about the agent's wallet address.
51///
52/// The address string is validated against the 0x+40-hex pattern *before*
53/// the HTTP call via the generated newtype, so a bad address fails locally
54/// as [`Error::Validation`] rather than surfacing as a 422 after a round-trip.
55///
56/// 200 returns [`WalletRegistration::Configured`]. 409 `wallet_already_configured`
57/// is promoted to [`WalletRegistration::AlreadyConfigured`] so callers can
58/// treat re-registration as success without reparsing `Error::Validation`.
59/// Every other failure propagates through `map_api_error` unchanged.
60pub async fn register_wallet(client: &TaskFastClient, address: &str) -> Result<WalletRegistration> {
61    let validated =
62        WalletSetupRequestTempoWalletAddress::try_from(address).map_err(|e| Error::Validation {
63            code: "invalid_wallet_address".into(),
64            message: e.to_string(),
65        })?;
66    let body = WalletSetupRequest {
67        tempo_wallet_address: validated,
68    };
69    match client.inner().register_agent_wallet(&body).await {
70        Ok(v) => Ok(WalletRegistration::Configured(v.into_inner())),
71        Err(e) => match map_api_error(e).await {
72            Error::Validation { code, .. } if code == "wallet_already_configured" => {
73                Ok(WalletRegistration::AlreadyConfigured)
74            }
75            other => Err(other),
76        },
77    }
78}
79
80/// Parse a hex-encoded wei string into a [`U256`].
81///
82/// Accepts an optional `0x`/`0X` prefix. Empty strings and non-hex bytes are
83/// protocol violations on the server's part — we surface them as
84/// [`Error::Server`] so init.sh-style callers abort instead of spinning.
85pub fn decode_wei(hex: &str) -> Result<U256> {
86    let trimmed = hex
87        .strip_prefix("0x")
88        .or_else(|| hex.strip_prefix("0X"))
89        .unwrap_or(hex);
90    if trimmed.is_empty() {
91        return Err(Error::Server(
92            "decode_wei: expected hex digits, got empty string".into(),
93        ));
94    }
95    if !trimmed.chars().all(|c| c.is_ascii_hexdigit()) {
96        return Err(Error::Server(format!(
97            "decode_wei: non-hex characters in {hex:?}"
98        )));
99    }
100    U256::from_str_radix(trimmed, 16)
101        .map_err(|e| Error::Server(format!("decode_wei: {e} (input {hex:?})")))
102}
103
104/// One-shot `GET /agents/me/wallet/balance` returning decoded wei.
105///
106/// A missing `available_balance` field is treated as zero (server contract
107/// allows it to be absent when the wallet is not yet indexed).
108pub async fn fetch_balance_once(client: &TaskFastClient) -> Result<U256> {
109    let resp: WalletBalance = match client.inner().get_wallet_balance().await {
110        Ok(v) => v.into_inner(),
111        Err(e) => return Err(map_api_error(e).await),
112    };
113    match resp.available_balance.as_deref() {
114        Some(s) => decode_wei(s),
115        None => Ok(U256::ZERO),
116    }
117}
118
119/// Knobs for [`poll_balance`]. Defaults mirror `scripts/init.sh`:
120/// 10 s between polls, 120 s total, `>= 1 wei` counts as funded.
121#[derive(Debug, Clone, Copy)]
122pub struct PollOptions {
123    pub min_balance: U256,
124    pub timeout: Duration,
125    pub poll_interval: Duration,
126}
127
128impl Default for PollOptions {
129    fn default() -> Self {
130        Self {
131            min_balance: U256::from(1u8),
132            timeout: Duration::from_mins(2),
133            poll_interval: Duration::from_secs(10),
134        }
135    }
136}
137
138/// Poll the balance endpoint until it meets `min_balance` or we time out.
139///
140/// Always performs at least one fetch before checking the clock — a tight
141/// timeout with a funded wallet still succeeds. Network/auth errors bubble
142/// up on the first occurrence (we don't silently swallow them to keep
143/// polling; a bad API key will never start working).
144pub async fn poll_balance(client: &TaskFastClient, opts: PollOptions) -> Result<U256> {
145    let start = Instant::now();
146    loop {
147        let balance = fetch_balance_once(client).await?;
148        if balance >= opts.min_balance {
149            return Ok(balance);
150        }
151        if start.elapsed() >= opts.timeout {
152            return Err(Error::Server(format!(
153                "wallet::poll_balance: timeout after {:?} (last balance {})",
154                opts.timeout, balance
155            )));
156        }
157        sleep(opts.poll_interval).await;
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    #[test]
166    fn decode_wei_accepts_zero_variants() {
167        assert_eq!(decode_wei("0x0").unwrap(), U256::ZERO);
168        assert_eq!(decode_wei("0X0").unwrap(), U256::ZERO);
169        assert_eq!(decode_wei("0").unwrap(), U256::ZERO);
170        assert_eq!(
171            decode_wei("0x0000000000000000000000000000000000000000000000000000000000000000")
172                .unwrap(),
173            U256::ZERO
174        );
175    }
176
177    #[test]
178    fn decode_wei_accepts_prefixed_and_bare_hex() {
179        assert_eq!(decode_wei("0x1").unwrap(), U256::from(1u8));
180        assert_eq!(decode_wei("ff").unwrap(), U256::from(255u16));
181        assert_eq!(decode_wei("0xFF").unwrap(), U256::from(255u16));
182    }
183
184    #[test]
185    fn decode_wei_accepts_u256_max() {
186        let max_hex = format!("0x{}", "f".repeat(64));
187        assert_eq!(decode_wei(&max_hex).unwrap(), U256::MAX);
188    }
189
190    #[test]
191    fn decode_wei_rejects_empty_and_non_hex() {
192        assert!(matches!(decode_wei(""), Err(Error::Server(_))));
193        assert!(matches!(decode_wei("0x"), Err(Error::Server(_))));
194        assert!(matches!(decode_wei("0xzz"), Err(Error::Server(_))));
195        assert!(matches!(decode_wei("hello"), Err(Error::Server(_))));
196    }
197
198    #[test]
199    fn generate_signer_yields_distinct_keys() {
200        let a = generate_signer();
201        let b = generate_signer();
202        assert_ne!(a.address(), b.address());
203    }
204}