stellar-data 0.1.5

A command line tool and REST API for querying the Stellar blockchain using public data lakes and RPC nodes, providing JSON formatted responses to simplify data availability
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
use anyhow::{Context, Result};
use stellar_xdr::curr::{LedgerCloseMeta, LedgerCloseMetaBatch, Limits, ReadXdr, WriteXdr};
use stellar_strkey::Strkey;
use crate::config::Config;

/// Reflector oracle contract addresses
const REFLECTOR_STELLAR_CONTRACT: &str = "CALI2BYU2JE6WVRUFYTS6MSBNEHGJ35P4AVCZYF3B6QOE3QKOB2PLE6M";
const REFLECTOR_CRYPTO_CONTRACT: &str = "CAFJZQWSED6YAWZU3GWRTOCNPPCGBN32L7QV43XX5LZLFTK6JLN34DLN";
const REFLECTOR_FIAT_CONTRACT: &str = "CBKGPWGKSKZF52CFHMTRR23TBWTPMRDIYZ4O2P5VS65BMHYH4DXMCJZC";
const REFLECTOR_DECIMALS: u32 = 14;

/// Crypto assets that use the crypto oracle
const CRYPTO_ASSETS: &[&str] = &[
    "BTC", "ETH", "USDT", "XRP", "SOL", "USDC", "ADA", "AVAX", "DOT",
    "MATIC", "LINK", "DAI", "ATOM", "XLM", "UNI", "EURC"
];

/// Fiat assets that use the fiat oracle
const FIAT_ASSETS: &[&str] = &[
    "EUR", "GBP", "CAD", "BRL", "JPY", "CNY", "MXN", "KRW", "TRY", "ARS",
    "PEN", "VES", "CLP", "CRC", "CDF", "COP", "HKD", "INR", "NGN", "PHP",
    "RUB", "ZAR", "XAU"
];

/// Determine which Reflector oracle to use based on the asset
fn get_oracle_for_asset(asset: &str) -> &'static str {
    let asset_upper = asset.to_uppercase();

    if CRYPTO_ASSETS.contains(&asset_upper.as_str()) {
        REFLECTOR_CRYPTO_CONTRACT
    } else if FIAT_ASSETS.contains(&asset_upper.as_str()) {
        REFLECTOR_FIAT_CONTRACT
    } else {
        // Default to Stellar contract for contract addresses and other assets
        REFLECTOR_STELLAR_CONTRACT
    }
}

/// RPC response structures (currently unused, kept for reference)
#[allow(dead_code)]
#[derive(serde::Deserialize)]
struct RpcLedgerResponse {
    ledgers: Vec<RpcLedger>,
}

#[allow(dead_code)]
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct RpcLedger {
    sequence: u32,
    metadata_xdr: String,
}

/// Fetch ledger data from RPC when S3 doesn't have it yet
pub fn fetch_from_rpc(ledger_seq: u32, _silent: bool) -> Result<Vec<u8>> {
    let client = reqwest::blocking::Client::new();
    let rpc_request = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "getLedgers",
        "params": {
            "startLedger": ledger_seq,
            "pagination": {
                "limit": 1
            }
        }
    });

    let response = client
        .post(Config::rpc_url())
        .json(&rpc_request)
        .send()
        .context("Failed to call RPC")?;

    if !response.status().is_success() {
        anyhow::bail!("RPC returned error status: {}", response.status());
    }

    let json: serde_json::Value = response.json()
        .context("Failed to parse RPC response")?;

    if let Some(error) = json.get("error") {
        anyhow::bail!("RPC error: {}", error);
    }

    let result = json.get("result")
        .ok_or_else(|| anyhow::anyhow!("No result in RPC response"))?;

    let ledgers = result.get("ledgers")
        .and_then(|l| l.as_array())
        .ok_or_else(|| anyhow::anyhow!("No ledgers in RPC response"))?;

    if ledgers.is_empty() {
        anyhow::bail!("Ledger {} not found in RPC", ledger_seq);
    }

    let ledger = &ledgers[0];
    let metadata_xdr = ledger.get("metadataXdr")
        .and_then(|m| m.as_str())
        .ok_or_else(|| anyhow::anyhow!("No metadataXdr in RPC response"))?;

    // Decode base64 to get the XDR bytes for LedgerCloseMeta
    let ledger_close_meta = LedgerCloseMeta::from_xdr_base64(metadata_xdr, Limits::none())
        .context("Failed to decode metadataXdr from RPC")?;

    // Wrap it in a LedgerCloseMetaBatch (single ledger batch)
    let batch = LedgerCloseMetaBatch {
        start_sequence: ledger_seq,
        end_sequence: ledger_seq,
        ledger_close_metas: vec![ledger_close_meta].try_into()
            .map_err(|_| anyhow::anyhow!("Failed to create VecM"))?,
    };

    // Serialize the batch to XDR bytes so it matches the S3 format
    let xdr_bytes = batch.to_xdr(Limits::none())
        .context("Failed to serialize batch to XDR")?;

    Ok(xdr_bytes)
}

