koios_sdk/api/transaction.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
use crate::error::{Error, Result};
use crate::models::UtxoInfo;
use crate::{
models::{
requests::{TransactionIdsRequest, TransactionInfoRequest, UtxoRefsWithExtendedRequest},
transaction::{
TransactionCbor, TransactionInfo, TransactionMetadata, TransactionStatus, TxMetaLabels,
},
},
Client,
};
use reqwest::StatusCode;
impl Client {
/// Get UTxO set for requested UTxO references
///
/// # Arguments
///
/// * `utxo_refs` - List of UTxO references to query
/// * `extended` - Optional flag to include extended information
///
/// # Examples
///
/// ```no_run
/// use koios_sdk::Client;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new()?;
/// let utxo_refs = vec!["1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef#1".to_string()];
/// let utxo_info = client.get_utxo_info(&utxo_refs, Some(true)).await?;
/// println!("UTxO info: {:?}", utxo_info);
/// Ok(())
/// }
/// ```
pub async fn get_utxo_info(
&self,
utxo_refs: &[String],
extended: Option<bool>,
) -> Result<Vec<UtxoInfo>> {
let request = UtxoRefsWithExtendedRequest {
utxo_refs: utxo_refs.to_vec(),
extended,
};
self.post("/utxo_info", &request).await
}
/// Get raw transaction(s) in CBOR format
///
/// # Arguments
///
/// * `tx_hashes` - List of transaction hashes to query
///
/// # Examples
///
/// ```no_run
/// use koios_sdk::Client;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new()?;
/// let tx_hashes = vec!["1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef".to_string()];
/// let tx_cbor = client.get_transaction_cbor(&tx_hashes).await?;
/// println!("Transaction CBOR: {:?}", tx_cbor);
/// Ok(())
/// }
/// ```
pub async fn get_transaction_cbor(&self, tx_hashes: &[String]) -> Result<Vec<TransactionCbor>> {
let request = TransactionIdsRequest {
tx_hashes: tx_hashes.to_vec(),
};
self.post("/tx_cbor", &request).await
}
/// Get detailed information about transaction(s)
///
/// # Arguments
///
/// * `tx_hashes` - List of transaction hashes to query
/// * `options` - Optional parameters for customizing the response
///
/// # Examples
///
/// ```no_run
/// use koios_sdk::Client;
/// use koios_sdk::models::requests::TransactionInfoRequest;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new()?;
/// let tx_hashes = vec!["1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef".to_string()];
/// let options = TransactionInfoRequest {
/// tx_hashes,
/// inputs: Some(true),
/// ..Default::default()
/// };
/// let tx_info = client.get_transaction_info(&options).await?;
/// println!("Transaction info: {:?}", tx_info);
/// Ok(())
/// }
/// ```
pub async fn get_transaction_info(
&self,
options: &TransactionInfoRequest,
) -> Result<Vec<TransactionInfo>> {
self.post("/tx_info", options).await
}
/// Get metadata information (if any) for given transaction(s)
///
/// # Arguments
///
/// * `tx_hashes` - List of transaction hashes to query
///
/// # Examples
///
/// ```no_run
/// use koios_sdk::Client;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new()?;
/// let tx_hashes = vec!["1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef".to_string()];
/// let metadata = client.get_transaction_metadata(&tx_hashes).await?;
/// println!("Transaction metadata: {:?}", metadata);
/// Ok(())
/// }
/// ```
pub async fn get_transaction_metadata(
&self,
tx_hashes: &[String],
) -> Result<Vec<TransactionMetadata>> {
let request = TransactionIdsRequest {
tx_hashes: tx_hashes.to_vec(),
};
self.post("/tx_metadata", &request).await
}
/// Get a list of all transaction metalabels
///
/// # Examples
///
/// ```no_run
/// use koios_sdk::Client;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new()?;
/// let metalabels = client.get_transaction_metalabels().await?;
/// println!("Transaction metalabels: {:?}", metalabels);
/// Ok(())
/// }
/// ```
pub async fn get_transaction_metalabels(&self) -> Result<Vec<TxMetaLabels>> {
self.get("/tx_metalabels").await
}
/// Submit an already serialized transaction to the network
///
/// # Arguments
///
/// * `cbor_data` - Raw CBOR data of the serialized transaction
///
/// # Returns
///
/// The transaction ID as a hex string on success
///
/// # Errors
///
/// Returns an error if:
/// - The request fails
/// - The server returns a non-202 status code
/// - The response is not a valid transaction ID
pub async fn submit_transaction(&self, cbor_data: &[u8]) -> Result<String> {
// Build URL from base URL
let url = format!("{}/submittx", self.base_url());
// Create request with CBOR data
let mut request = reqwest::Client::new()
.post(&url)
.header("Content-Type", "application/cbor")
.body(cbor_data.to_vec());
// Add authorization if token is present
if let Some(token) = self.auth_token() {
request = request.header("Authorization", format!("Bearer {}", token));
}
// Send request and handle response
let response = request.send().await?;
match response.status() {
StatusCode::ACCEPTED => {
let tx_id: String = response.text().await?;
// Validate transaction ID format (64 character hex string)
if tx_id.len() == 64 && tx_id.chars().all(|c| c.is_ascii_hexdigit()) {
Ok(tx_id)
} else {
Err(Error::Api {
status: 500,
message: "Invalid transaction ID format in response".to_string(),
})
}
}
StatusCode::BAD_REQUEST => {
let message: String = response
.text()
.await
.unwrap_or_else(|_| "Transaction submission failed".to_string());
Err(Error::Api {
status: 400,
message,
})
}
status => {
let message: String = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(Error::Api {
status: status.as_u16(),
message,
})
}
}
}
/// Get the number of block confirmations for a given transaction hash list
///
/// # Arguments
///
/// * `tx_hashes` - List of transaction hashes to query
///
/// # Examples
///
/// ```no_run
/// use koios_sdk::Client;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new()?;
/// let tx_hashes = vec!["1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef".to_string()];
/// let status = client.get_transaction_status(&tx_hashes).await?;
/// println!("Transaction status: {:?}", status);
/// Ok(())
/// }
/// ```
pub async fn get_transaction_status(
&self,
tx_hashes: &[String],
) -> Result<Vec<TransactionStatus>> {
let request = TransactionIdsRequest {
tx_hashes: tx_hashes.to_vec(),
};
self.post("/tx_status", &request).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
#[tokio::test]
async fn test_get_transaction_metadata() {
let mock_server = MockServer::start().await;
let client = Client::builder()
.base_url(mock_server.uri())
.build()
.unwrap();
let tx_hash = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
let mock_response = json!([{
"tx_hash": tx_hash,
"metadata": {
"1": {
"key": "value"
}
}
}]);
Mock::given(method("POST"))
.and(path("/tx_metadata"))
.respond_with(ResponseTemplate::new(200).set_body_json(&mock_response))
.mount(&mock_server)
.await;
let response = client
.get_transaction_metadata(&[tx_hash.to_string()])
.await
.unwrap();
assert_eq!(response.len(), 1);
assert_eq!(response[0].tx_hash, tx_hash);
}
// Add more tests for other endpoints...
}