aspens 0.7.0

Aspens crosschain trading SDK
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
use eyre::{Context, Result};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use url::Url;

use crate::commands::config::config_pb::{Chain, GetConfigResponse, Token};

/// JWT token information for authenticated admin operations
#[derive(Debug, Clone)]
pub struct JwtToken {
    /// The JWT token string
    pub token: String,
    /// Unix timestamp when the token expires (in seconds)
    pub expires_at: u64,
}

/// Transport for trading actions. Config discovery always uses gRPC; actions
/// (orders/cancels/withdraws/reads) route through the selected transport.
#[cfg(feature = "fce")]
#[derive(Clone)]
pub enum Transport {
    /// Direct arborter gRPC (the default).
    Grpc,
    /// The Flare Confidential Extension proxy (`POST /direct` + poll).
    Fce(crate::fce::FceClient),
}

#[cfg(feature = "fce")]
impl std::fmt::Debug for Transport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Transport::Grpc => write!(f, "Transport::Grpc"),
            Transport::Fce(_) => write!(f, "Transport::Fce"),
        }
    }
}

/// Main client for interacting with Aspens trading platform
pub struct AspensClient {
    /// URL of the Aspens Market Stack
    pub(crate) stack_url: Url,
    /// Environment variables loaded from .env file
    pub(crate) env_vars: HashMap<String, String>,
    /// Cached configuration from the server
    pub(crate) config: Arc<RwLock<Option<GetConfigResponse>>>,
    /// JWT token for admin operations (when authenticated)
    pub(crate) jwt_token: Arc<RwLock<Option<JwtToken>>>,
    /// Trading-action transport (gRPC unless an FCE proxy is configured).
    #[cfg(feature = "fce")]
    pub(crate) transport: Transport,
}

impl AspensClient {
    /// Create a new builder for AspensClient
    pub fn builder() -> AspensClientBuilder {
        AspensClientBuilder::default()
    }

    /// Get the Aspens Market Stack URL
    pub fn stack_url(&self) -> &Url {
        &self.stack_url
    }

    /// Get an environment variable value
    pub fn get_env(&self, key: &str) -> Option<&String> {
        self.env_vars.get(key)
    }

    /// Fetch configuration from the server and cache it
    pub async fn fetch_config(&self) -> Result<()> {
        // With an FCE transport, discover config over `/direct` too. Otherwise a
        // client that routes every ACTION through the proxy would still need
        // arborter gRPC reachability just to learn market decimals — which is
        // exactly the dependency the FCE transport exists to remove.
        #[cfg(feature = "fce")]
        if self.uses_fce() {
            let config = crate::commands::trading::fce_actions::get_config(self).await?;
            let mut guard = self
                .config
                .write()
                .expect("AspensClient config lock poisoned");
            *guard = Some(config);
            return Ok(());
        }
        let config = crate::commands::config::get_config(self.stack_url.to_string()).await?;
        let mut guard = self
            .config
            .write()
            .expect("AspensClient config lock poisoned");
        *guard = Some(config);
        Ok(())
    }

    /// Get the cached configuration, fetching it if necessary
    pub async fn get_config(&self) -> Result<GetConfigResponse> {
        // Check if we have a cached config
        {
            let guard = self
                .config
                .read()
                .expect("AspensClient config lock poisoned");
            if let Some(config) = guard.as_ref() {
                return Ok(config.clone());
            }
        }

        // No cached config, fetch it
        self.fetch_config().await?;

        // Return the newly fetched config
        let guard = self
            .config
            .read()
            .expect("AspensClient config lock poisoned");
        guard
            .as_ref()
            .cloned()
            .ok_or_else(|| eyre::eyre!("Failed to fetch configuration"))
    }

    /// Get chain information by network name
    pub async fn get_chain_info(&self, network: &str) -> Result<Chain> {
        let config = self.get_config().await?;
        config.get_chain(network).cloned().ok_or_else(|| {
            eyre::eyre!(
                "Chain '{}' not found in configuration. Available chains: {}",
                network,
                config
                    .config
                    .as_ref()
                    .map(|c| c
                        .chains
                        .iter()
                        .map(|ch| ch.network.as_str())
                        .collect::<Vec<_>>()
                        .join(", "))
                    .unwrap_or_default()
            )
        })
    }