/// Query token balance for an address using Soroban RPC
///
/// This uses the simulateTransaction RPC method with a minimal transaction envelope
/// that calls the "balance" function on the token contract.
pub fn query_balance(address: &str, token_contract: &str) -> Result<serde_json::Value> {
    use stellar_xdr::curr::*;

    let client = reqwest::blocking::Client::new();

    // Decode the Stellar address to get the account ID bytes
    let address_bytes = match Strkey::from_string(address) {
        Ok(Strkey::PublicKeyEd25519(pk)) => pk.0,
        _ => anyhow::bail!("Invalid Stellar address format"),
    };

    // Decode the contract address
    let contract_bytes = match Strkey::from_string(token_contract) {
        Ok(Strkey::Contract(contract)) => contract.0,
        _ => anyhow::bail!("Invalid contract address format"),
    };

    // Create the ScVal for the address parameter (Address type with Account variant)
    let address_scval = ScVal::Address(ScAddress::Account(
        AccountId(PublicKey::PublicKeyTypeEd25519(
            Uint256(address_bytes),
        )),
    ));

    // Create function name as ScSymbol
    let function_name = ScSymbol("balance".as_bytes().to_vec().try_into()
        .map_err(|_| anyhow::anyhow!("Function name too long"))?);

    // Create contract address
    use stellar_xdr::curr::ContractId;
    let contract_address = ScAddress::Contract(
        ContractId(Hash(contract_bytes)),
    );

    // Build InvokeContractArgs
    let invoke_args = InvokeContractArgs {
        contract_address,
        function_name,
        args: vec![address_scval].try_into()
            .map_err(|_| anyhow::anyhow!("Failed to create args vec"))?,
    };

    // Build HostFunction::InvokeContract
    let host_function = HostFunction::InvokeContract(invoke_args);

    // Build InvokeHostFunctionOp
    let invoke_op = InvokeHostFunctionOp {
        host_function,
        auth: vec![].try_into()
            .map_err(|_| anyhow::anyhow!("Failed to create auth vec"))?,
    };

    // Build Operation
    let operation = Operation {
        source_account: None,
        body: OperationBody::InvokeHostFunction(invoke_op),
    };

    // Build a minimal transaction envelope
    // Use a dummy source account
    let source_account = MuxedAccount::Ed25519(Uint256([0u8; 32]));

    let tx = Transaction {
        source_account,
        fee: 100,
        seq_num: SequenceNumber(0),
        cond: Preconditions::None,
        memo: Memo::None,
        operations: vec![operation].try_into()
            .map_err(|_| anyhow::anyhow!("Failed to create operations vec"))?,
        ext: TransactionExt::V0,
    };

    let tx_envelope = TransactionEnvelope::Tx(TransactionV1Envelope {
        tx,
        signatures: vec![].try_into()
            .map_err(|_| anyhow::anyhow!("Failed to create signatures vec"))?,
    });

    // Encode transaction to base64 XDR
    let tx_xdr = tx_envelope.to_xdr_base64(Limits::none())
        .context("Failed to encode transaction to XDR")?;

    // Make the simulateTransaction RPC call
    let rpc_request = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "simulateTransaction",
        "params": {
            "transaction": tx_xdr
        }
    });

    let response = client
        .post(Config::soroban_rpc_url())
        .json(&rpc_request)
        .send()
        .context("Failed to call RPC for balance query")?;

    if !response.status().is_success() {
        anyhow::bail!("RPC returned error status: {}", response.status());
    }

    let json: serde_json::Value = response.json()
        .context("Failed to parse RPC response")?;

    if let Some(error) = json.get("error") {
        anyhow::bail!("RPC error: {}", error);
    }

    let result = json.get("result")
        .ok_or_else(|| anyhow::anyhow!("No result in RPC response"))?;

    // Try to extract and decode the balance from the result XDR
    // The result is in result.results[0].xdr
    if let Some(result_xdr) = result.get("results")
        .and_then(|r| r.get(0))
        .and_then(|r| r.get("xdr"))
        .and_then(|x| x.as_str())
    {
        match ScVal::from_xdr_base64(result_xdr, Limits::none()) {
            Ok(ScVal::I128(parts)) => {
                // Convert i128 parts to get raw balance in stroops
                let raw_balance = i128::from(parts.hi) << 64 | i128::from(parts.lo as u64);
                // Convert to human-readable format (7 decimals for Stellar tokens)
                let balance = raw_balance as f64 / 10_f64.powi(7);
                return Ok(serde_json::json!({
                    "address": address,
                    "token": token_contract,
                    "balance": balance,
                    "raw_balance": raw_balance.to_string()
                }));
            }
            Ok(ScVal::U128(parts)) => {
                // Convert u128 parts to get raw balance in stroops
                let raw_balance = u128::from(parts.hi) << 64 | u128::from(parts.lo);
                // Convert to human-readable format (7 decimals for Stellar tokens)
                let balance = raw_balance as f64 / 10_f64.powi(7);
                return Ok(serde_json::json!({
                    "address": address,
                    "token": token_contract,
                    "balance": balance,
                    "raw_balance": raw_balance.to_string()
                }));
            }
            Ok(val) => {
                // Return the ScVal as-is if it's not a number
                return Ok(serde_json::json!({
                    "address": address,
                    "token": token_contract,
                    "result": format!("{:?}", val)
                }));
            }
            Err(e) => {
                return Ok(serde_json::json!({
                    "address": address,
                    "token": token_contract,
                    "error": format!("Failed to decode result: {}", e),
                    "raw_xdr": result_xdr
                }));
            }
        }
    }

    // If we can't extract the XDR, return the full result
    Ok(serde_json::json!({
        "address": address,
        "token": token_contract,
        "result": result
    }))
}

