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
30#[derive(Debug)]
34pub enum WalletRegistration {
35 Configured(WalletSetupResponse),
37 AlreadyConfigured,
40}
41
42pub fn generate_signer() -> PrivateKeySigner {
47 PrivateKeySigner::random()
48}
49
50pub 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
80pub 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
104pub 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#[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
138pub 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}