    /// Get token information by network and symbol
    pub async fn get_token_info(&self, network: &str, symbol: &str) -> Result<Token> {
        let config = self.get_config().await?;
        config.get_token(network, symbol).cloned().ok_or_else(|| {
            let available_tokens = config
                .get_chain(network)
                .map(|chain| {
                    chain
                        .tokens
                        .keys()
                        .map(|s| s.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                })
                .unwrap_or_else(|| "none".to_string());

            eyre::eyre!(
                "Token '{}' not found on chain '{}'. Available tokens: {}",
                symbol,
                network,
                available_tokens
            )
        })
    }

    /// Get trade contract address for a given network
    pub async fn get_trade_contract_address(&self, network: &str) -> Result<String> {
        let chain = self.get_chain_info(network).await?;
        chain
            .trade_contract
            .as_ref()
            .map(|tc| tc.address.clone())
            .ok_or_else(|| {
                eyre::eyre!(
                    "Trade contract not found for chain '{}'. Please ensure the contract is deployed.",
                    network
                )
            })
    }

    /// Set the JWT token for admin operations
    pub fn set_jwt_token(&self, token: String, expires_at: u64) {
        let mut guard = self
            .jwt_token
            .write()
            .expect("AspensClient JWT lock poisoned");
        *guard = Some(JwtToken { token, expires_at });
    }

    /// The configured trading-action transport.
    #[cfg(feature = "fce")]
    pub fn transport(&self) -> &Transport {
        &self.transport
    }

    /// True when trading actions route through the FCE proxy.
    #[cfg(feature = "fce")]
    pub fn uses_fce(&self) -> bool {
        matches!(self.transport, Transport::Fce(_))
    }

    /// The FCE proxy client, when an FCE transport is configured.
    #[cfg(feature = "fce")]
    pub fn fce(&self) -> Option<&crate::fce::FceClient> {
        match &self.transport {
            Transport::Fce(c) => Some(c),
            Transport::Grpc => None,
        }
    }

    /// Get the current JWT token if valid
    pub fn get_jwt_token(&self) -> Option<String> {
        let guard = self
            .jwt_token
            .read()
            .expect("AspensClient JWT lock poisoned");
        guard.as_ref().and_then(|jwt| {
            if self.is_jwt_valid_internal(jwt) {
                Some(jwt.token.clone())
            } else {
                None
            }
        })
    }

    /// Check if the current JWT token is valid
    pub fn is_jwt_valid(&self) -> bool {
        let guard = self
            .jwt_token
            .read()
            .expect("AspensClient JWT lock poisoned");
        guard
            .as_ref()
            .map(|jwt| self.is_jwt_valid_internal(jwt))
            .unwrap_or(false)
    }

    /// Internal helper to check JWT validity
    fn is_jwt_valid_internal(&self, jwt: &JwtToken) -> bool {
        use std::time::{SystemTime, UNIX_EPOCH};
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        // Add a 30 second buffer for clock skew
        jwt.expires_at > now + 30
    }

    /// Clear the JWT token
    pub fn clear_jwt_token(&self) {
        let mut guard = self
            .jwt_token
            .write()
            .expect("AspensClient JWT lock poisoned");
        *guard = None;
    }

    /// Get JWT expiry time (if set)
    pub fn get_jwt_expiry(&self) -> Option<u64> {
        let guard = self
            .jwt_token
            .read()
            .expect("AspensClient JWT lock poisoned");
        guard.as_ref().map(|jwt| jwt.expires_at)
    }
}

/// Builder for AspensClient
#[derive(Default)]
pub struct AspensClientBuilder {
    stack_url: Option<Url>,
    env_file_path: Option<String>,
    /// (proxy_url, api_key) for the FCE transport, if set explicitly.
    #[cfg(feature = "fce")]
    fce: Option<(String, Option<String>)>,
}

impl AspensClientBuilder {
    /// Set the Aspens Market Stack Url
    pub fn with_url(mut self, url: impl Into<String>) -> Result<Self> {
        let url_str = url.into();
        self.stack_url = Some(Url::parse(&url_str).context("Invalid URL")?);
        Ok(self)
    }

