vaea-flash-sdk 0.1.0

VAEA Flash — Universal Flash Loan SDK for Solana. Borrow any SPL token atomically in one call.
Documentation
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use serde::{Deserialize, Serialize};
use std::fmt;

// ═══════════════════════════════════════════════════════════
//  Config
// ═══════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct VaeaConfig {
    pub api_url: String,
    pub source: Source,
}

impl Default for VaeaConfig {
    fn default() -> Self {
        Self {
            api_url: "https://api.vaea.fi".to_string(),
            source: Source::Sdk,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Source {
    Sdk,
    Ui,
    Protocol,
}

impl fmt::Display for Source {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Source::Sdk => write!(f, "sdk"),
            Source::Ui => write!(f, "ui"),
            Source::Protocol => write!(f, "protocol"),
        }
    }
}

// ═══════════════════════════════════════════════════════════
//  Error types
// ═══════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum VaeaErrorCode {
    InsufficientLiquidity,
    TokenNotSupported,
    SlippageExceeded,
    FeeTooHigh,
    RepayFailed,
    TxExpired,
    SourceUnavailable,
    ProgramPaused,
    InvalidAmount,
    InsufficientSolForFee,
    ApiError,
    NetworkError,
}

impl fmt::Display for VaeaErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            VaeaErrorCode::InsufficientLiquidity => write!(f, "INSUFFICIENT_LIQUIDITY"),
            VaeaErrorCode::TokenNotSupported => write!(f, "TOKEN_NOT_SUPPORTED"),
            VaeaErrorCode::SlippageExceeded => write!(f, "SLIPPAGE_EXCEEDED"),
            VaeaErrorCode::FeeTooHigh => write!(f, "FEE_TOO_HIGH"),
            VaeaErrorCode::RepayFailed => write!(f, "REPAY_FAILED"),
            VaeaErrorCode::TxExpired => write!(f, "TX_EXPIRED"),
            VaeaErrorCode::SourceUnavailable => write!(f, "SOURCE_UNAVAILABLE"),
            VaeaErrorCode::ProgramPaused => write!(f, "PROGRAM_PAUSED"),
            VaeaErrorCode::InvalidAmount => write!(f, "INVALID_AMOUNT"),
            VaeaErrorCode::InsufficientSolForFee => write!(f, "INSUFFICIENT_SOL_FOR_FEE"),
            VaeaErrorCode::ApiError => write!(f, "API_ERROR"),
            VaeaErrorCode::NetworkError => write!(f, "NETWORK_ERROR"),
        }
    }
}