/// Query price data from Reflector oracle
///
/// This uses the simulateTransaction RPC method to call the "lastprice" function
/// on the Reflector oracle contract. The asset can be:
/// - External asset symbol (e.g., "btc", "eth", "xlm") -> uses ReflectorAsset::Other variant with appropriate oracle
/// - Stellar contract address (starts with 'C') -> uses ReflectorAsset::Stellar variant with Stellar DEX oracle
pub fn query_price(asset_input: &str) -> Result<serde_json::Value> {
    use stellar_xdr::curr::*;

    let client = reqwest::blocking::Client::new();

    // Determine if this is a Stellar asset (contract address) or external asset (symbol)
    // And which oracle to use
    let (asset_type, asset_value, reflector_contract) = if asset_input.starts_with('C') && asset_input.len() == 56 {
        // It's a Stellar contract address - use Stellar DEX oracle
        ("Stellar", asset_input, REFLECTOR_STELLAR_CONTRACT)
    } else {
        // It's an asset symbol (including token shortcuts like xlm, usdc, btc, eth, etc.)
        // Treat all symbols as external assets and determine oracle based on asset type
        let oracle = get_oracle_for_asset(asset_input);
        ("Other", asset_input, oracle)
    };

    // Build the ReflectorAsset ScVal
    // ReflectorAsset is an enum with two variants:
    // - Stellar(Address): for Stellar tokens
    // - Other(Symbol): for external assets
    //
    // In Soroban XDR, enums with data are encoded as Vec where:
    // - First element: variant name as Symbol
    // - Remaining elements: the variant's associated data
    let asset_scval = if asset_type == "Stellar" {
        // Decode the contract address
        let contract_bytes = match Strkey::from_string(asset_value) {
            Ok(Strkey::Contract(contract)) => contract.0,
            _ => anyhow::bail!("Invalid contract address format: {}", asset_value),
        };

        // Create Stellar variant: Vec[Symbol("Stellar"), Address(Contract)]
        ScVal::Vec(Some(
            vec![
                ScVal::Symbol(ScSymbol("Stellar".as_bytes().to_vec().try_into()
                    .map_err(|_| anyhow::anyhow!("Variant name too long"))?)),
                ScVal::Address(ScAddress::Contract(
                    ContractId(Hash(contract_bytes)),
                )),
            ]
            .try_into()
            .map_err(|_| anyhow::anyhow!("Failed to create vec"))?,
        ))
    } else {
        // Create Other variant: Vec[Symbol("Other"), Symbol(asset)]
        ScVal::Vec(Some(
            vec![
                ScVal::Symbol(ScSymbol("Other".as_bytes().to_vec().try_into()
                    .map_err(|_| anyhow::anyhow!("Variant name too long"))?)),
                ScVal::Symbol(ScSymbol(asset_value.to_uppercase().as_bytes().to_vec().try_into()
                    .map_err(|_| anyhow::anyhow!("Asset symbol too long"))?)),
            ]
            .try_into()
            .map_err(|_| anyhow::anyhow!("Failed to create vec"))?,
        ))
    };

    // Decode the Reflector contract address
    let reflector_contract_bytes = match Strkey::from_string(reflector_contract) {
        Ok(Strkey::Contract(contract)) => contract.0,
        _ => anyhow::bail!("Invalid Reflector contract address"),
    };

    // Create function name as ScSymbol
    let function_name = ScSymbol("lastprice".as_bytes().to_vec().try_into()
        .map_err(|_| anyhow::anyhow!("Function name too long"))?);

    // Create contract address
    let contract_address = ScAddress::Contract(
        ContractId(Hash(reflector_contract_bytes)),
    );

    // Build InvokeContractArgs
    let invoke_args = InvokeContractArgs {
        contract_address,
        function_name,
        args: vec![asset_scval].try_into()
            .map_err(|_| anyhow::anyhow!("Failed to create args vec"))?,
    };

    // Build HostFunction::InvokeContract
    let host_function = HostFunction::InvokeContract(invoke_args);

    // Build InvokeHostFunctionOp
    let invoke_op = InvokeHostFunctionOp {
        host_function,
        auth: vec![].try_into()
            .map_err(|_| anyhow::anyhow!("Failed to create auth vec"))?,
    };

    // Build Operation
    let operation = Operation {
        source_account: None,
        body: OperationBody::InvokeHostFunction(invoke_op),
    };

    // Build a minimal transaction envelope
    // Use a dummy source account
    let source_account = MuxedAccount::Ed25519(Uint256([0u8; 32]));

    let tx = Transaction {
        source_account,
        fee: 100,
        seq_num: SequenceNumber(0),
        cond: Preconditions::None,
        memo: Memo::None,
        operations: vec![operation].try_into()
            .map_err(|_| anyhow::anyhow!("Failed to create operations vec"))?,
        ext: TransactionExt::V0,
    };

    let tx_envelope = TransactionEnvelope::Tx(TransactionV1Envelope {
        tx,
        signatures: vec![].try_into()
            .map_err(|_| anyhow::anyhow!("Failed to create signatures vec"))?,
    });

    // Encode transaction to base64 XDR
    let tx_xdr = tx_envelope.to_xdr_base64(Limits::none())
        .context("Failed to encode transaction to XDR")?;

    // Make the simulateTransaction RPC call
    let rpc_request = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "simulateTransaction",
        "params": {
            "transaction": tx_xdr
        }
    });

    let response = client
        .post(Config::soroban_rpc_url())
        .json(&rpc_request)
        .send()
        .context("Failed to call RPC for price query")?;

    if !response.status().is_success() {
        anyhow::bail!("RPC returned error status: {}", response.status());
    }

    let json: serde_json::Value = response.json()
        .context("Failed to parse RPC response")?;

    if let Some(error) = json.get("error") {
        anyhow::bail!("RPC error: {}", error);
    }

    let result = json.get("result")
        .ok_or_else(|| anyhow::anyhow!("No result in RPC response"))?;

    // Check for RPC error in result
    if let Some(error) = result.get("error") {
        return Ok(serde_json::json!({
            "asset": asset_input,
            "asset_type": asset_type,
            "error": "Contract execution failed",
            "contract_error": error,
            "result": result
        }));
    }

    // Try to extract and decode the price data from the result XDR
    // The result should be in result.results[0].xdr
    // Expected structure: { price: i128, timestamp: u64 }
    if let Some(result_xdr) = result.get("results")
        .and_then(|r| r.get(0))
        .and_then(|r| r.get("xdr"))
        .and_then(|x| x.as_str())
    {
        match ScVal::from_xdr_base64(result_xdr, Limits::none()) {
            Ok(ScVal::Map(Some(map))) => {
                // Parse the map to extract price and timestamp
                let mut price_i128: Option<i128> = None;
                let mut timestamp_u64: Option<u64> = None;

                for entry in map.as_vec() {
                    if let ScVal::Symbol(ref key_sym) = entry.key {
                        let key_str = String::from_utf8_lossy(key_sym.as_vec());

                        match key_str.as_ref() {
                            "price" => {
                                if let ScVal::I128(parts) = &entry.val {
                                    price_i128 = Some(i128::from(parts.hi) << 64 | i128::from(parts.lo as u64));
                                }
                            }
                            "timestamp" => {
                                if let ScVal::U64(ts) = &entry.val {
                                    timestamp_u64 = Some(*ts);
                                }
                            }
                            _ => {}
                        }
                    }
                }

                if let (Some(price), Some(timestamp)) = (price_i128, timestamp_u64) {
                    // Format price with decimals
                    let price_float = price as f64 / 10_f64.powi(REFLECTOR_DECIMALS as i32);

                    return Ok(serde_json::json!({
                        "asset": asset_input,
                        "asset_type": asset_type,
                        "price": price_float,
                        "price_raw": price.to_string(),
                        "timestamp": timestamp,
                        "decimals": REFLECTOR_DECIMALS,
                        "source": "reflector"
                    }));
                }
            }
            Ok(val) => {
                // Return the ScVal as-is if it's not the expected structure
                return Ok(serde_json::json!({
                    "asset": asset_input,
                    "asset_type": asset_type,
                    "error": "Unexpected result format",
                    "result": format!("{:?}", val)
                }));
            }
            Err(e) => {
                return Ok(serde_json::json!({
                    "asset": asset_input,
                    "asset_type": asset_type,
                    "error": format!("Failed to decode result: {}", e),
                    "raw_xdr": result_xdr
                }));
            }
        }
    }

    // If we can't extract the XDR, return the full result
    Ok(serde_json::json!({
        "asset": asset_input,
        "asset_type": asset_type,
        "error": "No result XDR found in response",
        "result": result
    }))
}

