use r402_protocol::network::ChainId;
use r402_protocol::payment::PriceTag;
#[cfg(not(feature = "avm"))]
use super::feature_missing;
#[cfg(feature = "avm")]
use super::{
accept_custom_decimals, amount_u64, custom_asset_address, invalid_network, invalid_pay_to,
named_ticker, no_deployment, reject_evm_fields, require_exact,
};
use crate::config::{AcceptConfig, ConfigError};
#[cfg(not(feature = "avm"))]
pub(super) fn build(
_accept: &AcceptConfig,
_network: &ChainId,
_amount: u128,
_pay_to: &str,
) -> Result<PriceTag, ConfigError> {
Err(feature_missing("algorand", "avm"))
}
#[cfg(not(feature = "avm"))]
pub(super) fn decimals(_accept: &AcceptConfig, _network: &ChainId) -> Result<u8, ConfigError> {
Err(feature_missing("algorand", "avm"))
}
#[cfg(feature = "avm")]
pub(super) fn decimals(accept: &AcceptConfig, network: &ChainId) -> Result<u8, ConfigError> {
Ok(token(accept, network)?.decimals)
}
#[cfg(feature = "avm")]
pub(super) fn build(
accept: &AcceptConfig,
network: &ChainId,
amount: u128,
pay_to: &str,
) -> Result<PriceTag, ConfigError> {
use std::str::FromStr as _;
use r402_avm::AlgorandExact;
use r402_avm::chain::AlgorandAddress;
require_exact(accept)?;
reject_evm_fields(accept, "algorand")?;
let amount = amount_u64(amount, "algorand")?;
let pay_to = AlgorandAddress::from_str(pay_to)
.map_err(|error| invalid_pay_to("Algorand", pay_to, error))?;
let token = token(accept, network)?;
Ok(AlgorandExact::price_tag(pay_to, token.amount(amount)))
}
#[cfg(feature = "avm")]
fn token(
accept: &AcceptConfig,
network: &ChainId,
) -> Result<r402_avm::chain::AlgorandTokenDeployment, ConfigError> {
use r402_avm::USDC;
use r402_avm::chain::{AlgorandChainReference, AlgorandTokenDeployment};
let chain = AlgorandChainReference::try_from(network.clone())
.map_err(|error| invalid_network("algorand", &accept.network, error))?;
if named_ticker(accept, &["usdc"])?.is_some() {
return USDC::on(chain)
.copied()
.ok_or_else(|| no_deployment("USDC", &accept.network));
}
let address = custom_asset_address(accept)?;
let asset_id: u64 = address.parse().map_err(|_| {
ConfigError::Validation(format!(
"algorand asset_address '{address}' must be an ASA id decimal string"
))
})?;
Ok(AlgorandTokenDeployment::new(
chain,
asset_id,
accept_custom_decimals(accept)?,
))
}