// ═══════════════════════════════════════════════════════════
//  Capacity types
// ═══════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CapacityResponse {
    pub updated_at: u64,
    pub tokens: Vec<TokenCapacity>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenCapacity {
    pub symbol: String,
    pub mint: String,
    pub name: String,
    pub decimals: u8,
    pub route_type: String,
    pub source_protocol: String,
    pub max_amount: f64,
    pub max_amount_usd: f64,
    pub fee_sdk: FeeInfo,
    pub fee_ui: FeeInfo,
    pub status: String,
    pub updated_at: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeeInfo {
    pub bps: u16,
    pub pct: f64,
    pub total_pct: f64,
}

// ═══════════════════════════════════════════════════════════
//  Quote types
// ═══════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QuoteResponse {
    pub token: String,
    pub mint: String,
    pub amount_requested: f64,
    pub source: String,
    pub route: RouteQuote,
    pub fee_breakdown: FeeBreakdown,
    pub price_impact: f64,
    pub valid_until: u64,
    pub valid_for_slots: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteQuote {
    #[serde(rename = "type")]
    pub route_type: String,
    pub steps: Vec<RouteStep>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteStep {
    pub action: String,
    pub protocol: String,
    pub token: String,
    pub amount: f64,
    pub expected_output: Option<f64>,
    pub price_impact: Option<f64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeeBreakdown {
    pub source_fee: f64,
    pub vaea_fee: f64,
    pub total_fee_sol: f64,
    pub total_fee_usd: f64,
    pub total_fee_pct: f64,
}

// ═══════════════════════════════════════════════════════════
//  Build types
// ═══════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildRequest {
    pub token: String,
    pub amount: f64,
    pub user_pubkey: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub slippage_bps: Option<u16>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_fee_bps: Option<u16>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiInstructionData {
    pub program_id: String,
    pub data: String,
    pub accounts: Vec<ApiAccountMeta>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiAccountMeta {
    pub pubkey: String,
    pub is_signer: bool,
    pub is_writable: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BuildResponse {
    pub prefix_instructions: Vec<ApiInstructionData>,
    pub suffix_instructions: Vec<ApiInstructionData>,
    pub lookup_tables: Vec<String>,
    pub estimated_fee_lamports: u64,
    pub valid_for_slots: u64,
}

// ═══════════════════════════════════════════════════════════
//  Health types
// ═══════════════════════════════════════════════════════════

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthResponse {
    pub status: String,
    pub timestamp: u64,
    pub components: serde_json::Value,
    pub sources: serde_json::Value,
}

// ═══════════════════════════════════════════════════════════
//  Borrow params
// ═══════════════════════════════════════════════════════════

pub struct BorrowParams {
    pub token: String,
    pub amount: f64,
    pub instructions: Vec<solana_sdk::instruction::Instruction>,
    pub slippage_bps: Option<u16>,
    pub max_fee_bps: Option<u16>,
}

// ═══════════════════════════════════════════════════════════
//  Constants
// ═══════════════════════════════════════════════════════════

pub const VAEA_API_URL: &str = "https://api.vaea.fi";
pub const VAEA_PROGRAM_ID: &str = "VAEAmcjQ5RB9yonyrCRSkRT8womX6uqm5PS7PXr528b";

/// Pre-loaded Address Lookup Table with VAEA fixed accounts.
/// Saves ~124 bytes per transaction by compressing 4 account addresses.
pub const VAEA_LOOKUP_TABLE: solana_sdk::pubkey::Pubkey =
    solana_sdk::pubkey!("CsfmCd4gBs2VNsBQu37kjKttKJTMzePrQwYCDdLnuLDs");

pub const SUPPORTED_TOKENS: &[&str] = &[
    // Direct routes
    "SOL", "USDC", "USDT", "JitoSOL", "JupSOL", "JUP", "JLP", "cbBTC",
    // Direct LSTs
    "mSOL", "bSOL",
    // Sanctum LSTs
    "INF", "laineSOL",
];

/// Fee constant — flat 0.02% for all tiers
pub const FEE_BPS_SDK: u16 = 2;
pub const FEE_BPS_UI: u16 = 2;
pub const FEE_BPS_CPI: u16 = 2;

// ═══════════════════════════════════════════════════════════
//  Extended types
// ═══════════════════════════════════════════════════════════

/// Result of a transaction simulation.
#[derive(Debug, Clone)]
pub struct SimulateResult {
    /// Whether the TX would succeed
    pub success: bool,
    /// Error details if simulation failed
    pub error: Option<String>,
    /// Exact compute units consumed
    pub compute_units: u64,
    /// Full program logs
    pub logs: Vec<String>,
}

/// A single loan request in a multi-borrow.
pub struct MultiBorrowRequest {
    /// Token symbol or mint
    pub token: String,
    /// Borrow amount in human units
    pub amount: f64,
}

/// Params for multi-token atomic flash loans.
pub struct BorrowMultiParams {
    /// Array of loans to execute atomically
    pub loans: Vec<MultiBorrowRequest>,
    /// User instructions to insert between all borrows and all repays
    pub instructions: Vec<solana_sdk::instruction::Instruction>,
    /// Max slippage in bps
    pub slippage_bps: Option<u16>,
    /// Max fee guard in bps
    pub max_fee_bps: Option<u16>,
}

// ═══════════════════════════════════════════════════════════
//  v2: Zero-CPI Types
// ═══════════════════════════════════════════════════════════

/// Source tier for fee routing
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlashTier {
    Sdk = 0,
    Ui = 1,
    Protocol = 2,
}

impl FlashTier {
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0 => Some(Self::Sdk),
            1 => Some(Self::Ui),
            2 => Some(Self::Protocol),
            _ => None,
        }
    }

    pub fn fee_bps(&self) -> u16 {
        match self {
            Self::Sdk => FEE_BPS_SDK,
            Self::Ui => FEE_BPS_UI,
            Self::Protocol => FEE_BPS_CPI,
        }
    }
}

/// On-chain FlashState v2 (102 bytes)
#[derive(Debug, Clone)]
pub struct FlashStateInfo {
    /// Borrower pubkey
    pub payer: solana_sdk::pubkey::Pubkey,
    /// Token mint borrowed
    pub token_mint: solana_sdk::pubkey::Pubkey,
    /// Amount borrowed in native units
    pub amount: u64,
    /// Fee in native units
    pub fee: u64,
    /// Source tier (0=SDK, 1=UI, 2=Protocol)
    pub source_tier: u8,
    /// Human-readable tier
    pub tier: FlashTier,
    /// Slot when created
    pub slot_created: u64,
    /// PDA bump
    pub bump: u8,
}

/// Per-source capacity detail
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceCapacity {
    pub protocol: String,
    pub pool: String,
    pub available: f64,
    pub available_usd: f64,
    pub utilization_pct: f64,
    pub status: String,
}

/// Aggregated capacity for a token across all sources
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AggregatedTokenCapacity {
    #[serde(flatten)]
    pub base: TokenCapacity,
    pub sources: Vec<SourceCapacity>,
    pub total_available: f64,
    pub total_available_usd: f64,
}

// ═══════════════════════════════════════════════════════════
//  Liquidity Matrix types (Phase 2)
// ═══════════════════════════════════════════════════════════

/// Per-token liquidity breakdown across all lending protocols.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MatrixTokenEntry {
    pub mint: String,
    pub symbol: String,
    pub name: String,
    pub decimals: u8,
    pub is_direct: bool,
    /// Per-protocol available liquidity (human-readable units)
    pub liquidity: std::collections::HashMap<String, f64>,
    pub total_liquidity: f64,
    pub total_liquidity_usd: f64,
    pub cheapest_source_fee_bps: u16,
    pub best_protocol: Option<String>,
}

/// Response from GET /v1/matrix.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MatrixResponse {
    pub updated_at: u64,
    pub total_tokens: u32,
    pub total_direct: u32,
    pub protocols: Vec<String>,
    pub tokens: Vec<MatrixTokenEntry>,
}

// ═══════════════════════════════════════════════════════════
//  Discovery types (Phase 1)
// ═══════════════════════════════════════════════════════════

/// Response from GET /v1/discovery.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverySummary {
    pub direct_count: Option<u32>,
    pub total_count: Option<u32>,
    pub scan_duration_ms: Option<u64>,
    #[serde(default)]
    pub protocols: Vec<String>,
    pub updated_at: Option<u64>,
}

