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 uuid::Uuid;
#[allow(unused_imports)]
use algonaut as _algonaut;
#[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>,
}
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,
}
}
}
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)]
pub struct AlgoOps {
pub passphrase: Option<String>,
pub address: Option<String>,
pub config: AlgoChainConfig,
}
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 fn new_indexer(config: Option<AlgoChainConfig>) -> Self {
Self::new(None, None, config)
}
pub fn new(
passphrase: Option<String>,
address: Option<String>,
config: Option<AlgoChainConfig>,
) -> Self {
let config = config.unwrap_or_default();
let mut ops = Self {
passphrase,
address,
config,
};
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 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}"))
}
pub const RETRYABLE_STATUS_CODES: &'static [u16] = &[408, 425, 429, 502, 503, 504];
pub fn is_retryable(e: &algonaut::Error) -> bool {
if let algonaut::Error::Request(req) = e
&& let algonaut::error::RequestErrorDetails::Http { status, .. } = &req.details
{
return Self::RETRYABLE_STATUS_CODES.contains(status);
}
false
}
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,
{
const MAX_RETRIES: u32 = 3;
const RETRY_BASE_MS: u64 = 1_000;
let mut attempt = 0u32;
loop {
let result = self
.rt_block_on(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(e) => {
let delay = std::time::Duration::from_millis(RETRY_BASE_MS * (1u64 << attempt));
tracing::warn!(
"algod transient error (attempt {}/{}), retrying in {:?}: {}",
attempt + 1,
MAX_RETRIES,
delay,
e
);
std::thread::sleep(delay);
attempt += 1;
}
Err(e) => {
if attempt >= MAX_RETRIES && Self::is_retryable(&e) {
return Err(AlgoError::transient("algod call", &e.to_string()).into());
}
return Err(anyhow!("{e}"));
}
}
}
}
fn rt_block_on<T: Send>(&self, fut: impl Future<Output = T> + Send) -> Result<T> {
if tokio::runtime::Handle::try_current().is_ok() {
return std::thread::scope(|s| {
let handle = s.spawn(|| {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("failed to build temporary tokio runtime");
rt.block_on(fut)
});
handle
.join()
.map_err(|_| anyhow!("rt_block_on thread panicked"))
});
}
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| anyhow!("failed to build tokio runtime: {e}"))?;
Ok(rt.block_on(fut))
}
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_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}"))?;
let als = match Self::json_get(&v, "apps_local_state", "apps-local-state")
.and_then(|x| x.as_array())
{
Some(a) => a,
None => return Ok(None),
};
for st in als {
let id = st.get("id").and_then(|x| x.as_u64());
if id == 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();
let out = Self::decode_state_entries(&keyvals_vec);
return Ok(Some(out));
}
}
Ok(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 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 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)
}
pub 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()))
}
pub 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 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]
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>> {
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);
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);
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))
}
pub 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)
}
pub 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
);
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))
}
fn build_call_app_tx_inner(
&self,
app_id: u64,
asset_id: Option<u64>,
foreign_app_ids: &[u64],
method: Option<&str>,
args: &[AppArg],
) -> Result<algonaut::transaction::transaction::Transaction> {
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!("failed to fetch application information: {e}"))?;
let app_info_v = serde_json::to_value(&app_info)
.map_err(|e| anyhow!("failed to serialize application info: {e}"))?;
let creator_str = app_info_v
.get("params")
.and_then(|p| p.get("creator").and_then(|x| x.as_str()))
.or_else(|| app_info_v.get("creator").and_then(|x| x.as_str()))
.ok_or_else(|| anyhow!("application info did not contain creator field"))?;
let creator = Self::parse_address(creator_str)?;
let sender = self.require_address()?;
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![creator];
if let Some(sig) = method
&& (sig == "set_allow_static(address,uint64)void"
|| sig == "set_allow_relay(address,uint64)void")
&& let Some(first) = args.first()
&& let AppArg::Bytes(b) = first
&& b.len() == 32
{
let mut pk = [0u8; 32];
pk.copy_from_slice(&b[..32]);
if let Ok(addr_str) = byte_key_to_address(&pk)
&& let Ok(target) = Self::parse_address(&addr_str)
{
accounts.insert(0, target);
}
}
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
))
}
}
#[derive(Debug, Clone)]
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(),
}
}
}
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)
}