    /// Set custom environment file path (defaults to .env)
    pub fn with_env_file(mut self, path: impl Into<String>) -> Self {
        self.env_file_path = Some(path.into());
        self
    }

    /// Route trading actions through the FCE proxy at `proxy_url`, authenticating
    /// with `api_key` (the proxy's `DIRECT_API_KEY`, sent as `X-API-Key`).
    /// Config discovery still uses gRPC against the stack URL.
    #[cfg(feature = "fce")]
    pub fn with_fce(mut self, proxy_url: impl Into<String>, api_key: Option<String>) -> Self {
        self.fce = Some((proxy_url.into(), api_key));
        self
    }

    /// Build the AspensClient
    pub fn build(self) -> Result<AspensClient> {
        // Load environment file (defaults to .env)
        let env_file = self.env_file_path.unwrap_or_else(|| ".env".to_string());

        let env_vars = load_env_file(&env_file)?;

        let stack_url = self
            .stack_url
            .or_else(|| {
                env_vars
                    .get("ASPENS_MARKET_STACK_URL")
                    .and_then(|u| Url::parse(u).ok())
            })
            .ok_or_else(|| {
                eyre::eyre!(
                    "aspens stack URL is not set: use AspensClient::builder().with_url(\"...\"), \
                     or set ASPENS_MARKET_STACK_URL in {} (or in the process environment before build).",
                    env_file
                )
            })?;

        // FCE transport: explicit `.with_fce(...)` wins; otherwise auto-detect
        // from `EXT_PROXY_URL` (+ optional `DIRECT_API_KEY`) in the env file /
        // process env. Absent both, actions use gRPC.
        #[cfg(feature = "fce")]
        let transport = {
            let cfg = self.fce.or_else(|| {
                env_vars
                    .get("EXT_PROXY_URL")
                    .filter(|u| !u.is_empty())
                    .map(|u| (u.clone(), env_vars.get("DIRECT_API_KEY").cloned()))
            });
            match cfg {
                Some((url, key)) => {
                    let mut fce = crate::fce::FceClient::new(url, key)?;
                    // The ext-proxy queues direct actions, so end-to-end latency
                    // is the queue depth, not the arborter. A backlogged proxy
                    // pushes a result minutes out and the 15 × 2s default gives
                    // up long before it lands — the action still executed, which
                    // reads as a silent failure. Let the caller widen the wait.
                    if let Some(attempts) = env_vars
                        .get("FCE_POLL_ATTEMPTS")
                        .and_then(|v| v.parse::<u32>().ok())
                    {
                        let interval = env_vars
                            .get("FCE_POLL_INTERVAL_SECS")
                            .and_then(|v| v.parse::<u64>().ok())
                            .unwrap_or(2);
                        fce = fce.with_polling(attempts, std::time::Duration::from_secs(interval));
                    }
                    Transport::Fce(fce)
                }
                None => Transport::Grpc,
            }
        };

        Ok(AspensClient {
            stack_url,
            env_vars,
            config: Arc::new(RwLock::new(None)),
            jwt_token: Arc::new(RwLock::new(None)),
            #[cfg(feature = "fce")]
            transport,
        })
    }
}

/// Load environment variables from a .env file
fn load_env_file(path: &str) -> Result<HashMap<String, String>> {
    use std::fs;
    use std::io::{BufRead, BufReader};

    let mut env_vars = HashMap::new();

    // Try to load the file, but don't fail if it doesn't exist
    if let Ok(file) = fs::File::open(path) {
        let reader = BufReader::new(file);
        for line in reader.lines() {
            let line = line?;
            let line = line.trim();

            // Skip empty lines and comments
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // Parse KEY=VALUE
            if let Some((key, value)) = line.split_once('=') {
                let key = key.trim().to_string();
                let mut value = value.trim().to_string();

                // Strip surrounding quotes if present
                if (value.starts_with('"') && value.ends_with('"'))
                    || (value.starts_with('\'') && value.ends_with('\''))
                {
                    value = value[1..value.len() - 1].to_string();
                }

                env_vars.insert(key.clone(), value.clone());
                // Also set in process environment for backwards compatibility
                unsafe {
                    std::env::set_var(&key, &value);
                }
            }
        }
    }

    Ok(env_vars)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_builder_with_url() {
        let client = AspensClient::builder()
            .with_url("http://example.com:8080")
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(client.stack_url().as_str(), "http://example.com:8080/");
    }

    #[test]
    fn test_builder_requires_stack_url() {
        let file = NamedTempFile::new().unwrap();
        let err = AspensClient::builder()
            .with_env_file(file.path().to_str().unwrap())
            .build()
            .err()
            .expect("builder should fail without ASPENS_MARKET_STACK_URL");
        let msg = err.to_string();
        assert!(
            msg.contains("ASPENS_MARKET_STACK_URL") && msg.contains("stack URL"),
            "unexpected error: {}",
            msg
        );
    }

    #[test]
    fn test_env_file_quote_stripping() {
        // Create a temporary .env file with quoted values
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "DOUBLE_QUOTED=\"value1\"").unwrap();
        writeln!(file, "SINGLE_QUOTED='value2'").unwrap();
        writeln!(file, "UNQUOTED=value3").unwrap();
        writeln!(file, "# Comment line").unwrap();
        writeln!(file, "EMPTY_VALUE=\"\"").unwrap();
        file.flush().unwrap();

        let env_vars = load_env_file(file.path().to_str().unwrap()).unwrap();

        assert_eq!(env_vars.get("DOUBLE_QUOTED"), Some(&"value1".to_string()));
        assert_eq!(env_vars.get("SINGLE_QUOTED"), Some(&"value2".to_string()));
        assert_eq!(env_vars.get("UNQUOTED"), Some(&"value3".to_string()));
        assert_eq!(env_vars.get("EMPTY_VALUE"), Some(&"".to_string()));
    }