// ═══════════════════════════════════════════════════════════
//  Smart Router types (Phase 3)
// ═══════════════════════════════════════════════════════════

/// A single route candidate evaluated by the Smart Router.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteCandidate {
    pub strategy_type: String,
    pub protocol: String,
    pub available_liquidity: f64,
    pub protocol_fee_bps: u16,
    pub vaea_fee_bps: u16,
    pub total_cost_bps: u16,
    pub total_cost_usd: f64,
    pub sufficient_liquidity: bool,
    pub feasible: bool,
}

/// Response from GET /v1/route — the optimal flash loan route.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolvedRoute {
    pub token_mint: String,
    pub token_symbol: String,
    pub amount: f64,
    pub amount_usd: f64,
    pub strategy: serde_json::Value,  // {"direct": {...}}
    pub candidates: Vec<RouteCandidate>,
    pub reasoning: String,
}


// ═══════════════════════════════════════════════════════════
//  Sources types
// ═══════════════════════════════════════════════════════════

/// A lending protocol in the sources response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProtocolInfo {
    pub id: String,
    pub name: String,
    pub program_id: String,
    pub token_count: u32,
    pub tokens: Vec<String>,
}

/// Fee tier detail.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeeTierInfo {
    pub bps: u16,
}

/// Response from GET /v1/sources.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourcesResponse {
    pub discovery: String,
    pub protocols: Vec<ProtocolInfo>,
    pub fee_tiers: std::collections::HashMap<String, FeeTierInfo>,
}

// ═══════════════════════════════════════════════════════════
//  Aggregated Capacity Response
// ═══════════════════════════════════════════════════════════

/// Response from GET /v1/capacity/aggregated.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AggregatedCapacityResponse {
    pub updated_at: u64,
    pub tokens: Vec<serde_json::Value>,
}