DeltaDeFi Rust SDK

The official Rust SDK for DeltaDeFi protocol, providing a comprehensive and ergonomic interface for decentralized finance operations. This SDK enables developers to interact with DeltaDeFi's trading platform, manage accounts, execute orders, and handle wallet operations seamlessly.
🚀 Features
- 🔐 Wallet Management: Secure wallet integration with master and operation key support
- 📊 Order Management: Complete order lifecycle - place, cancel, and track orders
- 💰 Account Operations: Deposits, withdrawals, transfers, and balance management
- 📈 Market Data: Real-time market prices and historical aggregated price data
- 🌐 Multi-Environment: Support for Mainnet, Staging, Dev, and custom environments
- ⚡ Async/Await: Fully asynchronous API built on tokio
- 🛡️ Type Safety: Comprehensive type definitions with serde serialization
- 🔒 Security: Built-in transaction signing and encryption support
📦 Installation
Add this to your Cargo.toml:
[dependencies]
deltadefi = "0.1.0"
tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }
dotenv = "0.15"
🏁 Quick Start
use deltadefi::{DeltaDeFi, Stage, OrderSide, OrderType};
use dotenv::dotenv;
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
dotenv().ok();
let api_key = env::var("DELTADEFI_API_KEY")?;
let mut client = DeltaDeFi::new(api_key, Stage::Staging, None)?;
let password = env::var("ENCRYPTION_PASSCODE")?;
client.load_operation_key(&password).await?;
let order_result = client.post_order(
"ADAUSDM",
OrderSide::Buy,
OrderType::Limit,
100.0, Some(1.25), None, None, ).await?;
println!("Order placed: {}", order_result.order_id);
Ok(())
}
🔧 Configuration
Environment Setup
Create a .env file with your credentials:
DELTADEFI_API_KEY=your_api_key_here
ENCRYPTION_PASSCODE=your_encryption_password
Network Environments
use deltadefi::{DeltaDeFi, Stage};
let mainnet_client = DeltaDeFi::new(api_key, Stage::Mainnet, None)?;
let staging_client = DeltaDeFi::new(api_key, Stage::Staging, None)?;
📚 API Reference
DeltaDeFi Client
The main client provides access to all SDK functionality:
pub struct DeltaDeFi {
pub accounts: Accounts, pub market: Market, pub order: Order, }
Core Methods
impl DeltaDeFi {
pub fn new(api_key: String, network: Stage, master_key: Option<WalletType>) -> Result<Self, WError>
pub async fn load_operation_key(&mut self, password: &str) -> Result<(), WError>
pub async fn post_order(
&self,
symbol: &str,
side: OrderSide,
order_type: OrderType,
quantity: f64,
price: Option<f64>,
limit_slippage: Option<bool>,
max_slippage_basis_point: Option<u64>,
) -> Result<SubmitPlaceOrderTransactionResponse, WError>
pub async fn cancel_order(&self, order_id: &str) -> Result<(), WError>
pub fn sign_tx_by_master_key(&self, tx: &str) -> Result<String, WError>
pub fn sign_tx_by_operation_key(&self, tx: &str) -> Result<String, WError>
}
Accounts Module
Manage account operations, balances, and transaction history:
impl Accounts {
pub async fn get_operation_key(&self) -> Result<GetOperationKeyResponse, WError>
pub async fn create_new_api_key(&self) -> Result<CreateNewAPIKeyResponse, WError>
pub async fn get_account_balance(&self) -> Result<GetAccountBalanceResponse, WError>
pub async fn get_deposit_records(&self) -> Result<GetDepositRecordsResponse, WError>
pub async fn get_withdrawal_records(&self) -> Result<GetWithdrawalRecordsResponse, WError>
pub async fn get_order_records(
&self,
status: OrderRecordStatus,
limit: Option<u32>,
page: Option<u32>,
symbol: Option<String>,
) -> Result<GetOrderRecordsResponse, WError>
pub async fn build_deposit_transaction(
&self,
deposit_amount: Vec<Asset>,
input_utxos: Vec<UTxO>,
) -> Result<BuildDepositTransactionResponse, WError>
pub async fn submit_deposit_transaction(
&self,
signed_tx: &str,
) -> Result<SubmitDepositTransactionResponse, WError>
}
Market Module
Access market data and price information:
impl Market {
pub async fn get_market_price(&self, symbol: &str) -> Result<GetMarketPriceResponse, WError>
pub async fn get_aggregated_price(
&self,
symbol: Symbol,
interval: Interval,
start: i64,
end: i64,
) -> Result<GetAggregatedPriceResponse, WError>
}
Order Module
Handle order lifecycle operations:
impl Order {
pub async fn build_place_order_transaction(
&self,
symbol: &str,
side: OrderSide,
order_type: OrderType,
quantity: f64,
price: Option<f64>,
limit_slippage: Option<bool>,
max_slippage_basis_point: Option<u64>,
) -> Result<BuildPlaceOrderTransactionResponse, WError>
pub async fn submit_place_order_transaction(
&self,
order_id: &str,
signed_tx: &str,
) -> Result<SubmitPlaceOrderTransactionResponse, WError>
pub async fn build_cancel_order_transaction(
&self,
order_id: &str,
) -> Result<BuildCancelOrderTransactionResponse, WError>
pub async fn submit_cancel_order_transaction(&self, signed_tx: &str) -> Result<(), WError>
}
🏷️ Types and Enums
Core Types
pub enum Symbol {
ADAUSDM,
}
pub enum Interval {
Interval5m, Interval15m, Interval30m, Interval1h, Interval1d, }
pub enum OrderType {
Market,
Limit,
}
pub enum OrderSide {
Buy,
Sell,
}
pub enum OrderStatus {
Processing,
Open,
FullyFilled,
PartiallyFilled,
Cancelled,
PartiallyCancelled,
Failed,
}
pub enum TransactionStatus {
Building,
HeldForOrder,
Submitted,
SubmissionFailed,
Confirmed,
}
💡 Examples
Complete Order Management
use deltadefi::{DeltaDeFi, Stage, OrderSide, OrderType, OrderRecordStatus};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = setup_client().await?;
let market_order = client.post_order(
"ADAUSDM",
OrderSide::Buy,
OrderType::Market,
50.0,
None, Some(true), Some(100), ).await?;
println!("Market order placed: {}", market_order.order_id);
let limit_order = client.post_order(
"ADAUSDM",
OrderSide::Sell,
OrderType::Limit,
75.0,
Some(1.30), None,
None,
).await?;
println!("Limit order placed: {}", limit_order.order_id);
let order_history = client.accounts.get_order_records(
OrderRecordStatus::OrderHistory,
Some(10), Some(1), None, ).await?;
println!("Order history: {} orders", order_history.total_count);
client.cancel_order(&limit_order.order_id).await?;
println!("Limit order cancelled");
Ok(())
}
async fn setup_client() -> Result<DeltaDeFi, Box<dyn std::error::Error>> {
dotenv::dotenv().ok();
let api_key = std::env::var("DELTADEFI_API_KEY")?;
let password = std::env::var("ENCRYPTION_PASSCODE")?;
let mut client = DeltaDeFi::new(api_key, Stage::Staging, None)?;
client.load_operation_key(&password).await?;
Ok(client)
}
Account Management
use deltadefi::{DeltaDeFi, Stage};
use whisky::{Asset, UTxO};
async fn manage_account(client: &DeltaDeFi) -> Result<(), Box<dyn std::error::Error>> {
let balance = client.accounts.get_account_balance().await?;
println!("Account balances:");
for asset_balance in balance.balances {
println!(" {}: {} free, {} locked",
asset_balance.asset,
asset_balance.free,
asset_balance.locked);
}
let deposits = client.accounts.get_deposit_records().await?;
println!("Recent deposits: {}", deposits.len());
let withdrawal_amount = vec![Asset {
unit: "lovelace".to_string(),
quantity: 1000000.0, }];
let withdrawal_tx = client.accounts
.build_withdrawal_transaction(withdrawal_amount)
.await?;
let signed_tx = client.sign_tx_by_master_key(&withdrawal_tx.tx_hex)?;
let withdrawal_result = client.accounts
.submit_withdrawal_transaction(&signed_tx)
.await?;
println!("Withdrawal submitted: {}", withdrawal_result.tx_hash);
Ok(())
}
Market Data Analysis
use deltadefi::{DeltaDeFi, Stage, Symbol, Interval};
use chrono::{Utc, Duration};
async fn analyze_market_data(client: &DeltaDeFi) -> Result<(), Box<dyn std::error::Error>> {
let current_price = client.market.get_market_price("ADAUSDM").await?;
println!("Current ADAUSDM price: {}", current_price.price);
let now = Utc::now();
let yesterday = now - Duration::hours(24);
let historical_data = client.market.get_aggregated_price(
Symbol::ADAUSDM,
Interval::Interval1h,
yesterday.timestamp(),
now.timestamp(),
).await?;
println!("Historical data points: {}", historical_data.data.len());
if let (Some(first), Some(last)) = (historical_data.data.first(), historical_data.data.last()) {
let price_change = ((last.close - first.open) / first.open) * 100.0;
println!("24h price change: {:.2}%", price_change);
}
Ok(())
}
🛡️ Error Handling
The SDK uses the WError type for comprehensive error handling:
use whisky::WError;
match client.post_order().await {
Ok(response) => println!("Order successful: {}", response.order_id),
Err(WError { source, message }) => {
eprintln!("Order failed - Source: {}, Message: {}", source, message);
match source.as_str() {
"build_place_order_transaction" => {
if message.contains("Missing required parameter") {
eprintln!("Please check order parameters");
}
}
"DeltaDeFi - post - send_request" => {
eprintln!("Network error, please retry");
}
_ => eprintln!("Unexpected error occurred"),
}
}
}
🔐 Security Best Practices
- Environment Variables: Store sensitive data in environment variables
- Key Management: Never hardcode private keys or passwords
- Network Security: Use HTTPS endpoints for all API calls
- Error Handling: Avoid exposing sensitive information in error messages
let api_key = env::var("DELTADEFI_API_KEY")?;
let api_key = "your-api-key-here";
📄 License
This project is licensed under the Apache-2.0 License - see the LICENSE file for details.
🔗 Links
📞 Support