Skip to main content

qualia_client_core/api/
tokens.rs

1//! Token registry, wallet, identity, coins, transactions
2
3#![allow(non_snake_case)]
4
5use super::*;
6
7use crate::engine::llm_offload;
8use crate::state::*;
9use serde::{Deserialize, Serialize};
10use std::path::{Path, PathBuf};
11use std::sync::atomic::Ordering;
12use std::time::Duration;
13use tokio::time::sleep;
14
15#[derive(Serialize, Deserialize, Clone)]
16pub struct TokenEntry {
17    id: String,
18    chain: String,      // "eCash" | "Ethereum" | "Nyx"
19    token_type: String, // "ALP" | "SLP" | "ERC-20" | "CW-20"
20    contract: String,   // token ID / contract address
21    symbol: String,
22    name: String,
23    balance: String,
24    decimals: u8,
25    fiat_usd: f64,
26}
27
28/// Tokens file path.
29pub fn tokens_file_path(storage_path: &str) -> PathBuf {
30    PathBuf::from(storage_path).join("tokens.json")
31}
32
33/// Default token list.
34pub fn default_tokens() -> Vec<TokenEntry> {
35    vec![
36        TokenEntry {
37            id: "alp-lion".into(),
38            chain: "eCash".into(),
39            token_type: "ALP".into(),
40            contract: "alp:0x1A2B3C4D...".into(),
41            symbol: "LION".into(),
42            name: "Lion Rampant (Heraldry)".into(),
43            balance: "1.00".into(),
44            decimals: 8,
45            fiat_usd: 0.0,
46        },
47        TokenEntry {
48            id: "alp-horus".into(),
49            chain: "eCash".into(),
50            token_type: "ALP".into(),
51            contract: "alp:0x9B4C5D6E...".into(),
52            symbol: "HORUS".into(),
53            name: "Eye of Horus (Artifact)".into(),
54            balance: "50.00".into(),
55            decimals: 8,
56            fiat_usd: 0.0,
57        },
58        TokenEntry {
59            id: "slp-meme".into(),
60            chain: "eCash".into(),
61            token_type: "SLP".into(),
62            contract: "slp:0x44F1A2B3...".into(),
63            symbol: "MEME".into(),
64            name: "Early Beta Meme Coin".into(),
65            balance: "150000.00".into(),
66            decimals: 2,
67            fiat_usd: 0.0,
68        },
69        TokenEntry {
70            id: "erc20-usdt".into(),
71            chain: "Ethereum".into(),
72            token_type: "ERC-20".into(),
73            contract: "0xdAC17F958D2ee523a2206206994597C13D831ec7".into(),
74            symbol: "USDT".into(),
75            name: "Tether USD".into(),
76            balance: "250.00".into(),
77            decimals: 6,
78            fiat_usd: 250.0,
79        },
80        TokenEntry {
81            id: "erc20-usdc".into(),
82            chain: "Ethereum".into(),
83            token_type: "ERC-20".into(),
84            contract: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48".into(),
85            symbol: "USDC".into(),
86            name: "USD Coin".into(),
87            balance: "100.00".into(),
88            decimals: 6,
89            fiat_usd: 100.0,
90        },
91        TokenEntry {
92            id: "erc20-link".into(),
93            chain: "Ethereum".into(),
94            token_type: "ERC-20".into(),
95            contract: "0x514910771AF9Ca656af840dff83E8264EcF986CA".into(),
96            symbol: "LINK".into(),
97            name: "Chainlink Token".into(),
98            balance: "12.50".into(),
99            decimals: 18,
100            fiat_usd: 162.5,
101        },
102        TokenEntry {
103            id: "cw20-vnym".into(),
104            chain: "Nyx".into(),
105            token_type: "CW-20".into(),
106            contract: "nyx1staking000000000000000000000000000000000000".into(),
107            symbol: "vNYM".into(),
108            name: "Vested NYM (Staking)".into(),
109            balance: "100.00".into(),
110            decimals: 6,
111            fiat_usd: 2.0,
112        },
113    ]
114}
115
116/// Loads tokens-from-disk.
117pub fn load_tokens_from_disk(storage_path: &str) -> Vec<TokenEntry> {
118    let path = tokens_file_path(storage_path);
119    std::fs::read_to_string(&path)
120        .ok()
121        .and_then(|s| serde_json::from_str(&s).ok())
122        .unwrap_or_else(default_tokens)
123}
124
125/// Saves tokens-to-disk.
126pub fn save_tokens_to_disk(storage_path: &str, tokens: &[TokenEntry]) -> Result<(), String> {
127    let json = serde_json::to_string_pretty(tokens).map_err(|e| e.to_string())?;
128    std::fs::write(tokens_file_path(storage_path), json).map_err(|e| e.to_string())
129}
130
131/// Gets tokens.
132pub fn get_tokens() -> Vec<TokenEntry> {
133    let state = crate::state::APP_STATE.get().unwrap();
134    let storage_path = state.config.lock().unwrap().storage_path.clone();
135    let mut tokens = load_tokens_from_disk(&storage_path);
136
137    let id = read_identity();
138    if let Some(hash160) = id
139        .as_ref()
140        .and_then(|v| v.get("ecash_hash160"))
141        .and_then(|v| v.as_str())
142    {
143        let client = crate::wallet::chronik::ChronikClient::new("https://chronik.be.cash");
144        if let Ok(utxos) = client.fetch_utxos_p2pkh(hash160) {
145            let mut balances: std::collections::HashMap<String, u64> =
146                std::collections::HashMap::new();
147            for utxo in utxos {
148                if let Some(meta) = utxo.slp_meta {
149                    if let Some(token) = utxo.slp_token {
150                        if let Ok(amount) = token.amount.parse::<u64>() {
151                            *balances.entry(meta.token_id).or_insert(0) += amount;
152                        }
153                    }
154                }
155            }
156
157            for t in tokens.iter_mut() {
158                if t.chain == "eCash" {
159                    // Extract token ID from contract e.g. "slp:0x123..."
160                    let token_id = t.contract.split("0x").nth(1).unwrap_or("").to_string();
161                    if let Some(&amt) = balances.get(&token_id.to_lowercase()) {
162                        let float_amt = amt as f64 / 10f64.powi(t.decimals as i32);
163                        t.balance = format!("{:.2}", float_amt);
164                    }
165                }
166            }
167        }
168    }
169
170    tokens
171}
172
173/// Adds token.
174pub fn add_token(
175    chain: String,
176    token_type: String,
177    contract: String,
178    symbol: String,
179    name: String,
180    decimals: u8,
181) -> Result<TokenEntry, String> {
182    let state = crate::state::APP_STATE.get().unwrap();
183    let storage_path = state.config.lock().unwrap().storage_path.clone();
184    let mut tokens = load_tokens_from_disk(&storage_path);
185
186    if tokens
187        .iter()
188        .any(|t| t.contract.to_lowercase() == contract.to_lowercase() && t.chain == chain)
189    {
190        return Err("Token already in wallet".to_string());
191    }
192    let slug: String = contract
193        .chars()
194        .rev()
195        .take(8)
196        .collect::<String>()
197        .chars()
198        .rev()
199        .collect();
200    let id = format!(
201        "{}-{}",
202        chain.to_lowercase().replace(' ', "-"),
203        slug.to_lowercase()
204    );
205    let entry = TokenEntry {
206        id,
207        chain,
208        token_type,
209        contract,
210        symbol,
211        name,
212        balance: "0.00".into(),
213        decimals,
214        fiat_usd: 0.0,
215    };
216    tokens.push(entry.clone());
217    save_tokens_to_disk(&storage_path, &tokens)?;
218    Ok(entry)
219}
220
221/// Sends an eCash token.
222pub fn send_ecash_token(
223    token_id: &str,
224    destination_address: &str,
225    amount: u64,
226) -> Result<String, String> {
227    use crate::wallet::coin_select;
228    use crate::wallet::signer::{hash160, sign_p2pkh_input};
229    use crate::wallet::transaction::{Transaction, TxIn, TxOut};
230    use bip32::XPrv;
231    use std::str::FromStr;
232
233    let id = read_identity().ok_or("No identity set — generate a seed first")?;
234    let hash160_hex = id
235        .get("ecash_hash160")
236        .and_then(|v| v.as_str())
237        .ok_or("No ecash_hash160 in identity")?;
238
239    // Derive the private key from stored seed
240    let mnemonic_str = load_mnemonic_from_vault()?;
241    let mnemonic = bip39::Mnemonic::parse_in(bip39::Language::English, &mnemonic_str)
242        .map_err(|_| "Invalid stored mnemonic")?;
243    let seed_bytes = mnemonic.to_seed("");
244    let master = XPrv::new(&seed_bytes).map_err(|e| e.to_string())?;
245    let xec_path =
246        bip32::DerivationPath::from_str("m/44'/899'/0'/0/0").map_err(|e| e.to_string())?;
247    let mut child = master.clone();
248    for c in xec_path.iter() {
249        child = child.derive_child(c).map_err(|e| e.to_string())?;
250    }
251
252    // Fetch UTXOs
253    let client = crate::wallet::chronik::ChronikClient::new("https://chronik.be.cash");
254    let utxos = client.fetch_utxos_p2pkh(hash160_hex)?;
255
256    // Select token UTXOs + funding UTXOs
257    let (token_utxos, xec_selection) = coin_select::select_token_utxos(&utxos, token_id, amount)?;
258
259    // Build the transaction
260    let mut tx = Transaction::new();
261
262    // Add token inputs
263    for utxo in &token_utxos {
264        tx.inputs.push(TxIn {
265            prev_txid: utxo.outpoint.txid.clone(),
266            prev_out_idx: utxo.outpoint.out_idx,
267            signature_script: Vec::new(),
268            sequence: 0xFFFFFFFF,
269        });
270    }
271    // Add funding inputs
272    for utxo in &xec_selection.selected {
273        tx.inputs.push(TxIn {
274            prev_txid: utxo.outpoint.txid.clone(),
275            prev_out_idx: utxo.outpoint.out_idx,
276            signature_script: Vec::new(),
277            sequence: 0xFFFFFFFF,
278        });
279    }
280
281    // Output 0: OP_RETURN with SLP SEND
282    let op_return_script =
283        crate::wallet::semantic_tokens::generate_slp_send_op_return(token_id, &[amount]);
284    tx.outputs.push(TxOut {
285        value: 0,
286        pk_script: op_return_script,
287    });
288
289    // Output 1: Token recipient (dust amount)
290    let dest_pubkey_hash = decode_ecash_address(destination_address)?;
291    let mut p2pkh_script = vec![0x76, 0xa9, 0x14];
292    p2pkh_script.extend_from_slice(&dest_pubkey_hash);
293    p2pkh_script.extend_from_slice(&[0x88, 0xac]);
294    tx.outputs.push(TxOut {
295        value: coin_select::DUST_THRESHOLD_SATS as u64,
296        pk_script: p2pkh_script,
297    });
298
299    // Output 2: Change (if any)
300    if xec_selection.change_sats > 0 {
301        let own_pubkey_hash = hash160(&child.public_key().to_bytes());
302        let mut change_script = vec![0x76, 0xa9, 0x14];
303        change_script.extend_from_slice(&own_pubkey_hash);
304        change_script.extend_from_slice(&[0x88, 0xac]);
305        tx.outputs.push(TxOut {
306            value: xec_selection.change_sats as u64,
307            pk_script: change_script,
308        });
309    }
310
311    // Sign all inputs
312    let all_utxos: Vec<&crate::wallet::chronik::ChronikUtxo> = token_utxos
313        .iter()
314        .chain(xec_selection.selected.iter())
315        .collect();
316    for (i, utxo) in all_utxos.iter().enumerate() {
317        let script_sig = sign_p2pkh_input(&tx, i, utxo.value as u64, &child);
318        tx.inputs[i].signature_script = script_sig;
319    }
320
321    // Broadcast
322    let raw_hex = hex::encode(tx.serialize());
323    let txid = client.broadcast_tx(&raw_hex)?;
324
325    // Record in ledger
326    let state = crate::state::APP_STATE.get().unwrap();
327    let storage = state.config.lock().unwrap().storage_path.clone();
328    let _ = crate::wallet::ledger::append_entry(
329        std::path::Path::new(&storage),
330        &crate::wallet::ledger::new_entry(crate::wallet::ledger::LedgerEntryKind::TxBroadcast {
331            chain: "XEC".into(),
332            txid: txid.clone(),
333            amount_sats: amount,
334            direction: "out".into(),
335        }),
336    );
337
338    Ok(txid)
339}
340
341/// Build a native XEC send transaction (preview only — does not broadcast).
342/// Returns the raw transaction hex and a fee estimate for user confirmation.
343#[derive(Serialize, Clone)]
344pub struct SendPreview {
345    pub raw_hex: String,
346    pub fee_sats: i64,
347    pub total_input_sats: i64,
348    pub change_sats: i64,
349    pub target_sats: i64,
350}
351
352/// Builds send-xec.
353pub fn build_send_xec(destination_address: &str, amount_sats: i64) -> Result<SendPreview, String> {
354    use crate::wallet::coin_select;
355    use crate::wallet::signer::{hash160, sign_p2pkh_input};
356    use crate::wallet::transaction::{Transaction, TxIn, TxOut};
357    use bip32::XPrv;
358    use std::str::FromStr;
359
360    if amount_sats <= 0 {
361        return Err("Amount must be positive".into());
362    }
363
364    let id = read_identity().ok_or("No identity set — generate a seed first")?;
365    let hash160_hex = id
366        .get("ecash_hash160")
367        .and_then(|v| v.as_str())
368        .ok_or("No ecash_hash160 in identity")?;
369
370    let mnemonic_str = load_mnemonic_from_vault()?;
371    let mnemonic = bip39::Mnemonic::parse_in(bip39::Language::English, &mnemonic_str)
372        .map_err(|_| "Invalid stored mnemonic")?;
373    let seed_bytes = mnemonic.to_seed("");
374    let master = XPrv::new(&seed_bytes).map_err(|e| e.to_string())?;
375    let xec_path =
376        bip32::DerivationPath::from_str("m/44'/899'/0'/0/0").map_err(|e| e.to_string())?;
377    let mut child = master.clone();
378    for c in xec_path.iter() {
379        child = child.derive_child(c).map_err(|e| e.to_string())?;
380    }
381
382    let client = crate::wallet::chronik::ChronikClient::new("https://chronik.be.cash");
383    let utxos = client.fetch_utxos_p2pkh(hash160_hex)?;
384    let selection = coin_select::select_utxos(&utxos, amount_sats)?;
385
386    let mut tx = Transaction::new();
387    for utxo in &selection.selected {
388        tx.inputs.push(TxIn {
389            prev_txid: utxo.outpoint.txid.clone(),
390            prev_out_idx: utxo.outpoint.out_idx,
391            signature_script: Vec::new(),
392            sequence: 0xFFFFFFFF,
393        });
394    }
395
396    // Recipient output
397    let dest_pubkey_hash = decode_ecash_address(destination_address)?;
398    let mut p2pkh_script = vec![0x76, 0xa9, 0x14];
399    p2pkh_script.extend_from_slice(&dest_pubkey_hash);
400    p2pkh_script.extend_from_slice(&[0x88, 0xac]);
401    tx.outputs.push(TxOut {
402        value: amount_sats as u64,
403        pk_script: p2pkh_script,
404    });
405
406    // Change output
407    if selection.change_sats > 0 {
408        let own_pubkey_hash = hash160(&child.public_key().to_bytes());
409        let mut change_script = vec![0x76, 0xa9, 0x14];
410        change_script.extend_from_slice(&own_pubkey_hash);
411        change_script.extend_from_slice(&[0x88, 0xac]);
412        tx.outputs.push(TxOut {
413            value: selection.change_sats as u64,
414            pk_script: change_script,
415        });
416    }
417
418    // Sign
419    for (i, utxo) in selection.selected.iter().enumerate() {
420        let script_sig = sign_p2pkh_input(&tx, i, utxo.value as u64, &child);
421        tx.inputs[i].signature_script = script_sig;
422    }
423
424    let raw_hex = hex::encode(tx.serialize());
425    Ok(SendPreview {
426        raw_hex,
427        fee_sats: selection.fee_sats,
428        total_input_sats: selection.total_input_sats,
429        change_sats: selection.change_sats,
430        target_sats: amount_sats,
431    })
432}
433
434/// Broadcast a previously built transaction.
435pub fn confirm_send_xec(raw_hex: &str) -> Result<String, String> {
436    let client = crate::wallet::chronik::ChronikClient::new("https://chronik.be.cash");
437    let txid = client.broadcast_tx(raw_hex)?;
438
439    // Record in ledger
440    let state = crate::state::APP_STATE.get().unwrap();
441    let storage = state.config.lock().unwrap().storage_path.clone();
442    let _ = crate::wallet::ledger::append_entry(
443        std::path::Path::new(&storage),
444        &crate::wallet::ledger::new_entry(crate::wallet::ledger::LedgerEntryKind::TxBroadcast {
445            chain: "XEC".into(),
446            txid: txid.clone(),
447            amount_sats: 0, // Amount is in the raw tx; we don't parse it back here
448            direction: "out".into(),
449        }),
450    );
451
452    Ok(txid)
453}
454
455/// Decode an eCash address to its 20-byte pubkey hash.
456/// Supports both `ecash:q...` (CashAddr) and legacy base58 formats.
457fn decode_ecash_address(addr: &str) -> Result<Vec<u8>, String> {
458    // Strip ecash: prefix if present
459    let stripped = if let Some(a) = addr.strip_prefix("ecash:") {
460        a
461    } else {
462        addr
463    };
464    // Try base58 decode (legacy format)
465    let decoded = bs58::decode(stripped)
466        .into_vec()
467        .map_err(|e| format!("Invalid address: {}", e))?;
468    if decoded.len() < 21 {
469        return Err("Address too short".into());
470    }
471    // Skip version byte, take 20-byte hash
472    Ok(decoded[1..21].to_vec())
473}
474
475/// Load the stored mnemonic from the vault (identity file stores derivation result,
476/// the mnemonic itself is stored separately for security).
477fn load_mnemonic_from_vault() -> Result<String, String> {
478    let mnemonic_path = app_meta_dir().join("mnemonic.enc");
479    std::fs::read_to_string(&mnemonic_path).map_err(|_| {
480        "No mnemonic stored — please save your seed phrase via the identity setup flow".to_string()
481    })
482}
483
484/// Removes token.
485pub fn remove_token(id: String) -> Result<(), String> {
486    let state = crate::state::APP_STATE.get().unwrap();
487    let storage_path = state.config.lock().unwrap().storage_path.clone();
488    let mut tokens = load_tokens_from_disk(&storage_path);
489    tokens.retain(|t| t.id != id);
490    save_tokens_to_disk(&storage_path, &tokens)
491}
492
493// ─────────────────────────────────────────────────────────────────────────────
494
495/// Reads identity.
496pub fn read_identity() -> Option<serde_json::Value> {
497    std::fs::read_to_string(identity_file_path())
498        .ok()
499        .and_then(|s| serde_json::from_str(&s).ok())
500}
501
502#[derive(Serialize, Clone)]
503pub struct CoinBalance {
504    pub coin: String,
505    pub ticker: String,
506    pub address: String,
507    pub balance: f64,
508    pub balance_display: String,
509    pub fiat_usd: f64,
510    pub price_usd: f64,
511    pub change_24h: f64,
512    pub network: String,
513    pub status: String,
514}
515
516#[derive(Serialize, Clone)]
517pub struct TxRecord {
518    txid: String,
519    ticker: String,
520    direction: String, // "in" | "out"
521    amount: String,
522    label: String,
523    timestamp: String,
524    status: String, // "confirmed" | "pending"
525    confirmations: u32,
526    fee: String,
527    counterparty: String,
528}
529
530/// Gets coin-balances.
531pub fn get_coin_balances() -> Vec<CoinBalance> {
532    let id = read_identity();
533    let has_identity = id.is_some();
534    let addr = |key: &str| -> String {
535        id.as_ref()
536            .and_then(|v| v.get(key))
537            .and_then(|v| v.as_str())
538            .unwrap_or("")
539            .to_string()
540    };
541    let no_adapter_status: String = if has_identity {
542        "no_adapter".into()
543    } else {
544        "awaiting_identity".into()
545    };
546    let zero_display = if has_identity { "0" } else { "\u{2014}" };
547
548    let mut xec_balance = 0.0;
549    let mut xec_status = if has_identity {
550        "no_adapter".to_string()
551    } else {
552        "awaiting_identity".to_string()
553    };
554    let mut xec_display = zero_display.to_string();
555
556    if has_identity {
557        if let Some(hash160) = id
558            .as_ref()
559            .and_then(|v| v.get("ecash_hash160"))
560            .and_then(|v| v.as_str())
561        {
562            let client = crate::wallet::chronik::ChronikClient::new("https://chronik.be.cash");
563            if let Ok(utxos) = client.fetch_utxos_p2pkh(hash160) {
564                let mut sats = 0;
565                for utxo in utxos {
566                    if utxo.slp_meta.is_none() {
567                        sats += utxo.value;
568                    }
569                }
570                xec_balance = sats as f64 / 100.0; // XEC is 2 decimals (100 sats)
571                xec_display = format!("{:.2}", xec_balance);
572                xec_status = "synced".into();
573            } else {
574                xec_status = "offline".into();
575            }
576        }
577    }
578
579    let mut balances = vec![
580        CoinBalance {
581            coin: "eCash".into(),
582            ticker: "XEC".into(),
583            address: addr("ecash_xec"),
584            balance: xec_balance,
585            balance_display: xec_display,
586            fiat_usd: 0.0,
587            price_usd: 0.0,
588            change_24h: 0.0,
589            network: "eCash".into(),
590            status: xec_status,
591        },
592        CoinBalance {
593            coin: "Bitcoin".into(),
594            ticker: "BTC".into(),
595            address: addr("bitcoin_btc"),
596            balance: 0.0,
597            balance_display: zero_display.into(),
598            fiat_usd: 0.0,
599            price_usd: 0.0,
600            change_24h: 0.0,
601            network: "Bitcoin".into(),
602            status: no_adapter_status.clone(),
603        },
604        CoinBalance {
605            coin: "Monero".into(),
606            ticker: "XMR".into(),
607            // XMR derivation is not implemented (see derive_wallets_from_seed).
608            // Show an explicit non-address so it can't be mistaken for a real
609            // receive address — never a fabricated "4..." string.
610            address: "(not yet supported)".into(),
611            balance: 0.0,
612            balance_display: zero_display.into(),
613            fiat_usd: 0.0,
614            price_usd: 0.0,
615            change_24h: 0.0,
616            network: "Monero".into(),
617            status: no_adapter_status.clone(),
618        },
619        CoinBalance {
620            coin: "Ethereum".into(),
621            ticker: "ETH".into(),
622            address: addr("ethereum"),
623            balance: 0.0,
624            balance_display: zero_display.into(),
625            fiat_usd: 0.0,
626            price_usd: 0.0,
627            change_24h: 0.0,
628            network: "Ethereum".into(),
629            status: no_adapter_status.clone(),
630        },
631    ];
632
633    if nym_mixnet_opted_in() {
634        // Canonical key `nym`; never showcase fabricated n1… stubs.
635        let nym_claim = {
636            let a = addr("nym");
637            if a.starts_with("n1") {
638                String::new()
639            } else {
640                a
641            }
642        };
643        balances.push(CoinBalance {
644            coin: "Nym".into(),
645            ticker: "NYM".into(),
646            address: nym_claim,
647            balance: 0.0,
648            balance_display: zero_display.into(),
649            fiat_usd: 0.0,
650            price_usd: 0.0,
651            change_24h: 0.0,
652            network: "Nyx Chain".into(),
653            status: no_adapter_status,
654        });
655    }
656
657    balances
658}
659
660/// Gets transaction-history.
661pub fn get_transaction_history(ticker: String) -> Vec<TxRecord> {
662    // For XEC: query live transaction history from Chronik.
663    // For other chains: return empty (no adapter yet).
664    let id = read_identity();
665
666    let xec_history: Vec<TxRecord> = if ticker.is_empty() || ticker == "ALL" || ticker == "XEC" {
667        fetch_xec_tx_history(&id).unwrap_or_default()
668    } else {
669        Vec::new()
670    };
671
672    if ticker.is_empty() || ticker == "ALL" {
673        xec_history
674    } else {
675        xec_history
676            .into_iter()
677            .filter(|tx| tx.ticker == ticker)
678            .collect()
679    }
680}
681
682/// Fetch real XEC transaction history from Chronik.
683fn fetch_xec_tx_history(id: &Option<serde_json::Value>) -> Result<Vec<TxRecord>, String> {
684    let hash160 = id
685        .as_ref()
686        .and_then(|v| v.get("ecash_hash160"))
687        .and_then(|v| v.as_str())
688        .ok_or("No ecash_hash160 in identity")?;
689
690    let own_script_suffix = hash160.to_lowercase();
691
692    let client = crate::wallet::chronik::ChronikClient::new("https://chronik.be.cash");
693    let page = client.fetch_tx_history_p2pkh(hash160, 0, 25)?;
694
695    let mut records = Vec::new();
696    for tx in page.txs {
697        // Determine direction by checking if our address appears in inputs
698        let is_outgoing = tx.inputs.iter().any(|inp| {
699            inp.output_script
700                .to_lowercase()
701                .contains(&own_script_suffix)
702        });
703
704        // Calculate net amount
705        let own_output_sats: i64 = tx
706            .outputs
707            .iter()
708            .filter(|o| o.output_script.to_lowercase().contains(&own_script_suffix))
709            .map(|o| o.value)
710            .sum();
711
712        let own_input_sats: i64 = if is_outgoing {
713            tx.inputs
714                .iter()
715                .filter(|i| i.output_script.to_lowercase().contains(&own_script_suffix))
716                .map(|i| i.value)
717                .sum()
718        } else {
719            0
720        };
721
722        let (direction, amount_sats, label) = if is_outgoing {
723            let sent = own_input_sats - own_output_sats; // net outflow
724            ("out", sent, "Sent XEC")
725        } else {
726            ("in", own_output_sats, "Received XEC")
727        };
728
729        let xec_amount = amount_sats as f64 / 100.0;
730        let amount_str = format!("{:.2}", xec_amount);
731
732        // Determine confirmation status
733        let (status_str, confirmations) = match &tx.block {
734            Some(block) => {
735                // Rough confirmation count (we don't know current height, so show block height)
736                ("confirmed".to_string(), block.height as u32)
737            }
738            None => ("pending".to_string(), 0),
739        };
740
741        // Timestamp from block or first-seen
742        let timestamp = if let Some(ref block) = tx.block {
743            format_unix_timestamp(block.timestamp)
744        } else if tx.time_first_seen > 0 {
745            format_unix_timestamp(tx.time_first_seen)
746        } else {
747            "—".to_string()
748        };
749
750        // Counterparty: for outgoing, the first non-own output address; for incoming, first input
751        let counterparty = if is_outgoing {
752            tx.outputs
753                .iter()
754                .find(|o| {
755                    !o.output_script.to_lowercase().contains(&own_script_suffix) && o.value > 0
756                })
757                .map(|o| {
758                    format!(
759                        "script:{}",
760                        &o.output_script[..o.output_script.len().min(16)]
761                    )
762                })
763                .unwrap_or_else(|| "self".to_string())
764        } else {
765            tx.inputs
766                .first()
767                .map(|i| {
768                    format!(
769                        "script:{}",
770                        &i.output_script[..i.output_script.len().min(16)]
771                    )
772                })
773                .unwrap_or_else(|| "coinbase".to_string())
774        };
775
776        // Truncate txid for display
777        let txid_display = if tx.txid.len() > 16 {
778            format!("{}…{}", &tx.txid[..8], &tx.txid[tx.txid.len() - 4..])
779        } else {
780            tx.txid.clone()
781        };
782
783        records.push(TxRecord {
784            txid: txid_display,
785            ticker: "XEC".into(),
786            direction: direction.into(),
787            amount: amount_str,
788            label: label.into(),
789            timestamp,
790            status: status_str,
791            confirmations,
792            fee: "".into(), // Chronik doesn't return fee directly
793            counterparty,
794        });
795    }
796
797    Ok(records)
798}
799
800/// Format a Unix timestamp to a human-readable string.
801fn format_unix_timestamp(ts: i64) -> String {
802    let secs = ts as u64;
803    let days = secs / 86400;
804    let remaining = secs % 86400;
805    let hours = remaining / 3600;
806    let minutes = (remaining % 3600) / 60;
807    let (y, m, d) = crate::wallet::ledger::epoch_days_to_date_pub(days);
808    format!("{:04}-{:02}-{:02} {:02}:{:02}", y, m, d, hours, minutes)
809}
810
811/// `true` when first-run.
812pub fn is_first_run() -> bool {
813    !config_file_path().exists()
814}
815
816/// Saves identity.
817pub fn save_identity(wallets: serde_json::Value) -> Result<(), String> {
818    let meta = app_meta_dir();
819    std::fs::create_dir_all(&meta).map_err(|e| e.to_string())?;
820    let json = serde_json::to_string_pretty(&wallets).map_err(|e| e.to_string())?;
821    std::fs::write(identity_file_path(), json).map_err(|e| e.to_string())?;
822    Ok(())
823}
824
825/// Loads identity.
826pub fn load_identity() -> Result<Option<serde_json::Value>, String> {
827    let path = identity_file_path();
828    if !path.exists() {
829        return Ok(None);
830    }
831    let json = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
832    let val: serde_json::Value = serde_json::from_str(&json).map_err(|e| e.to_string())?;
833    Ok(Some(val))
834}
835
836use bip39::{Language, Mnemonic};
837
838/// Converts to hex.
839pub fn to_hex(bytes: &[u8]) -> String {
840    bytes.iter().map(|b| format!("{:02x}", b)).collect()
841}
842
843/// `generate-bip39` seed.
844pub async fn generate_bip39_seed() -> Result<String, String> {
845    // Generate a secure, randomized 12-word seed phrase natively
846    let mnemonic = Mnemonic::generate_in(Language::English, 12)
847        .map_err(|_| "Failed to generate".to_string())?;
848    let words: Vec<&str> = mnemonic.words().collect();
849    Ok(words.join(" "))
850}
851
852/// `derive-wallets-from` seed.
853pub async fn derive_wallets_from_seed(seed: String) -> Result<serde_json::Value, String> {
854    let mnemonic = match Mnemonic::parse_in(Language::English, &seed) {
855        Ok(m) => m,
856        Err(_) => return Err("Invalid 12-word seed phrase.".to_string()),
857    };
858
859    let seed_bytes = mnemonic.to_seed("");
860    let wallet = crate::wallet::HdWallet::from_seed(&seed_bytes)?;
861
862    let btc_addr = wallet.derive_address("BTC", "m/44'/0'/0'/0/0")?.address;
863    let eth_addr = wallet.derive_address("ETH", "m/44'/60'/0'/0/0")?.address;
864    let xec_payload = wallet.derive_address("XEC", "m/44'/899'/0'/0/0")?;
865    let xec_addr = xec_payload.address;
866    let xec_hash160 = xec_payload.pubkey_hash;
867
868    // Nym is deliberately NOT derived here. A fabricated "n1…" hex stub is not
869    // a real Nym locator (client id / sphinx / gateway bind). Canonical claim
870    // key is `nym` (never `nym_mixnet`). Planned until claim+bind.
871    //
872    // Monero is deliberately NOT derived here. It uses ed25519 (not the
873    // secp256k1 BIP32 path above), Keccak-256 key derivation, and its own
874    // base58 address format. Emitting a plausible-looking "4..." string with
875    // no keys behind it is dangerous: any XMR sent to a keyless address is
876    // permanently lost. So we report it empty rather than fabricate an
877    // address. Real, test-vector-verified ed25519/Keccak/base58 derivation is
878    // tracked as follow-up work (needs an authoritative seed→address vector to
879    // verify against before it can be trusted).
880    let hex_seed = to_hex(&seed_bytes[0..16]);
881
882    Ok(serde_json::json!({
883        "qualia_root": format!("did:qualia:0x{}", hex_seed),
884        "nym": "", // not derived — never fabricated n1… (see above)
885        "ecash_xec": xec_addr,
886        "ecash_hash160": xec_hash160,
887        "ethereum": eth_addr,
888        "bitcoin_btc": btc_addr,
889        "monero_xmr": "" // not derived — never a fabricated address (see above)
890    }))
891}
892
893/// Generates a front-door invite.
894pub async fn generate_front_door_invite() -> Result<String, String> {
895    let invite = crate::social_connect::generate_connect_invite(None)?;
896    Ok(invite.invite_json)
897}
898
899/// Mints a semantic token.
900pub async fn mint_semantic_token(asset_id: String) -> Result<String, String> {
901    use crate::wallet::coin_select;
902    use crate::wallet::signer::{hash160, sign_p2pkh_input};
903    use crate::wallet::transaction::{Transaction, TxIn, TxOut};
904    use bip32::XPrv;
905    use std::str::FromStr;
906
907    let id = read_identity().ok_or("No identity set — generate a seed first")?;
908    let hash160_hex = id
909        .get("ecash_hash160")
910        .and_then(|v| v.as_str())
911        .ok_or("No ecash_hash160 in identity")?;
912
913    let mnemonic_str = load_mnemonic_from_vault()?;
914    let mnemonic = bip39::Mnemonic::parse_in(bip39::Language::English, &mnemonic_str)
915        .map_err(|_| "Invalid stored mnemonic")?;
916    let seed_bytes = mnemonic.to_seed("");
917    let master = XPrv::new(&seed_bytes).map_err(|e| e.to_string())?;
918    let xec_path =
919        bip32::DerivationPath::from_str("m/44'/899'/0'/0/0").map_err(|e| e.to_string())?;
920    let mut child = master.clone();
921    for c in xec_path.iter() {
922        child = child.derive_child(c).map_err(|e| e.to_string())?;
923    }
924
925    // Parse asset_id as JSON metadata or use default
926    let metadata = crate::wallet::semantic_tokens::SemanticTokenMetadata {
927        token_ticker: asset_id.clone(),
928        token_name: format!("Qualia Semantic Token: {}", asset_id),
929        token_document_url: format!("https://qualia.io/tokens/{}", asset_id.to_lowercase()),
930        token_document_hash: format!("{:064x}", 0u128), // Placeholder hash
931        decimals: 0,
932    };
933
934    let client = crate::wallet::chronik::ChronikClient::new("https://chronik.be.cash");
935    let utxos = client.fetch_utxos_p2pkh(hash160_hex)?;
936
937    // Need enough XEC to cover: OP_RETURN (0) + mint output (546) + change + fee
938    let min_needed = coin_select::DUST_THRESHOLD_SATS + coin_select::BASE_FEE_SATS;
939    let selection = coin_select::select_utxos(&utxos, min_needed)?;
940
941    let mut tx = Transaction::new();
942    for utxo in &selection.selected {
943        tx.inputs.push(TxIn {
944            prev_txid: utxo.outpoint.txid.clone(),
945            prev_out_idx: utxo.outpoint.out_idx,
946            signature_script: Vec::new(),
947            sequence: 0xFFFFFFFF,
948        });
949    }
950
951    // Output 0: OP_RETURN GENESIS
952    let op_return = crate::wallet::semantic_tokens::generate_slp_op_return(&metadata);
953    tx.outputs.push(TxOut {
954        value: 0,
955        pk_script: op_return,
956    });
957
958    // Output 1: Mint receiver (self)
959    let own_pubkey_hash = hash160(&child.public_key().to_bytes());
960    let mut mint_script = vec![0x76, 0xa9, 0x14];
961    mint_script.extend_from_slice(&own_pubkey_hash);
962    mint_script.extend_from_slice(&[0x88, 0xac]);
963    tx.outputs.push(TxOut {
964        value: coin_select::DUST_THRESHOLD_SATS as u64,
965        pk_script: mint_script,
966    });
967
968    // Output 2: Change
969    if selection.change_sats > 0 {
970        let mut change_script = vec![0x76, 0xa9, 0x14];
971        change_script.extend_from_slice(&own_pubkey_hash);
972        change_script.extend_from_slice(&[0x88, 0xac]);
973        tx.outputs.push(TxOut {
974            value: selection.change_sats as u64,
975            pk_script: change_script,
976        });
977    }
978
979    // Sign
980    for (i, utxo) in selection.selected.iter().enumerate() {
981        let script_sig = sign_p2pkh_input(&tx, i, utxo.value as u64, &child);
982        tx.inputs[i].signature_script = script_sig;
983    }
984
985    // Broadcast
986    let raw_hex = hex::encode(tx.serialize());
987    let txid = client.broadcast_tx(&raw_hex)?;
988
989    // Record in ledger
990    let state = crate::state::APP_STATE.get().unwrap();
991    let storage = state.config.lock().unwrap().storage_path.clone();
992    let _ = crate::wallet::ledger::append_entry(
993        std::path::Path::new(&storage),
994        &crate::wallet::ledger::new_entry(crate::wallet::ledger::LedgerEntryKind::TokenMint {
995            chain: "XEC".into(),
996            txid: txid.clone(),
997            token_id: txid.clone(), // For SLP, the token_id IS the genesis txid
998            symbol: asset_id,
999        }),
1000    );
1001
1002    Ok(txid)
1003}
1004
1005/// Fetches wallet-portfolio.
1006pub async fn fetch_wallet_portfolio() -> Result<serde_json::Value, String> {
1007    // Compose real portfolio from live coin balances + token registry
1008    let balances = get_coin_balances();
1009    let tokens = get_tokens();
1010
1011    let mut portfolio = Vec::new();
1012
1013    // Add native coin entries
1014    for b in &balances {
1015        portfolio.push(serde_json::json!({
1016            "name": b.coin,
1017            "tokenId": "",
1018            "ticker": b.ticker,
1019            "balance": b.balance_display,
1020            "rdf": "",
1021            "network": b.network,
1022            "type": "native",
1023            "status": b.status,
1024            "address": b.address,
1025            "fiat_usd": b.fiat_usd,
1026        }));
1027    }
1028
1029    // Add token entries
1030    for t in &tokens {
1031        portfolio.push(serde_json::json!({
1032            "name": t.name,
1033            "tokenId": t.contract,
1034            "ticker": t.symbol,
1035            "balance": t.balance,
1036            "rdf": "",
1037            "network": t.chain,
1038            "type": t.token_type,
1039            "status": "loaded",
1040        }));
1041    }
1042
1043    Ok(serde_json::Value::Array(portfolio))
1044}
1045
1046/// `import-external` seed.
1047pub async fn import_external_seed(
1048    network: String,
1049    seed: String,
1050    _label: String,
1051) -> Result<String, String> {
1052    // Validate seed format
1053    if seed.split_whitespace().count() < 12 {
1054        return Err("Invalid seed phrase — must be at least 12 words".to_string());
1055    }
1056
1057    // Derive real addresses using the existing HD wallet pipeline
1058    let mnemonic = bip39::Mnemonic::parse_in(bip39::Language::English, &seed)
1059        .map_err(|_| "Invalid BIP-39 mnemonic".to_string())?;
1060    let seed_bytes = mnemonic.to_seed("");
1061    let wallet = crate::wallet::HdWallet::from_seed(&seed_bytes)?;
1062
1063    let (net_code, path) = match network.as_str() {
1064        "eCash (XEC)" | "XEC" => ("XEC", "m/44'/899'/0'/0/0"),
1065        "Bitcoin (BTC)" | "BTC" => ("BTC", "m/44'/0'/0'/0/0"),
1066        "Nym (NYM) - Nyx Chain" | "NYM" => {
1067            return Err(
1068                "Nym locator not derived — Planned until real claim+bind (no fabricated n1…)"
1069                    .into(),
1070            );
1071        }
1072        "Ethereum (EVM)" | "ETH" => ("ETH", "m/44'/60'/0'/0/0"),
1073        "Monero (XMR)" | "XMR" => {
1074            // Monero uses ed25519, not secp256k1 — still mock for now
1075            let xmr_hex = to_hex(&seed_bytes[48..56]);
1076            return Ok(format!("4{}...", &xmr_hex[0..xmr_hex.len().min(16)]));
1077        }
1078        _ => return Err(format!("Unsupported network: {}", network)),
1079    };
1080
1081    let payload = wallet.derive_address(net_code, path)?;
1082    Ok(payload.address)
1083}
1084
1085/// Toggles nym-relay.
1086pub async fn toggle_nym_relay() -> Result<bool, String> {
1087    #[cfg(not(target_arch = "wasm32"))]
1088    {
1089        return crate::nym_live::toggle_nym_relay().await;
1090    }
1091    #[cfg(target_arch = "wasm32")]
1092    {
1093        Err("Nym client is native-only — no mock relay".into())
1094    }
1095}
1096
1097/// Enables the Nym relay.
1098pub async fn enable_nym_relay(network: Option<String>) -> Result<serde_json::Value, String> {
1099    #[cfg(not(target_arch = "wasm32"))]
1100    {
1101        let st = crate::nym_live::enable_nym(network).await?;
1102        return Ok(serde_json::to_value(st).unwrap_or_default());
1103    }
1104    #[cfg(target_arch = "wasm32")]
1105    {
1106        let _ = network;
1107        Err("Nym client is native-only — no mock relay".into())
1108    }
1109}
1110
1111/// Disables the Nym relay.
1112pub async fn disable_nym_relay() -> Result<serde_json::Value, String> {
1113    #[cfg(not(target_arch = "wasm32"))]
1114    {
1115        let st = crate::nym_live::disable_nym().await?;
1116        return Ok(serde_json::to_value(st).unwrap_or_default());
1117    }
1118    #[cfg(target_arch = "wasm32")]
1119    {
1120        Err("Nym client is native-only — no mock relay".into())
1121    }
1122}
1123
1124/// `nym-live-status` as JSON.
1125pub fn nym_live_status_json() -> serde_json::Value {
1126    #[cfg(not(target_arch = "wasm32"))]
1127    {
1128        return serde_json::to_value(crate::nym_live::nym_live_status()).unwrap_or_default();
1129    }
1130    #[cfg(target_arch = "wasm32")]
1131    {
1132        serde_json::json!({
1133            "live": false,
1134            "enabled_wanted": false,
1135            "address": "",
1136            "network": "",
1137            "error": "native-only",
1138            "client": "none"
1139        })
1140    }
1141}
1142
1143/// Agent-facing keyRole request — purpose grant only, never seed material.
1144pub fn agent_request_key_role(role: String) -> Result<serde_json::Value, String> {
1145    #[cfg(not(target_arch = "wasm32"))]
1146    {
1147        let grant = crate::nym_live::agent_request_key_role(&role)?;
1148        return serde_json::to_value(grant).map_err(|e| e.to_string());
1149    }
1150    #[cfg(target_arch = "wasm32")]
1151    {
1152        let _ = role;
1153        Err("keyRole request is native-only".into())
1154    }
1155}
1156
1157/// Agent-facing mixnet keyRole request (≠ session-authentication).
1158pub fn agent_request_mixnet_key_role() -> Result<serde_json::Value, String> {
1159    agent_request_key_role("mixnet".into())
1160}
1161
1162/// Toggles stark-prover.
1163pub async fn toggle_stark_prover() -> Result<bool, String> {
1164    let state = crate::state::APP_STATE.get().unwrap();
1165    let active = &state.stark_prover_active;
1166    let currently_active = active.load(Ordering::Relaxed);
1167    let new_state = !currently_active;
1168    active.store(new_state, Ordering::Relaxed);
1169
1170    if new_state {
1171        let active_clone = active.clone();
1172        let solar_clone = state.simulated_solar_watts.clone();
1173
1174        // Spawn asynchronous background daemon for out-of-core proof chunking
1175        tokio::spawn(async move {
1176            let mut _fragments_paged = 0;
1177
1178            while active_clone.load(Ordering::Relaxed) {
1179                let current_solar = solar_clone.load(Ordering::Relaxed);
1180
1181                // Environmental state evaluation trigger (threshold at 400W)
1182                if current_solar < 400 {
1183                    // let _ = window_clone.emit("stark-telemetry", StarkTelemetry {
1184                    //     status: "Suspended - Awaiting Solar Surplus".to_string(),
1185                    //     cpu_utilization: 0.0,
1186                    //     ram_usage_mb: 0.0,
1187                    //     fragments_paged,
1188                    // });
1189                } else {
1190                    _fragments_paged += 8; // Simulate 48-byte Super-Quin paging writes
1191
1192                    // let _ = window_clone.emit("stark-telemetry", StarkTelemetry {
1193                    //     status: "Proving Execution Active".to_string(),
1194                    //     cpu_utilization: 85.4,
1195                    //     ram_usage_mb: 320.0, // Constrained flat memory footprint
1196                    //     fragments_paged,
1197                    // });
1198                }
1199                sleep(Duration::from_millis(1000)).await;
1200            }
1201        });
1202    }
1203    Ok(new_state)
1204}
1205
1206/// Updates solar input.
1207pub fn update_solar_input(watts: u32) {
1208    let state = crate::state::APP_STATE.get().unwrap();
1209    state.simulated_solar_watts.store(watts, Ordering::Relaxed);
1210}
1211
1212/// Fetches torrent-telemetry.
1213pub async fn fetch_torrent_telemetry() -> Result<serde_json::Value, String> {
1214    let state = crate::state::APP_STATE.get().unwrap();
1215    let storage = state.config.lock().unwrap().storage_path.clone();
1216    Ok(crate::ontology_workbench::torrent_telemetry(Path::new(
1217        &storage,
1218    )))
1219}
1220
1221/// Syncs workbench torrent seeds.
1222pub fn sync_workbench_torrent_seeds(storage_path: &str) -> Result<serde_json::Value, String> {
1223    crate::ontology_workbench::sync_workbench_seeds_to_daemon(Path::new(storage_path))
1224}
1225
1226/// `workbench-import-ontology` URI.
1227pub async fn workbench_import_ontology_uri(
1228    uri: String,
1229    ontology_id: Option<String>,
1230    domain: Option<String>,
1231    title: Option<String>,
1232) -> Result<serde_json::Value, String> {
1233    let state = crate::state::APP_STATE.get().unwrap();
1234    let storage = state.config.lock().unwrap().storage_path.clone();
1235    let result = crate::ontology_workbench::import_from_uri(
1236        Path::new(&storage),
1237        uri,
1238        ontology_id,
1239        domain,
1240        title,
1241    )
1242    .await?;
1243    serde_json::to_value(result).map_err(|e| e.to_string())
1244}
1245
1246/// Lists workbench ontologies.
1247pub fn list_workbench_ontologies() -> Result<serde_json::Value, String> {
1248    let state = crate::state::APP_STATE.get().unwrap();
1249    let storage = state.config.lock().unwrap().storage_path.clone();
1250    let entries = crate::ontology_workbench::list_workbench_entries(Path::new(&storage))?;
1251    serde_json::to_value(entries).map_err(|e| e.to_string())
1252}
1253
1254/// Sets workbench-torrent-policy.
1255pub fn set_workbench_torrent_policy(
1256    ontology_id: String,
1257    policy_json: serde_json::Value,
1258) -> Result<serde_json::Value, String> {
1259    let state = crate::state::APP_STATE.get().unwrap();
1260    let storage = state.config.lock().unwrap().storage_path.clone();
1261    let policy: crate::ontology_workbench::OntologyTorrentPolicy =
1262        serde_json::from_value(policy_json).map_err(|e| e.to_string())?;
1263    let updated =
1264        crate::ontology_workbench::set_torrent_policy(Path::new(&storage), &ontology_id, policy)?;
1265    serde_json::to_value(updated).map_err(|e| e.to_string())
1266}
1267
1268/// Sets workbench-seed.
1269pub fn set_workbench_seed(ontology_id: String, active: bool) -> Result<serde_json::Value, String> {
1270    let state = crate::state::APP_STATE.get().unwrap();
1271    let storage = state.config.lock().unwrap().storage_path.clone();
1272    let updated =
1273        crate::ontology_workbench::set_seed_active(Path::new(&storage), &ontology_id, active)?;
1274    serde_json::to_value(updated).map_err(|e| e.to_string())
1275}
1276
1277/// Gets torrent-bandwidth-policy.
1278pub fn get_torrent_bandwidth_policy() -> Result<serde_json::Value, String> {
1279    let policy = crate::ontology_workbench::load_bandwidth_policy();
1280    serde_json::to_value(policy).map_err(|e| e.to_string())
1281}
1282
1283/// Sets torrent-bandwidth-policy.
1284pub fn set_torrent_bandwidth_policy(
1285    policy_json: serde_json::Value,
1286) -> Result<serde_json::Value, String> {
1287    let policy: crate::ontology_workbench::TorrentBandwidthGlobal =
1288        serde_json::from_value(policy_json).map_err(|e| e.to_string())?;
1289    crate::ontology_workbench::save_bandwidth_policy(&policy)?;
1290    serde_json::to_value(policy).map_err(|e| e.to_string())
1291}
1292
1293/// Lists ontology shares for a contact.
1294pub fn list_ontology_shares_for_contact(contact_did: String) -> Result<serde_json::Value, String> {
1295    let state = crate::state::APP_STATE.get().unwrap();
1296    let storage = state.config.lock().unwrap().storage_path.clone();
1297    let cards =
1298        crate::ontology_workbench::list_share_cards_for_contact(Path::new(&storage), &contact_did)?;
1299    serde_json::to_value(cards).map_err(|e| e.to_string())
1300}
1301
1302/// Lists ontology shares for a session.
1303pub fn list_ontology_shares_for_session(session_did: String) -> Result<serde_json::Value, String> {
1304    let state = crate::state::APP_STATE.get().unwrap();
1305    let storage = state.config.lock().unwrap().storage_path.clone();
1306    let cards =
1307        crate::ontology_workbench::list_share_cards_for_session(Path::new(&storage), &session_did)?;
1308    serde_json::to_value(cards).map_err(|e| e.to_string())
1309}
1310
1311/// Lists chat-session share targets.
1312pub fn list_chat_session_share_targets() -> Result<serde_json::Value, String> {
1313    let state = crate::state::APP_STATE.get().unwrap();
1314    let storage = state.config.lock().unwrap().storage_path.clone();
1315    let targets = crate::chat_session::list_session_share_targets(Path::new(&storage))
1316        .map_err(|e| e.to_string())?;
1317    serde_json::to_value(targets).map_err(|e| e.to_string())
1318}
1319
1320/// Gets chat-session-did.
1321pub fn get_chat_session_did(session_id: String) -> Result<String, String> {
1322    let state = crate::state::APP_STATE.get().unwrap();
1323    let storage = state.config.lock().unwrap().storage_path.clone();
1324    crate::chat_session::get_session_did(Path::new(&storage), &session_id)
1325        .map_err(|e| e.to_string())
1326}
1327
1328/// Updates chat contact categories.
1329pub fn update_chat_contact_categories(
1330    contact_did: String,
1331    categories: Vec<String>,
1332) -> Result<serde_json::Value, String> {
1333    let contact = crate::social_connect::update_contact_categories(&contact_did, categories)?;
1334    serde_json::to_value(contact).map_err(|e| e.to_string())
1335}
1336
1337/// Discovers models.
1338pub async fn discover_models() -> Result<Vec<llm_offload::ModelInfo>, String> {
1339    use std::collections::HashSet;
1340
1341    let state = crate::state::APP_STATE.get().unwrap();
1342    let storage_path = state.config.lock().unwrap().storage_path.clone();
1343    let search_paths = state.config.lock().unwrap().model_search_paths.clone();
1344    let models_dir = PathBuf::from(&storage_path).join("Models");
1345    let active_path = load_active_model_from_disk();
1346    let mut models = Vec::new();
1347    let mut seen: HashSet<String> = HashSet::new();
1348
1349    let mut push_model = |path: &Path| {
1350        if !path.is_file() {
1351            return;
1352        }
1353        let name = path
1354            .file_name()
1355            .map(|n| n.to_string_lossy().to_string())
1356            .unwrap_or_default();
1357        let ext = path
1358            .extension()
1359            .and_then(|e| e.to_str())
1360            .unwrap_or("")
1361            .to_ascii_lowercase();
1362        if (ext != "gguf" && ext != "p64") || name.to_ascii_lowercase().contains("mmproj") {
1363            return;
1364        }
1365        // Prefer converted p64 when listing a GGUF that has a sibling container.
1366        let effective: PathBuf = if ext == "gguf" {
1367            let p64 = path.with_extension("p64");
1368            if p64.is_file() {
1369                p64
1370            } else {
1371                path.to_path_buf()
1372            }
1373        } else {
1374            path.to_path_buf()
1375        };
1376        let name = effective
1377            .file_name()
1378            .map(|n| n.to_string_lossy().to_string())
1379            .unwrap_or(name);
1380        let key = effective.to_string_lossy().to_ascii_lowercase();
1381        if !seen.insert(key) {
1382            return;
1383        }
1384        let display_name = if effective.starts_with(&models_dir) {
1385            name
1386        } else {
1387            effective.to_string_lossy().into_owned()
1388        };
1389        let is_active = active_path
1390            .as_ref()
1391            .map(|active| paths_refer_to_same_file(active, &effective))
1392            .unwrap_or(false);
1393        models.push(llm_offload::ModelInfo {
1394            name: display_name,
1395            is_active,
1396            avatar_type: if effective.starts_with(&models_dir) {
1397                "installed".to_string()
1398            } else {
1399                "local".to_string()
1400            },
1401        });
1402    };
1403
1404    if let Ok(entries) = std::fs::read_dir(&models_dir) {
1405        for entry in entries.filter_map(Result::ok) {
1406            let path = entry.path();
1407            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
1408            if ext == "gguf" || ext == "p64" {
1409                push_model(&path);
1410            } else if ext == "json"
1411                && path
1412                    .file_name()
1413                    .and_then(|n| n.to_str())
1414                    .map(|n| n.ends_with(".install.json"))
1415                    .unwrap_or(false)
1416            {
1417                if let Ok(text) = std::fs::read_to_string(&path) {
1418                    if let Ok(manifest) =
1419                        serde_json::from_str::<crate::model_lifecycle::InstallManifest>(&text)
1420                    {
1421                        push_model(Path::new(&manifest.gguf_path));
1422                    }
1423                }
1424            }
1425        }
1426    }
1427
1428    for root in &search_paths {
1429        let root_path = Path::new(root);
1430        if root_path.is_dir() {
1431            if let Ok(entries) = crate::model_lifecycle::scan_vault_gguf(root_path) {
1432                for entry in entries {
1433                    push_model(Path::new(&entry.path));
1434                }
1435            }
1436        }
1437    }
1438
1439    if let Some(active) = active_path.as_ref() {
1440        push_model(Path::new(active));
1441    }
1442
1443    models.sort_by(|a, b| {
1444        a.name
1445            .to_ascii_lowercase()
1446            .cmp(&b.name.to_ascii_lowercase())
1447    });
1448    Ok(models)
1449}
1450
1451fn paths_refer_to_same_file(left: &str, right: &Path) -> bool {
1452    let left_path = Path::new(left);
1453    if left_path == right {
1454        return true;
1455    }
1456    left_path
1457        .file_name()
1458        .is_some_and(|left_name| right.file_name() == Some(left_name))
1459        && left.replace('\\', "/").to_ascii_lowercase()
1460            == right
1461                .to_string_lossy()
1462                .replace('\\', "/")
1463                .to_ascii_lowercase()
1464}
1465
1466/// Runs agent inference.
1467pub async fn run_agent_inference(
1468    prompt: String,
1469    model_name: String,
1470    intent_layout: Vec<f64>,
1471) -> Result<(), String> {
1472    tokio::spawn(async move {
1473        let _ = llm_offload::execute_agent_inference(prompt, model_name, intent_layout).await;
1474    });
1475    Ok(())
1476}