use crate::error::AlgoError;
use algonaut::core::ToMsgPack;
use anyhow::{Result, anyhow, bail};
use base64::{Engine as _, engine::general_purpose};
use data_encoding::{BASE32_NOPAD, HEXLOWER};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use uuid::Uuid;
#[allow(unused_imports)]
use algonaut as _algonaut;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RateLimitConfig {
pub max_requests: u32,
pub per_millis: u64,
#[serde(default)]
pub mode: RateLimitMode,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum RateLimitMode {
#[default]
Block,
Reject,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DailyBudgetConfig {
pub max_requests_per_day: u32,
pub day_start_offset_secs: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AlgoChainConfig {
pub client_api_url: String,
pub client_api_port: u16,
pub indexer_api_url: String,
pub indexer_api_port: u16,
pub token: Option<String>,
pub token_key: Option<String>,
pub app_id: Option<u64>,
pub asset_id: Option<u64>,
#[serde(default)]
pub rate_limit: Option<RateLimitConfig>,
#[serde(default)]
pub daily_budget: Option<DailyBudgetConfig>,
}
impl Default for AlgoChainConfig {
fn default() -> Self {
Self {
client_api_url: "http://localhost".to_string(),
client_api_port: 4001,
indexer_api_url: "http://localhost".to_string(),
indexer_api_port: 8980,
token: Some(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string(),
),
token_key: Some("X-Algo-API-Token".to_string()),
app_id: None,
asset_id: None,
rate_limit: None,
daily_budget: None,
}
}
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
#[derive(Debug)]
pub(crate) struct RateLimiter {
capacity: f64,
tokens: f64,
refill_per_sec: f64,
last_refill: Instant,
}
impl RateLimiter {
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn new(cfg: &RateLimitConfig, now: Instant) -> Self {
let capacity = cfg.max_requests.max(1) as f64;
let per_secs = (cfg.per_millis.max(1) as f64) / 1000.0;
Self {
capacity,
tokens: capacity,
refill_per_sec: capacity / per_secs,
last_refill: now,
}
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn poll(&mut self, now: Instant) -> Duration {
let elapsed = now
.saturating_duration_since(self.last_refill)
.as_secs_f64();
self.tokens = (self.tokens + elapsed * self.refill_per_sec).min(self.capacity);
self.last_refill = now;
if self.tokens >= 1.0 {
self.tokens -= 1.0;
Duration::ZERO
} else {
Duration::from_secs_f64((1.0 - self.tokens) / self.refill_per_sec)
}
}
}
fn lock_recover<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
match m.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
}
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
#[derive(Debug)]
pub(crate) struct DailyBudget {
max: u32,
day_start_offset_secs: u32,
window_start_unix: u64,
spent: u32,
}
impl DailyBudget {
fn window_start_for(now: u64, offset: u64) -> u64 {
let k = (now as i64 - offset as i64).div_euclid(86_400);
(k * 86_400 + offset as i64).max(0) as u64
}
fn roll(&mut self, now: u64) {
let end = self.window_start_unix.saturating_add(86_400);
if now < self.window_start_unix || now >= end {
self.window_start_unix = Self::window_start_for(now, self.day_start_offset_secs as u64);
self.spent = 0;
}
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn new(cfg: &DailyBudgetConfig, now_unix_secs: u64, primed_spent: u32) -> Self {
let day_start_offset_secs = cfg.day_start_offset_secs % 86_400;
Self {
max: cfg.max_requests_per_day,
day_start_offset_secs,
window_start_unix: Self::window_start_for(now_unix_secs, day_start_offset_secs as u64),
spent: primed_spent,
}
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn check(&mut self, now_unix_secs: u64) -> Result<(), Duration> {
self.roll(now_unix_secs);
if self.spent >= self.max {
let end = self.window_start_unix.saturating_add(86_400);
Err(Duration::from_secs(end.saturating_sub(now_unix_secs)))
} else {
Ok(())
}
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn record(&mut self, now_unix_secs: u64) {
self.roll(now_unix_secs);
self.spent = self.spent.saturating_add(1);
}
}
#[derive(Debug, Clone, Copy)]
pub struct DailyBudgetState {
pub window_start_unix: u64,
pub spent: u32,
pub max: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AlgoSuggestedParams {
pub last_round: u64,
pub min_fee: u64,
pub genesis_hash: [u8; 32],
pub genesis_id: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct AlgoAccountFunds {
pub amount: u64,
pub min_balance: u64,
}
impl AlgoAccountFunds {
pub fn spendable(&self) -> u64 {
self.amount.saturating_sub(self.min_balance)
}
}
pub use blockchain_ops::ConfirmedTxn;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScannedTxn {
pub confirmed_round: u64,
pub sender: String,
pub note: Option<Vec<u8>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScannedAccount {
pub address: String,
pub local_state: Vec<(String, String)>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TxnScanFilter {
pub note_prefix: Option<Vec<u8>>,
pub sender: Option<String>,
pub app_id: Option<u64>,
}
impl TxnScanFilter {
fn prepare(&self) -> Result<PreparedScanFilter> {
Ok(PreparedScanFilter {
note_prefix: self
.note_prefix
.as_ref()
.map(|b| general_purpose::STANDARD.encode(b)),
address: self
.sender
.as_deref()
.map(AlgoOps::parse_address)
.transpose()?,
app_id: self.app_id.map(algonaut::core::AppId),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TxnScanCache<T> {
pub last_round: u64,
pub last_updated: u64,
pub entries: Vec<T>,
}
impl<T> TxnScanCache<T> {
pub fn new() -> Self {
TxnScanCache {
last_round: 0,
last_updated: 0,
entries: Vec::new(),
}
}
}
impl<T> Default for TxnScanCache<T> {
fn default() -> Self {
TxnScanCache::new()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AccountScanCache<T> {
pub last_round: u64,
pub last_updated: u64,
pub entries: Vec<(String, T)>,
}
impl<T> AccountScanCache<T> {
pub fn new() -> Self {
AccountScanCache {
last_round: 0,
last_updated: 0,
entries: Vec::new(),
}
}
pub fn clear(&mut self) {
*self = AccountScanCache::new();
}
}
impl<T> Default for AccountScanCache<T> {
fn default() -> Self {
AccountScanCache::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueryMode {
Refresh,
CacheOnly,
ForceFull,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TxnScanPage {
pub txns: Vec<ScannedTxn>,
pub next_token: Option<String>,
pub current_round: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccountScanPage {
pub accounts: Vec<ScannedAccount>,
pub next_token: Option<String>,
pub current_round: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChangedAddressesPage {
pub addresses: Vec<String>,
pub next_token: Option<String>,
pub current_round: u64,
}
struct PreparedScanFilter {
note_prefix: Option<String>,
address: Option<algonaut::core::Address>,
app_id: Option<algonaut::core::AppId>,
}
pub trait KeyProvider: Send + Sync {
fn get_id(&self) -> Option<String> {
None
}
fn get_private_key(&self) -> Option<String> {
None
}
fn save_private_key_object(&self, _address: &str, _passphrase: &str) {}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallKind {
Algod,
IndexerRead,
}
impl CallKind {
pub fn operation(self) -> &'static str {
match self {
CallKind::Algod => "algod call",
CallKind::IndexerRead => "indexer search",
}
}
}
#[derive(Debug, Clone)]
pub struct AlgoOps {
pub passphrase: Option<String>,
pub address: Option<String>,
pub config: AlgoChainConfig,
rate_limiter: Option<Arc<Mutex<RateLimiter>>>,
requests_made: Arc<AtomicU64>,
daily_budget: Option<Arc<Mutex<DailyBudget>>>,
timeout: Option<Duration>,
app_creators: Arc<Mutex<HashMap<u64, String>>>,
}
impl AlgoOps {
pub fn generate_keypair() -> (String, String) {
use ed25519_dalek::SigningKey;
use rand_core::{OsRng, RngCore};
let mut rng = OsRng;
let mut sk: [u8; 32] = [0u8; 32];
rng.fill_bytes(&mut sk);
let signing_key = SigningKey::from_bytes(&sk);
let verifying_key = signing_key.verifying_key();
let pk: [u8; 32] = verifying_key.to_bytes();
let id =
byte_key_to_address(&pk).expect("failed to derive Algorand address from public key");
let passphrase =
algonaut::crypto::mnemonic::from_key(&sk).expect("failed to generate mnemonic");
(id, passphrase)
}
pub fn seed_from_passphrase(passphrase: &str) -> Result<[u8; 32]> {
if !passphrase.is_empty()
&& let Ok(key) = algonaut::crypto::mnemonic::to_key(passphrase)
{
return key
.to_vec()
.as_slice()
.try_into()
.map_err(|_| anyhow!("invalid passphrase: derived seed is not 32 bytes"));
}
if let Some(rest) = passphrase.strip_prefix("b64:") {
let bytes = general_purpose::STANDARD
.decode(rest)
.map_err(|e| anyhow!("invalid passphrase: bad base64 secret ({e})"))?;
return bytes
.as_slice()
.try_into()
.map_err(|_| anyhow!("invalid passphrase: secret is not 32 bytes"));
}
bail!("invalid passphrase: expected a 25-word Algorand mnemonic")
}
pub fn address_from_passphrase(passphrase: &str) -> Result<String> {
use ed25519_dalek::SigningKey;
let sk = Self::seed_from_passphrase(passphrase)?;
let signing_key = SigningKey::from_bytes(&sk);
let pk: [u8; 32] = signing_key.verifying_key().to_bytes();
byte_key_to_address(&pk)
}
pub(crate) fn new(
passphrase: Option<String>,
address: Option<String>,
config: Option<AlgoChainConfig>,
) -> Self {
let config = config.unwrap_or_default();
let rate_limiter = config
.rate_limit
.as_ref()
.map(|rl| Arc::new(Mutex::new(RateLimiter::new(rl, Instant::now()))));
let daily_budget = config
.daily_budget
.as_ref()
.map(|db| Arc::new(Mutex::new(DailyBudget::new(db, Self::now_unix_secs(), 0))));
let mut ops = Self {
passphrase,
address,
config,
rate_limiter,
requests_made: Arc::new(AtomicU64::new(0)),
daily_budget,
timeout: None,
app_creators: Arc::new(Mutex::new(HashMap::new())),
};
if ops.address.is_none()
&& let Some(ref pass) = ops.passphrase
&& let Ok(addr) = Self::address_from_passphrase(pass)
{
ops.address = Some(addr);
}
ops
}
pub fn with_rate_limit(self, max: u32, per: Duration) -> Self {
self.with_rate_limit_mode(max, per, RateLimitMode::Block)
}
pub fn with_rate_limit_mode(mut self, max: u32, per: Duration, mode: RateLimitMode) -> Self {
let cfg = RateLimitConfig {
max_requests: max,
per_millis: per.as_millis() as u64,
mode,
};
self.rate_limiter = Some(Arc::new(Mutex::new(RateLimiter::new(&cfg, Instant::now()))));
self.config.rate_limit = Some(cfg);
self
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn requests_made(&self) -> u64 {
self.requests_made.load(Ordering::Relaxed)
}
pub fn with_initial_request_count(self, count: u64) -> Self {
self.requests_made.store(count, Ordering::Relaxed);
self
}
pub fn with_daily_budget(mut self, max_per_day: u32, day_start_offset_secs: u32) -> Self {
let cfg = DailyBudgetConfig {
max_requests_per_day: max_per_day,
day_start_offset_secs,
};
self.daily_budget = Some(Arc::new(Mutex::new(DailyBudget::new(
&cfg,
Self::now_unix_secs(),
0,
))));
self.config.daily_budget = Some(cfg);
self
}
pub fn with_daily_spent(self, spent: u32) -> Self {
if let Some(daily) = &self.daily_budget {
lock_recover(daily).spent = spent;
}
self
}
pub fn daily_budget_state(&self) -> Option<DailyBudgetState> {
let daily = self.daily_budget.as_ref()?;
let mut guard = lock_recover(daily);
guard.roll(Self::now_unix_secs());
Some(DailyBudgetState {
window_start_unix: guard.window_start_unix,
spent: guard.spent,
max: guard.max,
})
}
fn apply_rate_limit(&self, operation: &str) -> Result<()> {
let now_secs = self.daily_budget.as_ref().map(|_| Self::now_unix_secs());
if let Some(daily) = &self.daily_budget {
let now = now_secs.expect("now read when daily_budget is set");
let mut guard = lock_recover(daily);
if let Err(wait) = guard.check(now) {
let offset = guard.day_start_offset_secs;
drop(guard);
return Err(AlgoError::daily_budget_exceeded(wait, offset).into());
}
}
if let Some(limiter) = &self.rate_limiter {
let reject = matches!(
self.config.rate_limit.as_ref().map(|c| c.mode),
Some(RateLimitMode::Reject)
);
loop {
let wait = lock_recover(limiter).poll(Instant::now());
if wait.is_zero() {
break;
}
if reject {
return Err(AlgoError::rate_limited(operation, wait).into());
}
std::thread::sleep(wait);
}
}
if let Some(daily) = &self.daily_budget {
let now = now_secs.expect("now read when daily_budget is set");
lock_recover(daily).record(now);
}
self.requests_made.fetch_add(1, Ordering::Relaxed);
Ok(())
}
pub fn unique_note() -> Vec<u8> {
let mut n = Vec::new();
n.extend_from_slice(Uuid::new_v4().as_bytes());
n
}
pub fn algod_client(&self) -> Result<algonaut::Algod> {
let url = format!(
"{}:{}",
self.config.client_api_url, self.config.client_api_port
);
let token = self.config.token.clone().unwrap_or_default();
algonaut::Algod::new(&url, &token)
.map_err(|e| anyhow!("failed to construct Algod client: {e}"))
}
pub fn indexer_client(&self) -> Result<algonaut::Indexer> {
let url = format!(
"{}:{}",
self.config.indexer_api_url, self.config.indexer_api_port
);
let token = self.config.token.clone().unwrap_or_default();
algonaut::Indexer::new(&url, &token)
.map_err(|e| anyhow!("failed to construct Indexer client: {e}"))
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) const RETRYABLE_STATUS_CODES: &'static [u16] = &[408, 425, 429, 502, 503, 504];
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) const INDEXER_READ_RETRYABLE_STATUS_CODES: &'static [u16] = &[500];
#[cfg(feature = "test-support")]
pub fn is_retryable(e: &algonaut::Error) -> bool {
Self::is_retryable_for(CallKind::Algod, e)
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn is_retryable_for(kind: CallKind, e: &algonaut::Error) -> bool {
match Self::http_status(e) {
Some(status) => {
Self::RETRYABLE_STATUS_CODES.contains(&status)
|| (kind == CallKind::IndexerRead
&& Self::INDEXER_READ_RETRYABLE_STATUS_CODES.contains(&status))
}
None => false,
}
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn http_status(e: &algonaut::Error) -> Option<u16> {
if let algonaut::Error::Request(req) = e
&& let algonaut::error::RequestErrorDetails::Http { status, .. } = &req.details
{
return Some(*status);
}
None
}
pub fn algod_call<T, F, Fut>(&self, make_fut: F) -> Result<T>
where
T: Send,
F: Fn() -> Fut,
Fut: Future<Output = Result<T, algonaut::Error>> + Send,
{
self.call_with_retry(CallKind::Algod, make_fut)
}
pub fn indexer_call<T, F, Fut>(&self, make_fut: F) -> Result<T>
where
T: Send,
F: Fn() -> Fut,
Fut: Future<Output = Result<T, algonaut::Error>> + Send,
{
self.call_with_retry(CallKind::IndexerRead, make_fut)
}
fn call_with_retry<T, F, Fut>(&self, kind: CallKind, make_fut: F) -> Result<T>
where
T: Send,
F: Fn() -> Fut,
Fut: Future<Output = Result<T, algonaut::Error>> + Send,
{
const MAX_RETRIES: u32 = 3;
const RETRY_BASE_MS: u64 = 1_000;
let operation = kind.operation();
let mut attempt = 0u32;
loop {
self.apply_rate_limit(operation)?;
let result = self
.rt_block_on(operation, make_fut())
.map_err(|e| anyhow!("runtime error: {e}"))?;
match result {
Ok(val) => return Ok(val),
Err(ref e) if attempt < MAX_RETRIES && Self::is_retryable_for(kind, e) => {
let delay = std::time::Duration::from_millis(RETRY_BASE_MS * (1u64 << attempt));
tracing::warn!(
"{} transient error (attempt {}/{}), retrying in {:?}: {}",
operation,
attempt + 1,
MAX_RETRIES,
delay,
e
);
std::thread::sleep(delay);
attempt += 1;
}
Err(e) => {
if attempt >= MAX_RETRIES && Self::is_retryable_for(kind, &e) {
return Err(AlgoError::transient(operation, &e.to_string()).into());
}
if let Some(status) = Self::http_status(&e) {
return Err(AlgoError::http(operation, status, &e.to_string()).into());
}
return Err(anyhow!("{e}"));
}
}
}
}
fn rt_block_on<T: Send>(
&self,
operation: &str,
fut: impl Future<Output = T> + Send,
) -> Result<T> {
let timeout = self.timeout;
let block = move || -> Result<T> {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| anyhow!("failed to build tokio runtime: {e}"))?;
rt.block_on(async move {
match timeout {
Some(dur) => tokio::time::timeout(dur, fut)
.await
.map_err(|_| anyhow!("{operation} exceeded timeout of {dur:?}")),
None => Ok(fut.await),
}
})
};
if tokio::runtime::Handle::try_current().is_ok() {
std::thread::scope(|s| {
s.spawn(block)
.join()
.map_err(|_| anyhow!("rt_block_on thread panicked"))?
})
} else {
block()
}
}
fn parse_address(addr: &str) -> Result<algonaut::core::Address> {
use std::str::FromStr;
algonaut::core::Address::from_str(addr).map_err(|e| anyhow!("invalid address: {e}"))
}
fn require_address(&self) -> Result<algonaut::core::Address> {
let addr_str = self
.address
.as_ref()
.ok_or_else(|| anyhow!("This operation needs an address"))?;
Self::parse_address(addr_str)
}
pub fn address_str(&self) -> Result<String> {
self.address
.as_ref()
.cloned()
.ok_or_else(|| anyhow!("This operation needs an address"))
}
fn json_get<'a>(o: &'a serde_json::Value, k1: &str, k2: &str) -> Option<&'a serde_json::Value> {
o.get(k1).or_else(|| o.get(k2))
}
fn decode_state_entries(entries: &[serde_json::Value]) -> Vec<(String, String)> {
let mut kvs: Vec<(String, String)> = Vec::new();
for entry in entries {
let key_b64 = match entry.get("key").and_then(|x| x.as_str()) {
Some(s) => s,
None => continue,
};
let key = match general_purpose::STANDARD.decode(key_b64) {
Ok(bytes) => String::from_utf8(bytes).unwrap_or_else(|_| key_b64.to_string()),
Err(_) => key_b64.to_string(),
};
let val_obj = match entry.get("value").and_then(|x| x.as_object()) {
Some(o) => o,
None => continue,
};
let vtype = val_obj.get("type").and_then(|x| x.as_u64()).unwrap_or(0);
let val = if vtype == 1 {
let bytes_opt = if let Some(arr) = val_obj.get("bytes").and_then(|x| x.as_array()) {
let mut buf: Vec<u8> = Vec::with_capacity(arr.len());
for n in arr {
if let Some(u) = n.as_u64() {
buf.push((u & 0xFF) as u8);
} else if let Some(i) = n.as_i64()
&& i >= 0
{
buf.push(((i as u64) & 0xFF) as u8);
}
}
Some(buf)
} else if let Some(b64) = val_obj.get("bytes").and_then(|x| x.as_str()) {
general_purpose::STANDARD.decode(b64).ok()
} else {
None
};
if let Some(bytes) = bytes_opt {
match String::from_utf8(bytes.clone()) {
Ok(s) => s,
Err(_) => {
let mut hex = String::from("0x");
for byte in bytes {
hex.push_str(&format!("{:02x}", byte));
}
hex
}
}
} else {
String::new()
}
} else {
val_obj
.get("uint")
.and_then(|x| x.as_u64())
.map(|u| u.to_string())
.unwrap_or_else(|| "0".to_string())
};
kvs.push((key, val));
}
kvs
}
pub fn create_address(&mut self) -> Result<String> {
use ed25519_dalek::SigningKey;
use rand_core::{OsRng, RngCore};
let mut rng = OsRng;
let mut sk: [u8; 32] = [0u8; 32];
rng.fill_bytes(&mut sk);
let signing_key = SigningKey::from_bytes(&sk);
let verifying_key = signing_key.verifying_key();
let pk: [u8; 32] = verifying_key.to_bytes();
let addr = byte_key_to_address(&pk)?;
self.address = Some(addr.clone());
let sk_b64 = general_purpose::STANDARD.encode(sk);
self.passphrase = Some(format!("b64:{}", sk_b64));
Ok(addr)
}
pub fn public_key_bytes(&self) -> Result<[u8; 32]> {
let addr = self
.address
.as_ref()
.ok_or_else(|| anyhow!("This operation needs an address"))?;
address_to_byte_key(addr)
}
pub fn private_key_bytes(&self) -> Result<Vec<u8>> {
let pass = self
.passphrase
.as_ref()
.ok_or_else(|| anyhow!("This operation needs account access"))?;
Ok(Self::seed_from_passphrase(pass)?.to_vec())
}
pub fn contract_address(&self, app_id: u64) -> Result<String> {
use sha2::{Digest, Sha512_256};
let mut hasher = Sha512_256::new();
hasher.update(b"appID");
hasher.update(app_id.to_be_bytes());
let pk_bytes: [u8; 32] = hasher.finalize().into();
byte_key_to_address(&pk_bytes)
}
pub fn sign(&self, text: &str) -> Result<String> {
use ed25519_dalek::{Signer, SigningKey};
let sk_bytes = self.private_key_bytes()?;
let sk_arr: [u8; 32] = sk_bytes
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let signing_key = SigningKey::from_bytes(&sk_arr);
let signature = signing_key.sign(text.as_bytes());
Ok(general_purpose::STANDARD.encode(signature.to_bytes()))
}
pub fn sign_bytes(&self, message: &[u8]) -> Result<[u8; 64]> {
use ed25519_dalek::{Signer, SigningKey};
let sk_bytes = self.private_key_bytes()?;
let sk_arr: [u8; 32] = sk_bytes
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let signing_key = SigningKey::from_bytes(&sk_arr);
Ok(signing_key.sign(message).to_bytes())
}
pub fn sign_notify_envelope(
&self,
route: &str,
iss: &str,
audience: &str,
token: &str,
env: &str,
nonce: &str,
exp: i64,
) -> Result<String> {
use ed25519_dalek::{Signer, SigningKey};
use sha2::{Digest, Sha256};
let body = match route {
"register" => format!("{token}\n{env}"),
"alert" => String::new(),
other => bail!("unknown notify route: {other}"),
};
let body_hash = HEXLOWER.encode(&Sha256::digest(body.as_bytes()));
let msg =
format!("bingle-notify:v1\n{route}\n{iss}\n{audience}\n{body_hash}\n{nonce}\n{exp}");
let sk_bytes = self.private_key_bytes()?;
let sk_arr: [u8; 32] = sk_bytes
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let signing_key = SigningKey::from_bytes(&sk_arr);
let mut signed = Vec::with_capacity(2 + msg.len());
signed.extend_from_slice(b"MX");
signed.extend_from_slice(msg.as_bytes());
let signature = signing_key.sign(&signed);
Ok(general_purpose::STANDARD.encode(signature.to_bytes()))
}
pub fn verify(&self, text: &str, sig_b64: &str) -> Result<bool> {
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
let sig_bytes = match general_purpose::STANDARD.decode(sig_b64) {
Ok(b) => b,
Err(_) => return Ok(false),
};
if sig_bytes.len() != 64 {
return Ok(false);
}
let sig_arr: [u8; 64] = match sig_bytes.try_into() {
Ok(a) => a,
Err(_) => return Ok(false),
};
let signature = Signature::from_bytes(&sig_arr);
let pk = self.public_key_bytes()?;
let vk = VerifyingKey::from_bytes(&pk)
.map_err(|e| anyhow!("invalid verifying key from address: {e}"))?;
Ok(vk.verify(text.as_bytes(), &signature).is_ok())
}
pub fn account_balance(&self) -> Result<Option<f64>> {
let client = match self.algod_client() {
Ok(c) => c,
Err(e) => {
tracing::error!("[account_balance] Failed to access algod client: {}", e);
return Err(e);
}
};
let address = match self.require_address() {
Ok(a) => a,
Err(e) => {
tracing::error!("[account_balance] Failed to resolve address: {}", e);
return Err(e);
}
};
let info = match self.algod_call(|| client.account(&address)) {
Ok(r) => r,
Err(e) => {
if AlgoError::is_host_unreachable(&e) {
tracing::debug!(
"[account_balance] account information unreachable for {}: {}",
address,
e
);
return Err(
AlgoError::unreachable("account_information", &e.to_string()).into(),
);
}
tracing::error!(
"[account_balance] Failed to fetch account information for {}: {}",
address,
e
);
return Err(e);
}
};
let micro: u64 = info.amount;
algo_log!(
"[account_balance] Balance for address {} is {} microalgos",
address,
micro
);
Ok(Some(micro as f64 / 1_000_000.0))
}
pub fn global_state(
&self,
maybe_app_id: Option<u64>,
) -> Result<Option<Vec<(u64, Vec<(String, String)>)>>> {
let client = self.algod_client()?;
let address = self.require_address()?;
let info = match self.algod_call(|| client.account(&address)) {
Ok(v) => v,
Err(e) if AlgoError::is_host_unreachable(&anyhow!(e.to_string())) => {
return Err(AlgoError::unreachable("account_information", &e.to_string()).into());
}
Err(_) => return Ok(None),
};
let v = serde_json::to_value(&info)
.map_err(|e| anyhow!("failed to serialize account info: {e}"))?;
let created =
match Self::json_get(&v, "created_apps", "created-apps").and_then(|x| x.as_array()) {
Some(a) => a,
None => return Ok(Some(vec![])),
};
let mut out: Vec<(u64, Vec<(String, String)>)> = Vec::new();
for app in created {
let id = match app.get("id").and_then(|x| x.as_u64()) {
Some(i) => i,
None => continue,
};
if let Some(filter) = maybe_app_id
&& filter != id
{
continue;
}
let params = match app.get("params").and_then(|x| x.as_object()) {
Some(p) => p,
None => continue,
};
let params_value = serde_json::Value::Object(params.clone());
let gs_vec: Vec<serde_json::Value> =
Self::json_get(¶ms_value, "global_state", "global-state")
.and_then(|x| x.as_array())
.cloned()
.unwrap_or_default();
let kvs = Self::decode_state_entries(&gs_vec);
out.push((id, kvs));
}
Ok(Some(out))
}
pub fn app_global_bytes(&self, app_id: u64, key: &str) -> Result<Option<Vec<u8>>> {
if app_id == 0 {
bail!("app_id must be > 0");
}
let client = self.algod_client()?;
let app_info = match self.algod_call(|| client.app(algonaut::core::AppId(app_id))) {
Ok(v) => v,
Err(e) if AlgoError::is_host_unreachable(&anyhow!(e.to_string())) => {
return Err(AlgoError::unreachable("app_information", &e.to_string()).into());
}
Err(_) => return Ok(None),
};
let v = serde_json::to_value(&app_info)
.map_err(|e| anyhow!("failed to serialize app info: {e}"))?;
let params = match Self::json_get(&v, "params", "params").and_then(|x| x.as_object()) {
Some(p) => serde_json::Value::Object(p.clone()),
None => return Ok(None),
};
let gs: Vec<serde_json::Value> = Self::json_get(¶ms, "global_state", "global-state")
.and_then(|x| x.as_array())
.cloned()
.unwrap_or_default();
for entry in &gs {
let key_b64 = match entry.get("key").and_then(|x| x.as_str()) {
Some(s) => s,
None => continue,
};
let entry_key = match general_purpose::STANDARD.decode(key_b64) {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(s) => s,
Err(_) => continue,
},
Err(_) => continue,
};
if entry_key != key {
continue;
}
let val_obj = match entry.get("value").and_then(|x| x.as_object()) {
Some(o) => o,
None => continue,
};
let bytes = if let Some(arr) = val_obj.get("bytes").and_then(|x| x.as_array()) {
let mut buf: Vec<u8> = Vec::with_capacity(arr.len());
for n in arr {
if let Some(u) = n.as_u64() {
buf.push((u & 0xFF) as u8);
} else if let Some(i) = n.as_i64()
&& i >= 0
{
buf.push(((i as u64) & 0xFF) as u8);
}
}
Some(buf)
} else if let Some(b64) = val_obj.get("bytes").and_then(|x| x.as_str()) {
general_purpose::STANDARD.decode(b64).ok()
} else {
None
};
return Ok(bytes);
}
Ok(None)
}
pub fn get_app_local_schema(&self, app_id: u64) -> Result<(u64, u64)> {
if app_id == 0 {
bail!("app_id must be > 0");
}
let client = self.algod_client()?;
let app_info = self
.algod_call(|| client.app(algonaut::core::AppId(app_id)))
.map_err(|e| anyhow!("application_information failed: {e}"))?;
let v = serde_json::to_value(&app_info)
.map_err(|e| anyhow!("failed to serialize application info: {e}"))?;
let schema = v
.get("params")
.and_then(|p| {
p.get("local-state-schema")
.or_else(|| p.get("local_state_schema"))
})
.ok_or_else(|| anyhow!("local-state-schema missing for app_id {app_id}"))?;
let num_uints = schema
.get("num-uint")
.or_else(|| schema.get("num_uint"))
.and_then(|x| x.as_u64())
.unwrap_or(0);
let num_byte_slices = schema
.get("num-byte-slice")
.or_else(|| schema.get("num_byte_slice"))
.and_then(|x| x.as_u64())
.unwrap_or(0);
Ok((num_uints, num_byte_slices))
}
pub fn local_state_for_account(
&self,
app_id: u64,
account_address: &str,
) -> Result<Option<Vec<(String, String)>>> {
let client = self.algod_client()?;
let address = Self::parse_address(account_address)?;
let info = match self.algod_call(|| client.account(&address)) {
Ok(v) => v,
Err(e) if AlgoError::is_host_unreachable(&anyhow!(e.to_string())) => {
return Err(AlgoError::unreachable("account_information", &e.to_string()).into());
}
Err(_) => return Ok(None),
};
algo_log!("Retrieved account info for address: {}", account_address);
let v = serde_json::to_value(&info)
.map_err(|e| anyhow!("failed to serialize account info: {e}"))?;
Ok(Self::decode_app_local_state(&v, app_id))
}
fn decode_app_local_state(
account_json: &serde_json::Value,
app_id: u64,
) -> Option<Vec<(String, String)>> {
let als =
Self::json_get(account_json, "apps_local_state", "apps-local-state")?.as_array()?;
for st in als {
if st.get("id").and_then(|x| x.as_u64()) == Some(app_id) {
let keyvals_vec: Vec<serde_json::Value> =
Self::json_get(st, "key_value", "key-value")
.and_then(|x| x.as_array())
.cloned()
.unwrap_or_default();
return Some(Self::decode_state_entries(&keyvals_vec));
}
}
None
}
pub fn send_algo(&self, to_address: &str, amount_algos: f64) -> Result<()> {
if amount_algos <= 0.0 {
bail!("amount must be positive");
}
let sk = self.private_key_bytes()?;
let from = self.require_address()?;
let to = Self::parse_address(to_address)?;
let client = self.algod_client()?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let micro = (amount_algos * 1_000_000.0).round() as u64;
let tx = algonaut::transaction::Pay::new(from, to, algonaut::core::MicroAlgos(micro))
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build transaction: {e}"))?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)?;
Ok(())
}
pub fn create_asset(&self, name: &str, units_in_issue: u64) -> Result<Option<u64>> {
if name.trim().is_empty() {
bail!("asset name must not be empty");
}
if units_in_issue == 0 {
bail!("units_in_issue must be > 0");
}
let sk = self.private_key_bytes()?;
let issuer = self.require_address()?;
let client = self.algod_client()?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let tx = algonaut::transaction::CreateAsset::new(issuer, units_in_issue, 0, false)
.manager(issuer)
.reserve(issuer)
.clawback(issuer)
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build asset create transaction: {e}"))?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign asset create transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)?;
let tx_id_obj = algonaut::core::TransactionId::from(tx_id.as_str());
let info = self
.algod_call(|| client.pending_transaction(&tx_id_obj))
.map_err(|e| anyhow!("failed to fetch pending transaction info for asset id: {e}"))?;
Ok(info.asset_index.or(Some(0)).filter(|id| *id != 0))
}
pub fn create_asset_configured(
&self,
name: &str,
units_in_issue: u64,
manager_addr: &str,
reserve_addr: &str,
clawback_addr: &str,
freeze_addr: &str,
) -> Result<Option<u64>> {
if name.trim().is_empty() {
bail!("asset name must not be empty");
}
if units_in_issue == 0 {
bail!("units_in_issue must be > 0");
}
let sk = self.private_key_bytes()?;
let issuer = self.require_address()?;
let manager = Self::parse_address(manager_addr)?;
let reserve = Self::parse_address(reserve_addr)?;
let clawback = Self::parse_address(clawback_addr)?;
let freeze = Self::parse_address(freeze_addr)?;
let client = self.algod_client()?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let tx = algonaut::transaction::CreateAsset::new(issuer, units_in_issue, 0, false)
.manager(manager)
.reserve(reserve)
.clawback(clawback)
.freeze(freeze)
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build asset create transaction: {e}"))?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign asset create transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)?;
let tx_id_obj = algonaut::core::TransactionId::from(tx_id.as_str());
let info = self
.algod_call(|| client.pending_transaction(&tx_id_obj))
.map_err(|e| anyhow!("failed to fetch pending transaction info for asset id: {e}"))?;
Ok(info.asset_index.or(Some(0)).filter(|id| *id != 0))
}
pub fn create_asset_with_reserve_app(
&self,
name: &str,
units_in_issue: u64,
app_id: u64,
) -> Result<Option<u64>> {
if app_id == 0 {
bail!("app_id must be > 0");
}
let app_addr = self.contract_address(app_id)?;
let issuer_addr = self.address_str()?;
self.create_asset_configured(
name,
units_in_issue,
&issuer_addr,
&app_addr,
&app_addr,
&issuer_addr,
)
}
pub fn is_account_opted_in_to_asset(
&self,
account_address: &str,
asset_id: u64,
) -> Result<bool> {
if asset_id == 0 {
bail!("asset_id must be > 0");
}
let client = self.algod_client()?;
let address = Self::parse_address(account_address)?;
let info = match self.algod_call(|| client.account(&address)) {
Ok(v) => v,
Err(_) => return Ok(false),
};
let v = serde_json::to_value(&info)
.map_err(|e| anyhow!("failed to serialize account info: {e}"))?;
let assets_arr = v
.get("assets")
.or_else(|| v.get("assets"))
.and_then(|x| x.as_array())
.cloned()
.unwrap_or_default();
for a in assets_arr {
let id = a
.get("asset-id")
.and_then(|x| x.as_u64())
.or_else(|| a.get("asset_id").and_then(|x| x.as_u64()))
.unwrap_or(0);
if id == asset_id {
return Ok(true);
}
}
Ok(false)
}
pub fn asset_holding(&self, account_address: &str, asset_id: u64) -> Result<u64> {
let client = self.algod_client()?;
let address = Self::parse_address(account_address)?;
let info = self
.algod_call(|| client.account(&address))
.map_err(|e| anyhow!("failed to fetch account information: {e}"))?;
let v = serde_json::to_value(&info)
.map_err(|e| anyhow!("failed to serialize account info: {e}"))?;
Ok(Self::parse_holding_amount_from_account_value(&v, asset_id))
}
pub fn account_funds(&self, account_address: &str) -> Result<AlgoAccountFunds> {
let client = self.algod_client()?;
let address = Self::parse_address(account_address)?;
let info = match self.algod_call(|| client.account(&address)) {
Ok(info) => info,
Err(e) if AlgoError::is_host_unreachable(&e) => {
return Err(AlgoError::unreachable("account_funds", &e.to_string()).into());
}
Err(e) => {
return Err(AlgoError::contextualize(
&format!("failed to fetch account information for {account_address}"),
e,
));
}
};
Ok(AlgoAccountFunds {
amount: info.amount,
min_balance: info.min_balance,
})
}
pub fn microalgos_at(&self, account_address: &str) -> Result<u64> {
let client = self.algod_client()?;
let address = Self::parse_address(account_address)?;
let info = self.algod_call(|| client.account(&address)).map_err(|e| {
anyhow!("failed to fetch account information for {account_address}: {e}")
})?;
Ok(info.amount)
}
pub fn round(&self) -> Result<u64> {
let client = self.algod_client()?;
let status = match self.algod_call(|| client.status()) {
Ok(v) => v,
Err(e) if AlgoError::is_host_unreachable(&e) => {
return Err(AlgoError::unreachable("node_status", &e.to_string()).into());
}
Err(e) => return Err(AlgoError::contextualize("failed to get node status", e)),
};
Ok(status.last_round.0)
}
pub fn block_seed(&self, round: u64) -> Result<Vec<u8>> {
let url = format!(
"{}:{}/v2/blocks/{round}?format=json",
self.config.client_api_url, self.config.client_api_port
);
let token = self.config.token.clone().unwrap_or_default();
let token_header = self
.config
.token_key
.clone()
.unwrap_or_else(|| "X-Algo-API-Token".to_string());
let fetched: std::result::Result<String, (bool, String)> =
self.rt_block_on("algod call", async move {
let response = reqwest::Client::new()
.get(url.as_str())
.header(token_header.as_str(), token.as_str())
.send()
.await
.map_err(|e| (e.is_connect() || e.is_timeout(), e.to_string()))?;
let status = response.status();
let body = response.text().await.map_err(|e| (false, e.to_string()))?;
if status.is_success() {
Ok(body)
} else {
Err((false, format!("HTTP {status}: {body}")))
}
})?;
let body = fetched.map_err(|(unreachable, message)| {
if unreachable {
AlgoError::unreachable("block", &message).into()
} else {
anyhow!("failed to fetch block {round}: {message}")
}
})?;
Self::parse_block_header_seed(body.as_bytes(), round)
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn parse_block_header_seed(body: &[u8], round: u64) -> Result<Vec<u8>> {
#[derive(Deserialize)]
struct BlockHeaderResponse {
block: BlockHeaderSeed,
}
#[derive(Deserialize)]
struct BlockHeaderSeed {
seed: String, }
let parsed: BlockHeaderResponse = serde_json::from_slice(body)
.map_err(|e| anyhow!("failed to parse block {round} header seed: {e}"))?;
let seed = general_purpose::STANDARD
.decode(parsed.block.seed.as_bytes())
.map_err(|e| anyhow!("block {round} seed is not valid base64: {e}"))?;
if seed.len() != 32 {
bail!("block {round} seed is {} bytes, expected 32", seed.len());
}
Ok(seed)
}
pub fn suggested_params(&self) -> Result<AlgoSuggestedParams> {
let client = self.algod_client()?;
let params = match self.algod_call(|| client.suggested_params()) {
Ok(v) => v,
Err(e) if AlgoError::is_host_unreachable(&e) => {
return Err(AlgoError::unreachable("suggested_params", &e.to_string()).into());
}
Err(e) => {
return Err(AlgoError::contextualize(
"failed to fetch suggested params",
e,
));
}
};
Ok(AlgoSuggestedParams {
last_round: params.last_round.0,
min_fee: params.min_fee.0,
genesis_hash: params.genesis_hash.0,
genesis_id: params.genesis_id,
})
}
pub fn submit_signed(&self, signed_txn: &[u8]) -> Result<String> {
if signed_txn.is_empty() {
bail!("signed_txn must not be empty");
}
let client = self.algod_client()?;
let resp = match self.algod_call(|| client.send_raw(signed_txn)) {
Ok(v) => v,
Err(e) if AlgoError::is_host_unreachable(&e) => {
return Err(AlgoError::unreachable("send_raw", &e.to_string()).into());
}
Err(e) => return Err(AlgoError::contextualize("send_raw failed", e)),
};
Ok(resp.tx_id)
}
pub fn confirmed_transaction(&self, txid: &str) -> Result<Option<ConfirmedTxn>> {
if txid.trim().is_empty() {
bail!("txid must not be empty");
}
let client = self.algod_client()?;
let tx_id_obj = algonaut::core::TransactionId::from(txid);
let resp = match self.algod_call(|| client.pending_transaction(&tx_id_obj)) {
Ok(v) => v,
Err(e) if AlgoError::is_host_unreachable(&e) => {
return Err(AlgoError::unreachable("pending_transaction", &e.to_string()).into());
}
Err(e)
if e.downcast_ref::<AlgoError>()
.is_some_and(AlgoError::is_quota) =>
{
return Err(e);
}
Err(_) => return Ok(None),
};
let confirmed_round = resp.confirmed_round.unwrap_or(0);
let note = match &resp.txn.txn {
Some(txn) => {
let v = serde_json::to_value(txn)
.map_err(|e| anyhow!("failed to serialize pending transaction: {e}"))?;
v.get("note")
.and_then(|x| x.as_str())
.and_then(|s| general_purpose::STANDARD.decode(s).ok())
}
None => None,
};
Ok(Some(ConfirmedTxn {
confirmed_round,
note,
}))
}
fn find_confirmed_note_matching(
&self,
query: &[u8],
sender: Option<&str>,
matches: impl Fn(&[u8]) -> bool,
) -> Result<Option<ConfirmedTxn>> {
let client = self.indexer_client()?;
let note_prefix = general_purpose::STANDARD.encode(query);
let mut next: Option<String> = None;
loop {
let (candidates, next_token) =
self.confirmed_notes_page(&client, ¬e_prefix, sender, next.as_deref())?;
if let Some((confirmed_round, note)) =
candidates.into_iter().find(|(_, note)| matches(note))
{
return Ok(Some(ConfirmedTxn {
confirmed_round,
note: Some(note),
}));
}
match next_token {
Some(token) => next = Some(token),
None => return Ok(None),
}
}
}
fn collect_confirmed_notes_matching(
&self,
query: &[u8],
sender: Option<&str>,
matches: impl Fn(&[u8]) -> bool,
) -> Result<Vec<ConfirmedTxn>> {
let client = self.indexer_client()?;
let note_prefix = general_purpose::STANDARD.encode(query);
let mut found = Vec::new();
let mut next: Option<String> = None;
loop {
let (candidates, next_token) =
self.confirmed_notes_page(&client, ¬e_prefix, sender, next.as_deref())?;
found.extend(
candidates
.into_iter()
.filter(|(_, note)| matches(note))
.map(|(confirmed_round, note)| ConfirmedTxn {
confirmed_round,
note: Some(note),
}),
);
match next_token {
Some(token) => next = Some(token),
None => return Ok(found),
}
}
}
fn confirmed_notes_page(
&self,
client: &algonaut::Indexer,
note_prefix: &str,
sender: Option<&str>,
next: Option<&str>,
) -> Result<(Vec<(u64, Vec<u8>)>, Option<String>)> {
let address = sender.map(Self::parse_address).transpose()?;
let resp = match self.indexer_call(|| {
client.search_for_transactions(
None, next, Some(note_prefix), None, None, None, None, None, None, None, None, None, None, None, address.as_ref(), sender.map(|_| "sender"),
None, None, None, )
}) {
Ok(v) => v,
Err(e) if AlgoError::is_host_unreachable(&e) => {
return Err(
AlgoError::unreachable("search_for_transactions", &e.to_string()).into(),
);
}
Err(e) => return Err(e),
};
let candidates = resp
.transactions
.into_iter()
.filter_map(|txn| {
let confirmed_round = txn.confirmed_round.filter(|r| *r > 0)?;
let note = txn.note.map(|b| b.0)?;
Some((confirmed_round, note))
})
.collect();
let next_token = match resp.next_token {
Some(token) if !token.is_empty() => Some(token),
_ => None,
};
Ok((candidates, next_token))
}
pub fn find_transaction_by_note(&self, note: &[u8]) -> Result<Option<ConfirmedTxn>> {
if note.is_empty() {
bail!("note must not be empty");
}
self.find_confirmed_note_matching(note, None, |candidate| candidate == note)
}
pub fn find_transaction_by_note_and_sender(
&self,
note: &[u8],
sender: &str,
) -> Result<Option<ConfirmedTxn>> {
if note.is_empty() {
bail!("note must not be empty");
}
if sender.is_empty() {
bail!("sender must not be empty");
}
self.find_confirmed_note_matching(note, Some(sender), |candidate| candidate == note)
}
pub fn find_transaction_by_note_prefix(&self, prefix: &[u8]) -> Result<Option<ConfirmedTxn>> {
if prefix.is_empty() {
bail!("prefix must not be empty");
}
self.find_confirmed_note_matching(prefix, None, |candidate| candidate.starts_with(prefix))
}
pub fn find_transaction_by_note_prefix_and_sender(
&self,
prefix: &[u8],
sender: &str,
) -> Result<Option<ConfirmedTxn>> {
if prefix.is_empty() {
bail!("prefix must not be empty");
}
if sender.is_empty() {
bail!("sender must not be empty");
}
self.find_confirmed_note_matching(prefix, Some(sender), |candidate| {
candidate.starts_with(prefix)
})
}
pub fn find_transactions_by_note_prefix(&self, prefix: &[u8]) -> Result<Vec<ConfirmedTxn>> {
if prefix.is_empty() {
bail!("prefix must not be empty");
}
self.collect_confirmed_notes_matching(prefix, None, |candidate| {
candidate.starts_with(prefix)
})
}
pub fn find_transactions_by_note_prefix_and_sender(
&self,
prefix: &[u8],
sender: &str,
) -> Result<Vec<ConfirmedTxn>> {
if prefix.is_empty() {
bail!("prefix must not be empty");
}
if sender.is_empty() {
bail!("sender must not be empty");
}
self.collect_confirmed_notes_matching(prefix, Some(sender), |candidate| {
candidate.starts_with(prefix)
})
}
pub fn fetch_transactions_cached<T>(
&self,
cache: &Mutex<TxnScanCache<T>>,
filter: TxnScanFilter,
mode: QueryMode,
cache_lifetime_secs: Option<u64>,
ingest: impl Fn(&ScannedTxn) -> Option<T>,
) -> Result<()> {
let client = self.indexer_client()?;
let prepared = filter.prepare()?;
let now = Self::now_unix_secs();
Self::fetch_transactions_cached_with(
cache,
mode,
cache_lifetime_secs,
now,
ingest,
|min_round, next| self.fetch_scan_page(&client, &prepared, min_round, next),
)
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn fetch_transactions_cached_with<T>(
cache: &Mutex<TxnScanCache<T>>,
mode: QueryMode,
cache_lifetime_secs: Option<u64>,
now: u64,
ingest: impl Fn(&ScannedTxn) -> Option<T>,
mut fetch_page: impl FnMut(Option<u64>, Option<&str>) -> Result<TxnScanPage>,
) -> Result<()> {
let mut cache = cache
.lock()
.map_err(|_| anyhow!("transaction scan cache mutex poisoned"))?;
let fetch_from: Option<Option<u64>> = match mode {
QueryMode::CacheOnly => None,
QueryMode::ForceFull => {
cache.entries.clear();
cache.last_round = 0;
Some(None)
}
QueryMode::Refresh => {
if cache.last_updated == 0 {
Some(None)
} else if Self::scan_cache_is_fresh(cache.last_updated, now, cache_lifetime_secs) {
None
} else {
Some(Some(cache.last_round + 1))
}
}
};
if let Some(min_round) = fetch_from {
let mut watermark = cache.last_round;
let mut next: Option<String> = None;
loop {
let page = fetch_page(min_round, next.as_deref())?;
watermark = watermark.max(page.current_round);
for txn in &page.txns {
if let Some(entry) = ingest(txn) {
cache.entries.push(entry);
}
}
match page.next_token {
Some(token) => next = Some(token),
None => break,
}
}
cache.last_round = watermark;
cache.last_updated = now;
}
Ok(())
}
fn scan_cache_is_fresh(last_updated: u64, now: u64, lifetime: Option<u64>) -> bool {
match lifetime {
Some(secs) => now.saturating_sub(last_updated) < secs,
None => false,
}
}
fn now_unix_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
fn fetch_scan_page(
&self,
client: &algonaut::Indexer,
filter: &PreparedScanFilter,
min_round: Option<u64>,
next: Option<&str>,
) -> Result<TxnScanPage> {
let resp = match self.indexer_call(|| {
client.search_for_transactions(
None, next, filter.note_prefix.as_deref(), None, None, None, None, min_round, None, None, None, None, None, None, filter.address.as_ref(), filter.address.as_ref().map(|_| "sender"),
None, None, filter.app_id, )
}) {
Ok(v) => v,
Err(e) if AlgoError::is_host_unreachable(&e) => {
return Err(
AlgoError::unreachable("search_for_transactions", &e.to_string()).into(),
);
}
Err(e) => return Err(e),
};
let txns = resp
.transactions
.into_iter()
.filter_map(|txn| {
let confirmed_round = txn.confirmed_round.filter(|r| *r > 0)?;
Some(ScannedTxn {
confirmed_round,
sender: txn.sender,
note: txn.note.map(|b| b.0),
})
})
.collect();
let next_token = match resp.next_token {
Some(token) if !token.is_empty() => Some(token),
_ => None,
};
Ok(TxnScanPage {
txns,
next_token,
current_round: resp.current_round,
})
}
pub fn fetch_opted_in_accounts_cached<T>(
&self,
app_id: u64,
cache: &Mutex<AccountScanCache<T>>,
mode: QueryMode,
cache_lifetime_secs: Option<u64>,
ingest: impl Fn(&ScannedAccount) -> Option<T>,
) -> Result<()> {
if app_id == 0 {
bail!("app_id must be > 0");
}
let client = self.indexer_client()?;
let now = Self::now_unix_secs();
Self::fetch_opted_in_accounts_cached_with(
cache,
mode,
cache_lifetime_secs,
now,
ingest,
|next| self.fetch_account_page(&client, app_id, next),
|min_round, next| self.fetch_changed_addresses_page(&client, app_id, min_round, next),
|address| self.lookup_opted_in_account(&client, app_id, address),
)
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn fetch_opted_in_accounts_cached_with<T>(
cache: &Mutex<AccountScanCache<T>>,
mode: QueryMode,
cache_lifetime_secs: Option<u64>,
now: u64,
ingest: impl Fn(&ScannedAccount) -> Option<T>,
mut fetch_full_page: impl FnMut(Option<&str>) -> Result<AccountScanPage>,
mut fetch_changed: impl FnMut(u64, Option<&str>) -> Result<ChangedAddressesPage>,
mut lookup_account: impl FnMut(&str) -> Result<Option<ScannedAccount>>,
) -> Result<()> {
let mut cache = cache
.lock()
.map_err(|_| anyhow!("account scan cache mutex poisoned"))?;
let scan: Option<bool> = match mode {
QueryMode::CacheOnly => None,
QueryMode::ForceFull => {
cache.entries.clear();
cache.last_round = 0;
Some(true)
}
QueryMode::Refresh => {
if cache.last_updated == 0 || cache.last_round == 0 {
Some(true)
} else if Self::scan_cache_is_fresh(cache.last_updated, now, cache_lifetime_secs) {
None
} else {
Some(false)
}
}
};
match scan {
None => {}
Some(true) => {
cache.entries.clear();
let mut watermark: Option<u64> = None;
let mut next: Option<String> = None;
loop {
let page = fetch_full_page(next.as_deref())?;
watermark = Some(match watermark {
Some(w) => w.min(page.current_round),
None => page.current_round,
});
for acct in &page.accounts {
if let Some(entry) = ingest(acct) {
cache.entries.push((acct.address.clone(), entry));
}
}
match page.next_token {
Some(token) => next = Some(token),
None => break,
}
}
cache.last_round = watermark.unwrap_or(cache.last_round);
cache.last_updated = now;
}
Some(false) => {
let min_round = cache.last_round + 1;
let mut watermark = cache.last_round;
let mut next: Option<String> = None;
let mut seen: HashSet<String> = HashSet::new();
let mut changed: Vec<String> = Vec::new();
loop {
let page = fetch_changed(min_round, next.as_deref())?;
watermark = watermark.max(page.current_round);
for addr in page.addresses {
if seen.insert(addr.clone()) {
changed.push(addr);
}
}
match page.next_token {
Some(token) => next = Some(token),
None => break,
}
}
for addr in &changed {
match lookup_account(addr)? {
Some(acct) => match ingest(&acct) {
Some(entry) => {
Self::upsert_account_entry(&mut cache.entries, addr, entry)
}
None => Self::remove_account_entry(&mut cache.entries, addr),
},
None => Self::remove_account_entry(&mut cache.entries, addr),
}
}
cache.last_round = watermark;
cache.last_updated = now;
}
}
Ok(())
}
fn upsert_account_entry<T>(entries: &mut Vec<(String, T)>, address: &str, entry: T) {
if let Some(slot) = entries.iter_mut().find(|(a, _)| a == address) {
slot.1 = entry;
} else {
entries.push((address.to_string(), entry));
}
}
fn remove_account_entry<T>(entries: &mut Vec<(String, T)>, address: &str) {
entries.retain(|(a, _)| a != address);
}
fn fetch_account_page(
&self,
client: &algonaut::Indexer,
app_id: u64,
next: Option<&str>,
) -> Result<AccountScanPage> {
let resp = match self.indexer_call(|| {
client.search_for_accounts(
None, None, next, None, None, Self::account_scan_excludes(), None, None, None, Some(algonaut::core::AppId(app_id)), )
}) {
Ok(v) => v,
Err(e) if AlgoError::is_host_unreachable(&e) => {
return Err(AlgoError::unreachable("search_for_accounts", &e.to_string()).into());
}
Err(e) => return Err(e),
};
let mut accounts = Vec::with_capacity(resp.accounts.len());
for acct in &resp.accounts {
let v = serde_json::to_value(acct)
.map_err(|e| anyhow!("failed to serialize account: {e}"))?;
accounts.push(Self::scanned_account_from(&v, app_id));
}
let next_token = match resp.next_token {
Some(token) if !token.is_empty() => Some(token),
_ => None,
};
Ok(AccountScanPage {
accounts,
next_token,
current_round: resp.current_round,
})
}
fn fetch_changed_addresses_page(
&self,
client: &algonaut::Indexer,
app_id: u64,
min_round: u64,
next: Option<&str>,
) -> Result<ChangedAddressesPage> {
let resp = match self.indexer_call(|| {
client.search_for_transactions(
None, next, None, None, None, None, None, Some(min_round), None, None, None, None, None, None, None, None, None, None, Some(algonaut::core::AppId(app_id)), )
}) {
Ok(v) => v,
Err(e) if AlgoError::is_host_unreachable(&e) => {
return Err(
AlgoError::unreachable("search_for_transactions", &e.to_string()).into(),
);
}
Err(e) => return Err(e),
};
let mut addresses = Vec::new();
for txn in &resp.transactions {
Self::collect_changed_addresses(txn, &mut addresses);
}
let next_token = match resp.next_token {
Some(token) if !token.is_empty() => Some(token),
_ => None,
};
Ok(ChangedAddressesPage {
addresses,
next_token,
current_round: resp.current_round,
})
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn collect_changed_addresses(
txn: &algonaut::model::indexer::Transaction,
out: &mut Vec<String>,
) {
out.push(txn.sender.clone());
if let Some(app_txn) = &txn.application_transaction {
if let Some(accounts) = &app_txn.accounts {
for addr in accounts {
out.push(addr.clone());
}
}
}
if let Some(inner_txns) = &txn.inner_txns {
for inner in inner_txns {
Self::collect_changed_addresses(inner, out);
}
}
}
fn lookup_opted_in_account(
&self,
client: &algonaut::Indexer,
app_id: u64,
address: &str,
) -> Result<Option<ScannedAccount>> {
let addr = Self::parse_address(address)?;
let resp = match self.indexer_call(|| {
client.lookup_account_by_id(&addr, None, None, Self::account_scan_excludes())
}) {
Ok(v) => v,
Err(e)
if e.downcast_ref::<AlgoError>()
.is_some_and(|algo_err| algo_err.status() == Some(404)) =>
{
return Ok(None);
}
Err(e) if AlgoError::is_host_unreachable(&e) => {
return Err(AlgoError::unreachable("lookup_account_by_id", &e.to_string()).into());
}
Err(e) => return Err(e),
};
let acct = *resp.account;
let v =
serde_json::to_value(&acct).map_err(|e| anyhow!("failed to serialize account: {e}"))?;
match Self::decode_app_local_state(&v, app_id) {
Some(local_state) => Ok(Some(ScannedAccount {
address: acct.address,
local_state,
})),
None => Ok(None),
}
}
fn scanned_account_from(account_json: &serde_json::Value, app_id: u64) -> ScannedAccount {
let address = account_json
.get("address")
.and_then(|x| x.as_str())
.unwrap_or_default()
.to_string();
let local_state = Self::decode_app_local_state(account_json, app_id).unwrap_or_default();
ScannedAccount {
address,
local_state,
}
}
fn account_scan_excludes() -> Option<Vec<String>> {
Some(vec![
"assets".to_string(),
"created-apps".to_string(),
"created-assets".to_string(),
])
}
pub fn set_asset_clawback_to_app(&self, app_id: u64, asset_id: u64) -> Result<()> {
if app_id == 0 {
bail!("app_id must be > 0");
}
if asset_id == 0 {
bail!("asset_id must be > 0");
}
let client = self.algod_client()?;
let caller = self.require_address()?;
let asset_info = self
.algod_call(|| client.asset(algonaut::core::AssetId(asset_id)))
.map_err(|e| anyhow!("failed to fetch asset information: {e}"))?;
let v_asset = serde_json::to_value(&asset_info)
.map_err(|e| anyhow!("failed to serialize asset info: {e}"))?;
let asset_manager_str = v_asset
.get("params")
.and_then(|p| p.get("manager").and_then(|x| x.as_str()))
.ok_or_else(|| anyhow!("asset {} info did not contain manager field", asset_id))?;
let asset_manager = Self::parse_address(asset_manager_str)?;
if caller != asset_manager {
bail!(
"Only the asset manager ({}) can set asset clawback, but called by {}",
asset_manager_str,
caller
);
}
let app_addr_str = self.contract_address(app_id)?;
let app_addr = Self::parse_address(&app_addr_str)?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let tx = algonaut::transaction::builder::UpdateAsset::new(
caller,
algonaut::core::AssetId(asset_id),
)
.manager(caller)
.reserve(app_addr)
.clawback(app_addr)
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build asset config transaction: {e}"))?;
let sk = self.private_key_bytes()?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign asset config transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)?;
algo_log!(
"Successfully set asset {} clawback and reserve to app address {}",
asset_id,
app_addr
);
Ok(())
}
pub fn change_asset_reserve_address(&self, asset_id: u64, reserve_address: &str) -> Result<()> {
if asset_id == 0 {
bail!("asset_id must be > 0");
}
let new_reserve = Self::parse_address(reserve_address)
.map_err(|e| anyhow!("invalid reserve address: {e}"))?;
let sk = self.private_key_bytes()?;
let signer_addr = self.require_address()?;
let client = self.algod_client()?;
let asset_info = self
.algod_call(|| client.asset(algonaut::core::AssetId(asset_id)))
.map_err(|e| anyhow!("failed to fetch asset information: {e}"))?;
let v = serde_json::to_value(&asset_info)
.map_err(|e| anyhow!("failed to serialize asset info: {e}"))?;
let creator_str = v
.get("params")
.and_then(|p| p.get("creator").and_then(|x| x.as_str()))
.or_else(|| v.get("creator").and_then(|x| x.as_str()))
.or_else(|| {
v.get("params").and_then(|p| {
p.get("creator-address")
.or_else(|| p.get("creator_address"))
.and_then(|x| x.as_str())
})
})
.ok_or_else(|| anyhow!("asset info did not contain creator field"))?;
let caller_str = {
use std::str::FromStr;
algonaut::core::Address::from_str(
self.address
.as_ref()
.ok_or_else(|| anyhow!("This operation needs an address"))?,
)
.map_err(|e| anyhow!("invalid caller address: {e}"))?
.to_string()
};
if creator_str != caller_str {
bail!("caller must be the asset creator to change the reserve address");
}
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let tx = algonaut::transaction::builder::UpdateAsset::new(
signer_addr,
algonaut::core::AssetId(asset_id),
)
.manager(signer_addr)
.reserve(new_reserve)
.clawback(new_reserve)
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build asset config transaction: {e}"))?;
algo_log!("[change_asset_reserve_address] tx: {:#?}", tx);
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign asset config transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)?;
let acct_info = self
.algod_call(|| client.account(&signer_addr))
.map_err(|e| anyhow!("failed to fetch creator account information: {e}"))?;
let va = serde_json::to_value(&acct_info)
.map_err(|e| anyhow!("failed to serialize creator account info: {e}"))?;
let mut creator_amount: u64 = 0;
if let Some(arr) = va.get("assets").and_then(|x| x.as_array()) {
for holding in arr {
let id = holding
.get("asset-id")
.and_then(|x| x.as_u64())
.or_else(|| holding.get("asset_id").and_then(|x| x.as_u64()))
.unwrap_or(0);
if id == asset_id {
creator_amount = holding.get("amount").and_then(|x| x.as_u64()).unwrap_or(0);
break;
}
}
}
if creator_amount == 0 {
algo_log!(
"[change_asset_reserve_address] creator has no balance of asset {}",
asset_id
);
return Ok(()); }
if !self.is_account_opted_in_to_asset(reserve_address, asset_id)? {
bail!("new reserve address is not opted-in to asset {}", asset_id);
}
self.send_asset(asset_id, creator_amount, reserve_address)
}
pub fn send_asset(&self, asset_id: u64, amount: u64, to_address: &str) -> Result<()> {
if asset_id == 0 {
bail!("asset_id must be > 0");
}
if amount == 0 {
bail!("amount must be > 0");
}
let sk = self.private_key_bytes()?;
let from = self.require_address()?;
let to = Self::parse_address(to_address)?;
let client = self.algod_client()?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let tx = algonaut::transaction::TransferAsset::new(
from,
algonaut::core::AssetId(asset_id),
amount,
to,
)
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build asset transfer transaction: {e}"))?;
algo_log!("[send_asset] tx: {:#?}", tx);
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign asset transfer transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)
}
pub fn opt_in_to_asset(&self, asset_id: u64) -> Result<()> {
if asset_id == 0 {
bail!("asset_id must be > 0");
}
let sk = self.private_key_bytes()?;
let addr = self.require_address()?;
let client = self.algod_client()?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let tx = algonaut::transaction::TransferAsset::new(
addr,
algonaut::core::AssetId(asset_id),
0,
addr,
)
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build asset opt-in transaction: {e}"))?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign asset opt-in transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn parse_creator_reserve_from_asset_info_value(
v: &serde_json::Value,
) -> Option<(String, String)> {
let params = v.get("params");
let creator = params
.and_then(|p| p.get("creator").and_then(|x| x.as_str()))
.or_else(|| v.get("creator").and_then(|x| x.as_str()))?;
let reserve = params.and_then(|p| {
p.get("reserve").and_then(|x| x.as_str()).or_else(|| {
p.get("reserve-address")
.or_else(|| p.get("reserve_address"))
.and_then(|x| x.as_str())
})
})?;
Some((creator.to_string(), reserve.to_string()))
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn parse_holding_amount_from_account_value(
v: &serde_json::Value,
asset_id: u64,
) -> u64 {
if let Some(arr) = v.get("assets").and_then(|x| x.as_array()) {
for holding in arr {
let id = holding
.get("asset-id")
.and_then(|x| x.as_u64())
.or_else(|| holding.get("asset_id").and_then(|x| x.as_u64()))
.unwrap_or(0);
if id == asset_id {
return holding.get("amount").and_then(|x| x.as_u64()).unwrap_or(0);
}
}
}
0
}
pub fn app_creator(&self, app_id: u64) -> Result<String> {
if app_id == 0 {
bail!("app_id must be > 0");
}
if let Some(creator) = self.cached_app_creator(app_id) {
return Ok(creator);
}
let creator = self.fetch_app_creator(app_id)?;
self.app_creators
.lock()
.map_err(|_| anyhow!("app creator cache lock poisoned"))?
.insert(app_id, creator.clone());
Ok(creator)
}
fn cached_app_creator(&self, app_id: u64) -> Option<String> {
self.app_creators.lock().ok()?.get(&app_id).cloned()
}
fn fetch_app_creator(&self, app_id: u64) -> Result<String> {
let client = self.algod_client()?;
let app_info = self
.algod_call(|| client.app(algonaut::core::AppId(app_id)))
.map_err(|e| anyhow!("failed to fetch application {app_id} info: {e}"))?;
let v = serde_json::to_value(&app_info)
.map_err(|e| anyhow!("failed to serialize application info: {e}"))?;
Self::parse_app_creator_from_app_info_value(&v)
.ok_or_else(|| anyhow!("application {app_id} info did not contain a creator field"))
}
pub fn asset_clawback(&self, asset_id: u64) -> Result<Option<String>> {
if asset_id == 0 {
bail!("asset_id must be > 0");
}
let client = self.algod_client()?;
let asset_info = self
.algod_call(|| client.asset(algonaut::core::AssetId(asset_id)))
.map_err(|e| anyhow!("failed to fetch asset {asset_id} info: {e}"))?;
let v = serde_json::to_value(&asset_info)
.map_err(|e| anyhow!("failed to serialize asset info: {e}"))?;
Ok(Self::parse_clawback_from_asset_info_value(&v))
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn parse_app_creator_from_app_info_value(v: &serde_json::Value) -> Option<String> {
v.get("params")
.and_then(|p| p.get("creator").and_then(|x| x.as_str()))
.or_else(|| v.get("creator").and_then(|x| x.as_str()))
.map(|s| s.to_string())
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn parse_clawback_from_asset_info_value(v: &serde_json::Value) -> Option<String> {
v.get("params")
.and_then(|p| {
p.get("clawback")
.or_else(|| p.get("clawback-address"))
.or_else(|| p.get("clawback_address"))
.and_then(|x| x.as_str())
})
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
}
pub fn recover_reserve_balance(&self, asset_id: u64) -> Result<()> {
if asset_id == 0 {
bail!("asset_id must be > 0");
}
let client = self.algod_client()?;
let asset_info = self
.algod_call(|| client.asset(algonaut::core::AssetId(asset_id)))
.map_err(|e| anyhow!("failed to fetch asset information: {e}"))?;
let v = serde_json::to_value(&asset_info)
.map_err(|e| anyhow!("failed to serialize asset info: {e}"))?;
let (creator_str, reserve_str) = match Self::parse_creator_reserve_from_asset_info_value(&v)
{
Some(t) => t,
None => {
return Err(anyhow!(
"asset information did not contain creator/reserve fields"
));
}
};
let caller_addr = self
.address
.as_ref()
.ok_or_else(|| anyhow!("This operation needs an address"))?
.clone();
if caller_addr != reserve_str {
bail!("caller must be the current reserve address to recover the reserve balance");
}
if !self.is_account_opted_in_to_asset(&creator_str, asset_id)? {
bail!("creator address is not opted-in to asset {asset_id}");
}
let reserve_addr = Self::parse_address(&reserve_str)?;
let acct_info = self
.algod_call(|| client.account(&reserve_addr))
.map_err(|e| anyhow!("failed to fetch reserve account information: {e}"))?;
let va = serde_json::to_value(&acct_info)
.map_err(|e| anyhow!("failed to serialize reserve account info: {e}"))?;
let amount = Self::parse_holding_amount_from_account_value(&va, asset_id);
if amount == 0 {
algo_log!("[recover_reserve_balance] reserve has zero balance for asset {asset_id}");
return Ok(());
}
self.send_asset(asset_id, amount, &creator_str)
}
pub fn compile_teal(&self, source: &str) -> Result<Vec<u8>> {
if source.is_empty() {
bail!("source must not be empty");
}
if let Some(rest) = source.strip_prefix("base64:") {
let bytes = general_purpose::STANDARD
.decode(rest)
.map_err(|e| anyhow!("invalid base64 program: {e}"))?;
return Ok(bytes);
}
let client = self.algod_client()?;
let resp =
self.algod_call(|| client.teal_compile(source.as_bytes(), algonaut::SourceMap::Skip))?;
Ok(resp.0)
}
pub fn arc4_selector(sig: &str) -> [u8; 4] {
use sha2::{Digest, Sha512_256};
let mut hasher = Sha512_256::new();
hasher.update(sig.as_bytes());
let digest: [u8; 32] = hasher.finalize().into();
[digest[0], digest[1], digest[2], digest[3]]
}
#[inline]
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn required_extra_pages(program_size: usize) -> u32 {
(program_size.saturating_sub(1) / 2048) as u32
}
pub(crate) const MAX_EXTRA_PROGRAM_PAGES: u32 = 3;
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn extra_pages_for(program_size: usize, reserve_extra_pages: u32) -> u32 {
Self::required_extra_pages(program_size)
.max(reserve_extra_pages)
.min(Self::MAX_EXTRA_PROGRAM_PAGES)
}
fn estimate_fee_for_programs(
params: &algonaut::model::algod::SuggestedParams,
sizes: &[usize],
) -> algonaut::core::MicroAlgos {
let total_size: usize = sizes.iter().copied().sum();
let per_byte = params.fee; let min_fee = params.min_fee; let sized = per_byte * (total_size as u64);
if sized > min_fee { sized } else { min_fee }
}
#[inline]
fn estimate_fee_for_signed_size(
params: &algonaut::model::algod::SuggestedParams,
est_size: u64,
) -> algonaut::core::MicroAlgos {
let per_byte = params.fee; let min_fee = params.min_fee; let sized = per_byte * est_size;
if sized > min_fee { sized } else { min_fee }
}
fn state_schema_from_arc56(
arc56_json: &str,
) -> Result<(
algonaut::transaction::transaction::StateSchema,
algonaut::transaction::transaction::StateSchema,
)> {
let spec: serde_json::Value = serde_json::from_str(arc56_json)
.map_err(|e| anyhow!("failed to parse ARC-56 app spec json: {e}"))?;
let schema = spec
.get("state")
.and_then(|s| s.get("schema"))
.ok_or_else(|| anyhow!("ARC-56 app spec missing state/schema"))?;
let read = |section: &str, field: &str| -> Result<u64> {
schema
.get(section)
.and_then(|v| v.get(field))
.and_then(|v| v.as_u64())
.ok_or_else(|| {
anyhow!("ARC-56 app spec missing state/schema/{}/{}", section, field)
})
};
let global = algonaut::transaction::transaction::StateSchema {
number_ints: read("global", "ints")?,
number_byteslices: read("global", "bytes")?,
};
let local = algonaut::transaction::transaction::StateSchema {
number_ints: read("local", "ints")?,
number_byteslices: read("local", "bytes")?,
};
Ok((global, local))
}
pub fn deploy_app(
&self,
approval_program: &[u8],
clear_state_program: &[u8],
asset_id: Option<u64>,
method: Option<&str>,
args: &[AppArg],
opt_in_method_name: &str,
arc56_json: &str,
) -> Result<Option<u64>> {
self.deploy_app_reserving(
approval_program,
clear_state_program,
asset_id,
method,
args,
opt_in_method_name,
arc56_json,
0,
)
}
#[allow(clippy::too_many_arguments)]
pub fn deploy_app_reserving(
&self,
approval_program: &[u8],
clear_state_program: &[u8],
asset_id: Option<u64>,
method: Option<&str>,
args: &[AppArg],
opt_in_method_name: &str,
arc56_json: &str,
reserve_extra_pages: u32,
) -> Result<Option<u64>> {
if approval_program.is_empty() {
bail!("approval_program must not be empty");
}
if clear_state_program.is_empty() {
bail!("clear_state_program must not be empty");
}
let sk = self.private_key_bytes()?;
let sender = self.require_address()?;
let approval = algonaut::core::CompiledTeal(approval_program.to_vec());
let clear = algonaut::core::CompiledTeal(clear_state_program.to_vec());
let (gs, ls) = Self::state_schema_from_arc56(arc56_json)?;
let client = self.algod_client()?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let est_prog_size: usize = approval.bytes_to_sign().len() + clear.bytes_to_sign().len();
let est_fee = Self::estimate_fee_for_programs(¶ms, &[est_prog_size]);
let est_fee_micro: u64 = est_fee.0;
let balance_algos = self
.account_balance()? .ok_or_else(|| anyhow!("Unable to determine account balance from algod; the account may not be funded or node unreachable"))?;
let balance_micro = (balance_algos * 1_000_000.0).floor() as u64;
if balance_micro < est_fee_micro {
let need_algos = est_fee_micro as f64 / 1_000_000.0;
return Err(anyhow!(
"Insufficient funds to create application: balance {:.6} ALGO, estimated required fee {:.6} ALGO. Please fund the creator account and retry.",
balance_algos,
need_algos
));
}
let per_byte = params.fee;
let min_fee = params.min_fee;
algo_log!(
"Preflight: min_fee={} µAlgos, fee_per_byte={} µAlgos/byte, est_prog_size={} bytes, estimated fee: {:.6} ALGO ({} µAlgos); current balance: {:.6} ALGO ({} µAlgos)",
min_fee.0,
per_byte.0,
est_prog_size,
est_fee_micro as f64 / 1_000_000.0,
est_fee_micro,
balance_algos,
balance_micro
);
let mut app_args: Vec<Vec<u8>> = Vec::new();
if let Some(sig) = method {
app_args.push(Self::arc4_selector(sig).to_vec());
}
app_args.extend(args.iter().map(|a| a.to_bytes()));
let mut builder =
algonaut::transaction::CreateApplication::new(sender, approval, clear, gs, ls);
let extra_pages = Self::extra_pages_for(est_prog_size, reserve_extra_pages);
if extra_pages > 0 {
builder = builder.extra_pages(extra_pages);
}
if let Some(aid) = asset_id {
builder = builder.foreign_assets(vec![algonaut::core::AssetId(aid)]);
}
if !app_args.is_empty() {
builder = builder.app_arguments(app_args);
}
let tx = builder
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build app create transaction: {e}"))?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign app create transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)?;
let tx_id_obj = algonaut::core::TransactionId::from(tx_id.as_str());
let info = self
.algod_call(|| client.pending_transaction(&tx_id_obj))
.map_err(|e| anyhow!("failed to fetch pending transaction info for app id: {e}"))?;
{
let v = serde_json::to_value(&info)
.map_err(|e| anyhow!("failed to serialize pending tx info: {e}"))?;
let app_id = v
.get("application-index")
.and_then(|x| x.as_u64())
.or_else(|| v.get("application_index").and_then(|x| x.as_u64()))
.unwrap_or(0);
if app_id != 0 {
if let Ok(app_addr) = self.contract_address(app_id) {
self.send_algo(&app_addr, 3.21)?;
}
if let Some(aid) = asset_id {
let _ = self.opt_in_app_to_asset(app_id, aid, opt_in_method_name)?;
self.set_asset_clawback_to_app(app_id, aid)?;
}
}
Ok((app_id != 0).then_some(app_id))
}
}
pub fn update_app(
&self,
app_id: u64,
approval_program: &[u8],
clear_state_program: &[u8],
asset_id: Option<u64>,
) -> Result<Option<u64>> {
if app_id == 0 {
bail!("app_id must be > 0");
}
if approval_program.is_empty() {
bail!("approval_program must not be empty");
}
if clear_state_program.is_empty() {
bail!("clear_state_program must not be empty");
}
let sk = self.private_key_bytes()?;
let sender = self.require_address()?;
let approval = algonaut::core::CompiledTeal(approval_program.to_vec());
let clear = algonaut::core::CompiledTeal(clear_state_program.to_vec());
let client = self.algod_client()?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let est_prog_size: usize = approval.bytes_to_sign().len() + clear.bytes_to_sign().len();
let est_fee = Self::estimate_fee_for_programs(¶ms, &[est_prog_size]);
let per_byte = params.fee;
let min_fee = params.min_fee;
algo_log!(
"Update preflight: min_fee={} µAlgos, fee_per_byte={} µAlgos/byte, est_prog_size={} bytes, estimated fee: {:.6} ALGO ({} µAlgos)",
min_fee.0,
per_byte.0,
est_prog_size,
est_fee.0 as f64 / 1_000_000.0,
est_fee.0
);
let mut builder = algonaut::transaction::builder::UpdateApplication::new(
sender,
algonaut::core::AppId(app_id),
approval,
clear,
);
if let Some(aid) = asset_id {
builder = builder.foreign_assets(vec![algonaut::core::AssetId(aid)]);
}
let tx = builder
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build app update transaction: {e}"))?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign app update transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)?;
Ok(Some(app_id))
}
pub fn call_app(
&self,
app_id: u64,
asset_id: Option<u64>,
method: Option<&str>,
args: &[AppArg],
) -> Result<(String, Vec<Vec<u8>>)> {
if app_id == 0 {
bail!("app_id must be > 0");
}
let tx = self.build_call_app_tx(app_id, asset_id, method, args)?;
algo_log!(
"[call_app] method={:?} app_id={} asset_id={:?} args_len={}",
method,
app_id,
asset_id,
args.len()
);
algo_log!("[call_app] tx={:?}", tx);
self.sign_submit_and_fetch_logs(tx)
}
pub fn call_app_raw_args(
&self,
app_id: u64,
asset_id: Option<u64>,
method: Option<&str>,
args: &[AppArg],
) -> Result<(String, Vec<Vec<u8>>)> {
self.call_app(app_id, asset_id, method, args)
}
pub fn call_app_arc4_args(
&self,
app_id: u64,
asset_id: Option<u64>,
method: Option<&str>,
args: &[AppArg],
) -> Result<(String, Vec<Vec<u8>>)> {
let framed = arc4_frame_args(method, args)?;
self.call_app(app_id, asset_id, method, &framed)
}
pub fn call_app_with_accounts(
&self,
app_id: u64,
asset_id: Option<u64>,
method: Option<&str>,
args: &[AppArg],
extra_accounts: &[&str],
) -> Result<(String, Vec<Vec<u8>>)> {
if app_id == 0 {
bail!("app_id must be > 0");
}
let parsed: Vec<algonaut::core::Address> = extra_accounts
.iter()
.map(|a| Self::parse_address(a))
.collect::<Result<_>>()?;
let tx = self.build_call_app_tx_inner(app_id, asset_id, &[], &parsed, method, args)?;
algo_log!(
"[call_app_with_accounts] method={:?} app_id={} extra_accounts={}",
method,
app_id,
extra_accounts.len()
);
self.sign_submit_and_fetch_logs(tx)
}
fn sign_submit_and_fetch_logs(
&self,
tx: algonaut::transaction::transaction::Transaction,
) -> Result<(String, Vec<Vec<u8>>)> {
let sk = self.private_key_bytes()?;
let client = self.algod_client()?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign app call transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)?;
let tx_id_obj = algonaut::core::TransactionId::from(tx_id.as_str());
let p = self
.algod_call(|| client.pending_transaction(&tx_id_obj))
.map_err(|e| anyhow!("failed to fetch pending transaction info: {e}"))?;
let v = serde_json::to_value(&p)
.map_err(|e| anyhow!("failed to serialize pending tx info: {e}"))?;
let logs_arr = v
.get("logs")
.and_then(|x| x.as_array())
.cloned()
.unwrap_or_default();
let mut logs: Vec<Vec<u8>> = Vec::new();
for l in logs_arr {
if let Some(s) = l.as_str()
&& let Ok(bytes) = general_purpose::STANDARD.decode(s)
{
logs.push(bytes);
}
}
Ok((tx_id, logs))
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
pub(crate) fn build_call_app_tx(
&self,
app_id: u64,
asset_id: Option<u64>,
method: Option<&str>,
args: &[AppArg],
) -> Result<algonaut::transaction::transaction::Transaction> {
self.build_call_app_tx_inner(app_id, asset_id, &[], &[], method, args)
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
#[cfg_attr(not(feature = "test-support"), allow(dead_code))]
pub(crate) fn build_call_app_tx_with_foreign_apps(
&self,
app_id: u64,
asset_id: Option<u64>,
foreign_app_ids: &[u64],
method: Option<&str>,
args: &[AppArg],
) -> Result<algonaut::transaction::transaction::Transaction> {
self.build_call_app_tx_inner(app_id, asset_id, foreign_app_ids, &[], method, args)
}
pub fn call_app_with_foreign_app(
&self,
app_id: u64,
foreign_app_id: u64,
asset_id: Option<u64>,
method: Option<&str>,
args: &[AppArg],
) -> Result<(String, Vec<Vec<u8>>)> {
if app_id == 0 {
bail!("app_id must be > 0");
}
if foreign_app_id == 0 {
bail!("foreign_app_id must be > 0");
}
let tx =
self.build_call_app_tx_inner(app_id, asset_id, &[foreign_app_id], &[], method, args)?;
algo_log!(
"[call_app_with_foreign_app] method={:?} app_id={} foreign_app_id={}",
method,
app_id,
foreign_app_id
);
self.sign_submit_and_fetch_logs(tx)
}
fn build_call_app_tx_inner(
&self,
app_id: u64,
asset_id: Option<u64>,
foreign_app_ids: &[u64],
extra_accounts: &[algonaut::core::Address],
method: Option<&str>,
args: &[AppArg],
) -> Result<algonaut::transaction::transaction::Transaction> {
if app_id == 0 {
bail!("app_id must be > 0");
}
let creator = Self::parse_address(&self.app_creator(app_id)?)?;
let sender = self.require_address()?;
let client = self.algod_client()?;
let mut app_args: Vec<Vec<u8>> = Vec::new();
if let Some(sig) = method {
app_args.push(Self::arc4_selector(sig).to_vec());
}
app_args.extend(args.iter().map(|a| a.to_bytes()));
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let mut accounts: Vec<algonaut::core::Address> =
Vec::with_capacity(extra_accounts.len() + 1);
accounts.extend_from_slice(extra_accounts);
accounts.push(creator);
let fapps: Vec<algonaut::core::AppId> = foreign_app_ids
.iter()
.map(|&id| algonaut::core::AppId(id))
.collect();
let make_builder = || {
let mut b = algonaut::transaction::builder::CallApplication::new(
sender,
algonaut::core::AppId(app_id),
)
.accounts(accounts.clone())
.app_arguments(app_args.clone());
if let Some(aid) = asset_id {
b = b.foreign_assets(vec![algonaut::core::AssetId(aid)]);
}
if !fapps.is_empty() {
b = b.foreign_apps(fapps.clone());
}
b
};
let tx_zero_fee = make_builder()
.fee(algonaut::core::MicroAlgos(0))
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build app call transaction for fee estimation: {e}"))?;
let est_size = tx_zero_fee
.estimate_basic_sig_size()
.map_err(|e| anyhow!("failed to estimate signed tx size: {e}"))?;
let est_fee = Self::estimate_fee_for_signed_size(¶ms, est_size);
let tx = make_builder()
.fee(est_fee)
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build app call transaction: {e}"))?;
Ok(tx)
}
pub fn opt_in_app(&self, app_id: u64) -> Result<()> {
if app_id == 0 {
bail!("app_id must be > 0");
}
let addr_str = self
.address
.as_ref()
.ok_or_else(|| anyhow!("This operation needs an address"))?;
if let Some(_entries) = self.local_state_for_account(app_id, addr_str)? {
return Ok(());
}
let sender = self.require_address()?;
let sk = self.private_key_bytes()?;
let client = self.algod_client()?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let tx = algonaut::transaction::builder::OptInApplication::new(
sender,
algonaut::core::AppId(app_id),
)
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build app opt-in transaction: {e}"))?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign app opt-in transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)
}
pub fn clear_state_app(&self, app_id: u64) -> Result<()> {
if app_id == 0 {
bail!("app_id must be > 0");
}
let sender = self.require_address()?;
let sk = self.private_key_bytes()?;
let client = self.algod_client()?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let tx = algonaut::transaction::builder::ClearApplication::new(
sender,
algonaut::core::AppId(app_id),
)
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build app clear transaction: {e}"))?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign app clear transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)
}
pub fn close_out_app(&self, app_id: u64) -> Result<()> {
if app_id == 0 {
bail!("app_id must be > 0");
}
let sender = self.require_address()?;
let sk = self.private_key_bytes()?;
let client = self.algod_client()?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let tx = algonaut::transaction::builder::CloseApplication::new(
sender,
algonaut::core::AppId(app_id),
)
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build app close-out transaction: {e}"))?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign app close-out transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)
}
pub fn delete_app(&self, app_id: u64) -> Result<()> {
if app_id == 0 {
bail!("app_id must be > 0");
}
let sender = self.require_address()?;
let sk = self.private_key_bytes()?;
let client = self.algod_client()?;
let params = self
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let tx = algonaut::transaction::builder::DeleteApplication::new(
sender,
algonaut::core::AppId(app_id),
)
.note(Self::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build app delete transaction: {e}"))?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let signed_tx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign app delete transaction: {e}"))?;
let signed = signed_tx
.to_msg_pack()
.map_err(|e| anyhow!("failed to encode signed transaction: {e}"))?;
let tx_id = self
.algod_call(|| client.send_raw(&signed))
.map_err(|e| anyhow!("send_raw failed: {e}"))?
.tx_id;
self.wait_for_confirmation(&tx_id, 10)
}
pub fn opt_in_app_to_asset(
&self,
app_id: u64,
asset_id: u64,
opt_in_method_name: &str,
) -> Result<String> {
tracing::info!("opt_in_app_to_asset: app_id={}", app_id);
if app_id == 0 {
bail!("app_id must be > 0");
}
if asset_id == 0 {
bail!("asset_id must be > 0");
}
let app_addr_str = self.contract_address(app_id)?;
if self.is_account_opted_in_to_asset(&app_addr_str, asset_id)? {
return Ok(String::new());
}
let (tx_id, _logs) = self.call_app(
app_id,
Some(asset_id),
Some(opt_in_method_name),
&[AppArg::Uint(asset_id)],
)?;
Ok(tx_id)
}
pub fn wait_for_confirmation(&self, tx_id: &str, timeout_rounds: u64) -> Result<()> {
if timeout_rounds == 0 {
bail!("timeout_rounds must be > 0");
}
let client = self.algod_client()?;
let status = self
.algod_call(|| client.status())
.map_err(|e| anyhow!("failed to get node status: {e}"))?;
let start_round = status.last_round.0 + 1;
let end_round = start_round + timeout_rounds;
let mut current_round = start_round;
while current_round < end_round {
let tx_id_obj = algonaut::core::TransactionId::from(tx_id);
match self.algod_call(|| client.pending_transaction(&tx_id_obj)) {
Ok(p) => {
if let Some(cr) = p.confirmed_round
&& cr > 0
{
return Ok(());
}
if !p.pool_error.is_empty() {
bail!("Transaction rejected with pool error: {}", p.pool_error);
}
}
Err(e) => {
if AlgoError::is_host_unreachable(&anyhow!(e.to_string())) {
return Err(
AlgoError::unreachable("pending_transaction", &e.to_string()).into(),
);
}
}
}
self.algod_call(|| client.status_after_block(algonaut::core::Round(current_round)))
.map_err(|e| anyhow!("status_after_block failed: {e}"))?;
current_round += 1;
}
Err(anyhow!(
"Transaction not confirmed after {} rounds",
timeout_rounds
))
}
pub fn transaction_group(&self) -> TransactionGroupBuilder<'_> {
TransactionGroupBuilder {
ops: self,
legs: Vec::new(),
error: None,
}
}
}
#[derive(Debug, Clone)]
enum GroupLeg {
Payment { to: String, micro_algos: u64 },
AssetTransfer {
asset_id: u64,
amount: u64,
to: String,
},
AppCall {
app_id: u64,
method: Option<String>,
args: Vec<AppArg>,
foreign_asset: Option<u64>,
foreign_app: Option<u64>,
},
}
#[derive(Debug)]
pub struct TransactionGroupBuilder<'a> {
ops: &'a AlgoOps,
legs: Vec<GroupLeg>,
error: Option<String>,
}
impl<'a> TransactionGroupBuilder<'a> {
fn set_error(&mut self, msg: impl Into<String>) {
if self.error.is_none() {
self.error = Some(msg.into());
}
}
pub fn payment(mut self, to_address: &str, micro_algos: u64) -> Self {
self.legs.push(GroupLeg::Payment {
to: to_address.to_string(),
micro_algos,
});
self
}
pub fn asset_transfer(mut self, asset_id: u64, amount: u64, to_address: &str) -> Self {
self.legs.push(GroupLeg::AssetTransfer {
asset_id,
amount,
to: to_address.to_string(),
});
self
}
pub fn call_app(mut self, app_id: u64, method: Option<&str>, args: &[AppArg]) -> Self {
if app_id == 0 {
self.set_error("call_app() requires app_id > 0");
}
self.legs.push(GroupLeg::AppCall {
app_id,
method: method.map(|s| s.to_string()),
args: args.to_vec(),
foreign_asset: None,
foreign_app: None,
});
self
}
pub fn call_app_raw_args(self, app_id: u64, method: Option<&str>, args: &[AppArg]) -> Self {
self.call_app(app_id, method, args)
}
pub fn call_app_arc4_args(
mut self,
app_id: u64,
method: Option<&str>,
args: &[AppArg],
) -> Self {
match arc4_frame_args(method, args) {
Ok(framed_args) => self.call_app(app_id, method, &framed_args),
Err(error) => {
self.set_error(format!("call_app_arc4_args(): {error}"));
self.call_app(app_id, method, args)
}
}
}
pub fn foreign_asset(mut self, asset_id: u64) -> Self {
match self.legs.last_mut() {
Some(GroupLeg::AppCall { foreign_asset, .. }) => *foreign_asset = Some(asset_id),
_ => self.set_error("foreign_asset() must follow a call_app() leg"),
}
self
}
pub fn foreign_app(mut self, foreign_app_id: u64) -> Self {
match self.legs.last_mut() {
Some(GroupLeg::AppCall { foreign_app, .. }) => *foreign_app = Some(foreign_app_id),
_ => self.set_error("foreign_app() must follow a call_app() leg"),
}
self
}
pub fn sign_and_send(self) -> Result<String> {
if let Some(err) = self.error {
bail!("{err}");
}
if self.legs.is_empty() {
bail!("transaction group must contain at least one transaction");
}
let ops = self.ops;
let sk = ops.private_key_bytes()?;
let seed: [u8; 32] = sk
.as_slice()
.try_into()
.map_err(|_| anyhow!("Secret key must be 32 bytes"))?;
let sender = ops.require_address()?;
let client = ops.algod_client()?;
let params = ops
.algod_call(|| client.suggested_params())
.map_err(|e| anyhow!("failed to fetch suggested params: {e}"))?;
let mut txns: Vec<algonaut::transaction::transaction::Transaction> =
Vec::with_capacity(self.legs.len());
for leg in &self.legs {
let tx = match leg {
GroupLeg::Payment { to, micro_algos } => {
let to_addr = AlgoOps::parse_address(to)?;
algonaut::transaction::Pay::new(
sender,
to_addr,
algonaut::core::MicroAlgos(*micro_algos),
)
.note(AlgoOps::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build payment transaction: {e}"))?
}
GroupLeg::AssetTransfer {
asset_id,
amount,
to,
} => {
let to_addr = AlgoOps::parse_address(to)?;
algonaut::transaction::TransferAsset::new(
sender,
algonaut::core::AssetId(*asset_id),
*amount,
to_addr,
)
.note(AlgoOps::unique_note())
.build(¶ms)
.map_err(|e| anyhow!("failed to build asset transfer transaction: {e}"))?
}
GroupLeg::AppCall {
app_id,
method,
args,
foreign_asset,
foreign_app,
} => {
let fapps: Vec<u64> = foreign_app.iter().copied().collect();
ops.build_call_app_tx_inner(
*app_id,
*foreign_asset,
&fapps,
&[],
method.as_deref(),
args,
)?
}
};
txns.push(tx);
}
let group = algonaut::transaction::group::TransactionGroup::try_from(txns)
.map_err(|e| anyhow!("failed to assign group id: {e}"))?;
let account = algonaut::transaction::account::Account::from_seed(seed);
let mut signed: Vec<algonaut::transaction::SignedTransaction> = Vec::new();
for tx in group.into_transactions() {
let stx = account
.sign(tx)
.map_err(|e| anyhow!("failed to sign grouped transaction: {e}"))?;
signed.push(stx);
}
let tx_id = ops
.algod_call(|| client.send_transactions(&signed))
.map_err(|e| anyhow!("failed to broadcast transaction group: {e}"))?
.tx_id;
ops.wait_for_confirmation(&tx_id, 10)?;
Ok(tx_id)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AppArg {
Bytes(Vec<u8>),
Utf8(String),
Uint(u64),
}
impl AppArg {
pub fn to_bytes(&self) -> Vec<u8> {
match self {
AppArg::Bytes(b) => b.clone(),
AppArg::Utf8(s) => s.as_bytes().to_vec(),
AppArg::Uint(v) => v.to_be_bytes().to_vec(),
}
}
}
fn abi_arg_types(sig: &str) -> Option<Vec<String>> {
let open = sig.find('(')?;
let mut depth = 0i32;
let mut start = 0usize;
let mut inner: Option<&str> = None;
for (i, c) in sig.char_indices().skip_while(|(i, _)| *i < open) {
match c {
'(' => {
depth += 1;
if depth == 1 {
start = i + 1;
}
}
')' => {
depth -= 1;
if depth == 0 {
inner = Some(&sig[start..i]);
break;
}
}
_ => {}
}
}
let inner = inner?;
if inner.trim().is_empty() {
return Some(Vec::new());
}
let mut out = Vec::new();
let mut d = 0i32;
let mut seg = 0usize;
for (i, c) in inner.char_indices() {
match c {
'(' | '[' => d += 1,
')' | ']' => d -= 1,
',' if d == 0 => {
out.push(inner[seg..i].trim().to_string());
seg = i + 1;
}
_ => {}
}
}
out.push(inner[seg..].trim().to_string());
Some(out)
}
#[cfg_attr(feature = "test-support", visibility::make(pub))]
fn arc4_frame_args(method: Option<&str>, args: &[AppArg]) -> Result<Vec<AppArg>> {
let types = method.and_then(abi_arg_types);
args.iter()
.enumerate()
.map(|(i, arg)| {
let ty = types.as_ref().and_then(|t| t.get(i)).map(String::as_str);
match ty {
Some("byte[]") | Some("string") => {
let raw = arg.to_bytes();
let len = u16::try_from(raw.len()).map_err(|_| {
anyhow!(
"ARC-4 byte[]/string argument {i} is {} bytes, over the u16 length limit",
raw.len()
)
})?;
let mut framed = Vec::with_capacity(2 + raw.len());
framed.extend_from_slice(&len.to_be_bytes());
framed.extend_from_slice(&raw);
Ok(AppArg::Bytes(framed))
}
_ => Ok(arg.clone()),
}
})
.collect()
}
pub fn address_to_byte_key(address: &str) -> Result<[u8; 32]> {
let decoded = BASE32_NOPAD
.decode(address.as_bytes())
.map_err(|e| anyhow!("Invalid base32 address: {e}"))?;
if decoded.len() < 32 {
bail!("Decoded address is shorter than 32 bytes");
}
let mut pk = [0u8; 32];
pk.copy_from_slice(&decoded[..32]);
Ok(pk)
}
pub fn byte_key_to_address(byte_public_key: &[u8; 32]) -> Result<String> {
use sha2::{Digest, Sha512_256};
let mut hasher = Sha512_256::new();
hasher.update(byte_public_key);
let hash = hasher.finalize();
let checksum = &hash[hash.len() - 4..];
let mut addr_bytes = [0u8; 36];
addr_bytes[..32].copy_from_slice(byte_public_key);
addr_bytes[32..].copy_from_slice(checksum);
let addr = BASE32_NOPAD.encode(&addr_bytes);
Ok(addr)
}