    /// Builds an FCE-transport client from an env file carrying `extra` lines.
    #[cfg(feature = "fce")]
    fn fce_client_from_env(extra: &[&str]) -> AspensClient {
        let mut file = NamedTempFile::new().unwrap();
        writeln!(file, "ASPENS_MARKET_STACK_URL=http://example.com:8080").unwrap();
        writeln!(file, "EXT_PROXY_URL=http://example.com:6674").unwrap();
        for line in extra {
            writeln!(file, "{line}").unwrap();
        }
        file.flush().unwrap();
        AspensClient::builder()
            .with_env_file(file.path().to_str().unwrap())
            .build()
            .unwrap()
    }

    #[test]
    #[cfg(feature = "fce")]
    fn fce_poll_schedule_defaults_when_env_absent() {
        let client = fce_client_from_env(&[]);
        let (attempts, interval) = client.fce().expect("FCE transport").polling();
        assert_eq!(attempts, 15);
        assert_eq!(interval, std::time::Duration::from_secs(2));
    }

    #[test]
    #[cfg(feature = "fce")]
    fn fce_poll_schedule_honours_env() {
        let client = fce_client_from_env(&["FCE_POLL_ATTEMPTS=200", "FCE_POLL_INTERVAL_SECS=10"]);
        let (attempts, interval) = client.fce().expect("FCE transport").polling();
        assert_eq!(attempts, 200);
        assert_eq!(interval, std::time::Duration::from_secs(10));
    }

    /// The interval is optional: attempts alone widens the wait, keeping the
    /// 2s default cadence.
    #[test]
    #[cfg(feature = "fce")]
    fn fce_poll_attempts_alone_keeps_default_interval() {
        let client = fce_client_from_env(&["FCE_POLL_ATTEMPTS=50"]);
        let (attempts, interval) = client.fce().expect("FCE transport").polling();
        assert_eq!(attempts, 50);
        assert_eq!(interval, std::time::Duration::from_secs(2));
    }

    /// A garbled value must not silently become a 0-attempt schedule — that
    /// would turn every action into an instant "no result" while it executes.
    #[test]
    #[cfg(feature = "fce")]
    fn fce_poll_schedule_ignores_unparseable_values() {
        let client = fce_client_from_env(&["FCE_POLL_ATTEMPTS=soon", "FCE_POLL_INTERVAL_SECS=x"]);
        let (attempts, interval) = client.fce().expect("FCE transport").polling();
        assert_eq!(attempts, 15);
        assert_eq!(interval, std::time::Duration::from_secs(2));
    }
}