/// Query TTL (time to live) for a contract's code and instance entries
///
/// Uses the Soroban RPC getLedgerEntries method to fetch both the entry and its TTL.
pub fn query_ttl(contract_address: &str) -> Result<serde_json::Value> {
    use stellar_xdr::curr::*;

    let client = reqwest::blocking::Client::new();

    // Decode the contract address
    let contract_bytes = match Strkey::from_string(contract_address) {
        Ok(Strkey::Contract(contract)) => contract.0,
        _ => anyhow::bail!("Invalid contract address format"),
    };

    let contract_sc_address = ScAddress::Contract(ContractId(Hash(contract_bytes)));

    // Helper to parse u32 from JSON (number or string)
    fn parse_u32(value: &serde_json::Value) -> Option<u32> {
        if let Some(num) = value.as_u64() {
            return u32::try_from(num).ok();
        }
        if let Some(text) = value.as_str() {
            return text.parse::<u32>().ok();
        }
        None
    }

    // Fetch entry and TTL info for a ledger key
    fn fetch_entry_with_ttl(
        client: &reqwest::blocking::Client,
        ledger_key: LedgerKey,
    ) -> Result<(serde_json::Value, Option<u32>, Option<Hash>, Option<String>)> {
        let key_xdr = ledger_key.to_xdr_base64(Limits::none())
            .context("Failed to encode ledger key to XDR")?;

        let rpc_request = serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "getLedgerEntries",
            "params": {
                "keys": [key_xdr]
            }
        });

        let response = client
            .post(Config::soroban_rpc_url())
            .json(&rpc_request)
            .send()
            .context("Failed to call RPC for ttl query")?;

        if !response.status().is_success() {
            anyhow::bail!("RPC returned error status: {}", response.status());
        }

        let json: serde_json::Value = response.json()
            .context("Failed to parse RPC response")?;

        if let Some(error) = json.get("error") {
            anyhow::bail!("RPC error: {}", error);
        }

        let result = json.get("result")
            .ok_or_else(|| anyhow::anyhow!("No result in RPC response"))?;

        let latest_ledger = result.get("latestLedger")
            .and_then(parse_u32)
            .or_else(|| result.get("latestLedgerSeq").and_then(parse_u32));

        let mut last_modified: Option<u32> = None;
        let mut live_until: Option<u32> = None;
        let mut found = false;
        let mut wasm_hash: Option<Hash> = None;
        let mut executable_type: Option<String> = None;

        if let Some(entries) = result.get("entries").and_then(|e| e.as_array()) {
            for entry in entries {
                if let Some(last) = entry.get("lastModifiedLedgerSeq").and_then(parse_u32) {
                    last_modified = Some(last);
                    found = true;
                }

                if let Some(live) = entry.get("liveUntilLedgerSeq").and_then(parse_u32) {
                    live_until = Some(live);
                }

                if let Some(xdr) = entry.get("xdr").and_then(|x| x.as_str()) {
                    if let Ok(entry_data) = LedgerEntryData::from_xdr_base64(xdr, Limits::none()) {
                        match entry_data {
                            LedgerEntryData::ContractData(data_entry) => {
                                found = true;

                                if let ScVal::ContractInstance(instance) = data_entry.val {
                                    match instance.executable {
                                        ContractExecutable::Wasm(hash) => {
                                            wasm_hash = Some(hash);
                                            executable_type = Some("Wasm".to_string());
                                        }
                                        ContractExecutable::StellarAsset => {
                                            executable_type = Some("StellarAsset".to_string());
                                        }
                                    }
                                }
                            }
                            LedgerEntryData::ContractCode(_) => {
                                found = true;
                            }
                            _ => {}
                        }
                    } else if let Ok(ledger_entry) =
                        LedgerEntry::from_xdr_base64(xdr, Limits::none())
                    {
                        last_modified = Some(ledger_entry.last_modified_ledger_seq);
                        match ledger_entry.data {
                            LedgerEntryData::ContractData(data_entry) => {
                                found = true;

                                if let ScVal::ContractInstance(instance) = data_entry.val {
                                    match instance.executable {
                                        ContractExecutable::Wasm(hash) => {
                                            wasm_hash = Some(hash);
                                            executable_type = Some("Wasm".to_string());
                                        }
                                        ContractExecutable::StellarAsset => {
                                            executable_type = Some("StellarAsset".to_string());
                                        }
                                    }
                                }
                            }
                            LedgerEntryData::ContractCode(_) => {
                                found = true;
                            }
                            _ => {}
                        }
                    }
                }
            }
        }

        let ttl_remaining = match (live_until, latest_ledger) {
            (Some(live), Some(current)) => Some(live.saturating_sub(current)),
            _ => None,
        };
        // Stellar averages ~5 seconds per ledger; use for a rough time estimate.
        let ttl_remaining_seconds = ttl_remaining.map(|remaining| remaining as u64 * 5);
        let ttl_remaining_days = ttl_remaining_seconds.map(|seconds| {
            let days = seconds as f64 / 86_400.0;
            (days * 100.0).round() / 100.0
        });

        Ok((
            serde_json::json!({
                "exists": found,
                "last_modified_ledger": last_modified,
                "live_until_ledger": live_until,
                "ttl_remaining_ledgers": ttl_remaining,
                "ttl_remaining_days": ttl_remaining_days,
                "ttl_estimate_seconds_per_ledger": 5,
                "contract_executable": executable_type.as_ref(),
                "contract_executable_wasm_hash": wasm_hash.as_ref().map(|h| h.to_string())
            }),
            latest_ledger,
            wasm_hash,
            executable_type,
        ))
    }

    // Contract instance entry (stored in contract data)
    let instance_key = LedgerKey::ContractData(LedgerKeyContractData {
        contract: contract_sc_address.clone(),
        key: ScVal::LedgerKeyContractInstance,
        durability: ContractDataDurability::Persistent,
    });

    let (instance_info, instance_latest, wasm_hash, executable_type) =
        fetch_entry_with_ttl(&client, instance_key)?;

    let (code_info, code_latest) = if let Some(hash) = wasm_hash {
        let code_hash = hash.clone();
        let code_key = LedgerKey::ContractCode(LedgerKeyContractCode { hash });
        let (info, latest, _, _) = fetch_entry_with_ttl(&client, code_key)?;
        (
            serde_json::json!({
                "code_hash": code_hash.to_string(),
                "ttl": info
            }),
            latest,
        )
    } else if executable_type.as_deref() == Some("StellarAsset") {
        (
            serde_json::json!({
                "exists": false,
                "error": "Contract executable is StellarAsset; no WASM code entry"
            }),
            None,
        )
    } else {
        (
            serde_json::json!({
                "exists": false,
                "error": "Contract instance did not provide a WASM code hash"
            }),
            None,
        )
    };

    let latest_ledger = instance_latest.or(code_latest);

    Ok(serde_json::json!({
        "contract": contract_address,
        "latest_ledger": latest_ledger,
        "contract_instance": instance_info,
        "contract_code": code_info
    }))
}