1use 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
30pub fn generate_signer() -> PrivateKeySigner {
35 PrivateKeySigner::random()
36}
37
38pub 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
61pub 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
85pub 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#[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
119pub 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}