use std::time::Duration;
use alloy_primitives::U256;
use alloy_signer_local::PrivateKeySigner;
use taskfast_client::api::types::{
WalletBalance, WalletSetupRequest, WalletSetupRequestTempoWalletAddress, WalletSetupResponse,
};
use taskfast_client::{map_api_error, Error, Result, TaskFastClient};
use tokio::time::{sleep, Instant};
#[derive(Debug)]
pub enum WalletRegistration {
Configured(WalletSetupResponse),
AlreadyConfigured,
}
pub fn generate_signer() -> PrivateKeySigner {
PrivateKeySigner::random()
}
pub async fn register_wallet(client: &TaskFastClient, address: &str) -> Result<WalletRegistration> {
let validated =
WalletSetupRequestTempoWalletAddress::try_from(address).map_err(|e| Error::Validation {
code: "invalid_wallet_address".into(),
message: e.to_string(),
})?;
let body = WalletSetupRequest {
tempo_wallet_address: validated,
};
match client.inner().register_agent_wallet(&body).await {
Ok(v) => Ok(WalletRegistration::Configured(v.into_inner())),
Err(e) => match map_api_error(e).await {
Error::Validation { code, .. } if code == "wallet_already_configured" => {
Ok(WalletRegistration::AlreadyConfigured)
}
other => Err(other),
},
}
}
pub fn decode_wei(hex: &str) -> Result<U256> {
let trimmed = hex
.strip_prefix("0x")
.or_else(|| hex.strip_prefix("0X"))
.unwrap_or(hex);
if trimmed.is_empty() {
return Err(Error::Server(
"decode_wei: expected hex digits, got empty string".into(),
));
}
if !trimmed.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(Error::Server(format!(
"decode_wei: non-hex characters in {hex:?}"
)));
}
U256::from_str_radix(trimmed, 16)
.map_err(|e| Error::Server(format!("decode_wei: {e} (input {hex:?})")))
}
pub async fn fetch_balance_once(client: &TaskFastClient) -> Result<U256> {
let resp: WalletBalance = match client.inner().get_wallet_balance().await {
Ok(v) => v.into_inner(),
Err(e) => return Err(map_api_error(e).await),
};
match resp.available_balance.as_deref() {
Some(s) => decode_wei(s),
None => Ok(U256::ZERO),
}
}
#[derive(Debug, Clone, Copy)]
pub struct PollOptions {
pub min_balance: U256,
pub timeout: Duration,
pub poll_interval: Duration,
}
impl Default for PollOptions {
fn default() -> Self {
Self {
min_balance: U256::from(1u8),
timeout: Duration::from_mins(2),
poll_interval: Duration::from_secs(10),
}
}
}
pub async fn poll_balance(client: &TaskFastClient, opts: PollOptions) -> Result<U256> {
let start = Instant::now();
loop {
let balance = fetch_balance_once(client).await?;
if balance >= opts.min_balance {
return Ok(balance);
}
if start.elapsed() >= opts.timeout {
return Err(Error::Server(format!(
"wallet::poll_balance: timeout after {:?} (last balance {})",
opts.timeout, balance
)));
}
sleep(opts.poll_interval).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decode_wei_accepts_zero_variants() {
assert_eq!(decode_wei("0x0").unwrap(), U256::ZERO);
assert_eq!(decode_wei("0X0").unwrap(), U256::ZERO);
assert_eq!(decode_wei("0").unwrap(), U256::ZERO);
assert_eq!(
decode_wei("0x0000000000000000000000000000000000000000000000000000000000000000")
.unwrap(),
U256::ZERO
);
}
#[test]
fn decode_wei_accepts_prefixed_and_bare_hex() {
assert_eq!(decode_wei("0x1").unwrap(), U256::from(1u8));
assert_eq!(decode_wei("ff").unwrap(), U256::from(255u16));
assert_eq!(decode_wei("0xFF").unwrap(), U256::from(255u16));
}
#[test]
fn decode_wei_accepts_u256_max() {
let max_hex = format!("0x{}", "f".repeat(64));
assert_eq!(decode_wei(&max_hex).unwrap(), U256::MAX);
}
#[test]
fn decode_wei_rejects_empty_and_non_hex() {
assert!(matches!(decode_wei(""), Err(Error::Server(_))));
assert!(matches!(decode_wei("0x"), Err(Error::Server(_))));
assert!(matches!(decode_wei("0xzz"), Err(Error::Server(_))));
assert!(matches!(decode_wei("hello"), Err(Error::Server(_))));
}
#[test]
fn generate_signer_yields_distinct_keys() {
let a = generate_signer();
let b = generate_signer();
assert_ne!(a.address(), b.address());
}
}