chia-query 0.5.2

Query the Chia blockchain via decentralized peers with coinset.org fallback
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
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
//! Thin HTTP wrapper around the coinset.org REST API.
//!
//! Every endpoint is a simple POST-JSON / parse-JSON round-trip.  The only
//! cleverness is the shared `post()` helper that checks the `success` flag in
//! every response.

use std::collections::HashMap;
#[cfg(feature = "native")]
use std::time::Duration;

use serde_json::{json, Value};

use crate::types::*;

pub mod transport;

use transport::HttpTransport;

/// The transport chia-query uses by default for the target it is built for:
/// `reqwest` on native, an injected `fetch` on wasm. Named so the common type
/// `CoinsetClient` (without a generic argument) resolves correctly on both.
#[cfg(feature = "native")]
pub type DefaultTransport = transport::ReqwestTransport;
#[cfg(all(target_arch = "wasm32", feature = "coinset", not(feature = "native")))]
pub type DefaultTransport = transport::FetchTransport;

/// A thin, transport-generic client over the coinset.org REST API.
///
/// Every endpoint is a `POST`-JSON / parse-JSON round-trip; the only cleverness
/// is [`post`](Self::post), which checks the `success` flag on every response.
pub struct CoinsetClient<T = DefaultTransport> {
    transport: T,
    base_url: String,
}

#[cfg(feature = "native")]
impl CoinsetClient<transport::ReqwestTransport> {
    /// Build a native coinset client backed by a `reqwest` transport.
    pub fn new(base_url: &str, timeout: Duration) -> Result<Self, ChiaQueryError> {
        Ok(Self {
            transport: transport::ReqwestTransport::new(timeout)?,
            base_url: base_url.trim_end_matches('/').to_string(),
        })
    }
}

impl<T: HttpTransport> CoinsetClient<T> {
    /// Build a client from an explicit transport (used by wasm consumers that
    /// inject `fetch`, and by tests supplying a mock transport).
    pub fn with_transport(base_url: &str, transport: T) -> Self {
        Self {
            transport,
            base_url: base_url.trim_end_matches('/').to_string(),
        }
    }

    // -----------------------------------------------------------------------
    // Generic POST helper
    // -----------------------------------------------------------------------

    /// POST to `endpoint` and return the response, mapping a `success: false`
    /// envelope to [`ChiaQueryError::CoinsetApiError`] (preferring the
    /// structured error message).
    pub async fn post(&self, endpoint: &str, body: &Value) -> Result<Value, ChiaQueryError> {
        let json = self.post_raw(endpoint, body).await?;
        if json.get("success").and_then(Value::as_bool) != Some(true) {
            return Err(ChiaQueryError::CoinsetApiError(coinset_error_message(
                &json,
            )));
        }
        Ok(json)
    }

    /// POST and return the raw JSON response *without* the `success` gate.
    ///
    /// Unlike [`post`](Self::post), this never converts a `success: false`
    /// envelope into an error โ€” the caller sees the response verbatim. It
    /// exists for the drift-monitor, which must inspect the *shape* of every
    /// response (including error envelopes) rather than its meaning.
    pub async fn post_raw(&self, endpoint: &str, body: &Value) -> Result<Value, ChiaQueryError> {
        let url = format!("{}/{}", self.base_url, endpoint);
        self.transport.post_json(url, body.clone()).await
    }

    /// Convenience: post and then deserialise a single key out of the
    /// response object.
    async fn post_extract<D: serde::de::DeserializeOwned>(
        &self,
        endpoint: &str,
        body: &Value,
        key: &str,
    ) -> Result<D, ChiaQueryError> {
        let json = self.post(endpoint, body).await?;
        serde_json::from_value(json[key].clone())
            .map_err(|e| ChiaQueryError::CoinsetApiError(format!("parse `{key}`: {e}")))
    }

    /// Absence-aware sibling of [`post_extract`](Self::post_extract): distinguishes a PROVABLE
    /// absence from a failure.
    ///
    /// coinset.org answers a "not found" single-record query with a `success: true` envelope whose
    /// data field is `null`. That is provable absence -> `Ok(None)`. A `success: false` envelope
    /// (handled by [`post`](Self::post)) is a failure -> `Err`, as is a present-but-unparseable
    /// field. Absence is NEVER collapsed into an error, and a transport/API error is NEVER collapsed
    /// into `Ok(None)` (SPEC ยง3, the money-critical mapping).
    async fn post_extract_opt<D: serde::de::DeserializeOwned>(
        &self,
        endpoint: &str,
        body: &Value,
        key: &str,
    ) -> Result<Option<D>, ChiaQueryError> {
        let json = self.post(endpoint, body).await?;
        optional_field(&json, key)
    }

    // =======================================================================
    // Blocks
    // =======================================================================

    pub async fn get_additions_and_removals(
        &self,
        header_hash: &str,
    ) -> Result<AdditionsAndRemovals, ChiaQueryError> {
        let json = self
            .post(
                "get_additions_and_removals",
                &json!({ "header_hash": header_hash }),
            )
            .await?;
        let additions = serde_json::from_value(json["additions"].clone())
            .map_err(|e| ChiaQueryError::CoinsetApiError(e.to_string()))?;
        let removals = serde_json::from_value(json["removals"].clone())
            .map_err(|e| ChiaQueryError::CoinsetApiError(e.to_string()))?;
        Ok(AdditionsAndRemovals {
            additions,
            removals,
        })
    }

    pub async fn get_block(&self, header_hash: &str) -> Result<FullBlock, ChiaQueryError> {
        self.post_extract("get_block", &json!({ "header_hash": header_hash }), "block")
            .await
    }

    pub async fn get_block_count_metrics(&self) -> Result<BlockCountMetrics, ChiaQueryError> {
        self.post_extract("get_block_count_metrics", &json!({}), "metrics")
            .await
    }

    pub async fn get_block_record(&self, header_hash: &str) -> Result<BlockRecord, ChiaQueryError> {
        self.post_extract(
            "get_block_record",
            &json!({ "header_hash": header_hash }),
            "block_record",
        )
        .await
    }

    pub async fn get_block_record_by_height(
        &self,
        height: u32,
    ) -> Result<BlockRecord, ChiaQueryError> {
        self.post_extract(
            "get_block_record_by_height",
            &json!({ "height": height }),
            "block_record",
        )
        .await
    }

    /// Absence-aware [`get_block_record_by_height`](Self::get_block_record_by_height): `Ok(None)`
    /// when no block exists at `height` (coinset returns `block_record: null`), `Err` on failure.
    pub async fn get_block_record_by_height_opt(
        &self,
        height: u32,
    ) -> Result<Option<BlockRecord>, ChiaQueryError> {
        self.post_extract_opt(
            "get_block_record_by_height",
            &json!({ "height": height }),
            "block_record",
        )
        .await
    }

    pub async fn get_block_records(
        &self,
        start: u32,
        end: u32,
    ) -> Result<Vec<BlockRecord>, ChiaQueryError> {
        self.post_extract(
            "get_block_records",
            &json!({ "start": start, "end": end }),
            "block_records",
        )
        .await
    }

    pub async fn get_block_spends(
        &self,
        header_hash: &str,
    ) -> Result<Vec<CoinSpend>, ChiaQueryError> {
        self.post_extract(
            "get_block_spends",
            &json!({ "header_hash": header_hash }),
            "block_spends",
        )
        .await
    }

    pub async fn get_block_spends_with_conditions(
        &self,
        header_hash: &str,
    ) -> Result<Vec<CoinSpendWithConditions>, ChiaQueryError> {
        self.post_extract(
            "get_block_spends_with_conditions",
            &json!({ "header_hash": header_hash }),
            "block_spends_with_conditions",
        )
        .await
    }

    pub async fn get_blocks(
        &self,
        start: u32,
        end: u32,
        exclude_header_hash: bool,
        exclude_reorged: bool,
    ) -> Result<Vec<FullBlock>, ChiaQueryError> {
        self.post_extract(
            "get_blocks",
            &json!({
                "start": start,
                "end": end,
                "exclude_header_hash": exclude_header_hash,
                "exclude_reorged": exclude_reorged,
            }),
            "blocks",
        )
        .await
    }

    pub async fn get_unfinished_block_headers(
        &self,
    ) -> Result<Vec<UnfinishedBlockHeader>, ChiaQueryError> {
        self.post_extract("get_unfinished_block_headers", &json!({}), "headers")
            .await
    }

    // =======================================================================
    // Coins
    // =======================================================================

    pub async fn get_coin_record_by_name(&self, name: &str) -> Result<CoinRecord, ChiaQueryError> {
        self.post_extract(
            "get_coin_record_by_name",
            &json!({ "name": name }),
            "coin_record",
        )
        .await
    }

    /// Absence-aware [`get_coin_record_by_name`](Self::get_coin_record_by_name): `Ok(None)` when the
    /// coin provably does not exist, `Err` when the read could not be completed.
    pub async fn get_coin_record_by_name_opt(
        &self,
        name: &str,
    ) -> Result<Option<CoinRecord>, ChiaQueryError> {
        self.post_extract_opt(
            "get_coin_record_by_name",
            &json!({ "name": name }),
            "coin_record",
        )
        .await
    }

    pub async fn get_coin_records_by_hint(
        &self,
        hint: &str,
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        self.post_extract(
            "get_coin_records_by_hint",
            &json!({
                "hint": hint,
                "start_height": start_height,
                "end_height": end_height,
                "include_spent_coins": include_spent_coins,
            }),
            "coin_records",
        )
        .await
    }

    pub async fn get_coin_records_by_hints(
        &self,
        hints: &[String],
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        self.post_extract(
            "get_coin_records_by_hints",
            &json!({
                "hints": hints,
                "start_height": start_height,
                "end_height": end_height,
                "include_spent_coins": include_spent_coins,
            }),
            "coin_records",
        )
        .await
    }

    pub async fn get_coin_records_by_names(
        &self,
        names: &[String],
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        self.post_extract(
            "get_coin_records_by_names",
            &json!({
                "names": names,
                "start_height": start_height,
                "end_height": end_height,
                "include_spent_coins": include_spent_coins,
            }),
            "coin_records",
        )
        .await
    }

    pub async fn get_coin_records_by_parent_ids(
        &self,
        parent_ids: &[String],
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        self.post_extract(
            "get_coin_records_by_parent_ids",
            &json!({
                "parent_ids": parent_ids,
                "start_height": start_height,
                "end_height": end_height,
                "include_spent_coins": include_spent_coins,
            }),
            "coin_records",
        )
        .await
    }

    pub async fn get_coin_records_by_puzzle_hash(
        &self,
        puzzle_hash: &str,
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        self.post_extract(
            "get_coin_records_by_puzzle_hash",
            &json!({
                "puzzle_hash": puzzle_hash,
                "start_height": start_height,
                "end_height": end_height,
                "include_spent_coins": include_spent_coins,
            }),
            "coin_records",
        )
        .await
    }

    pub async fn get_coin_records_by_puzzle_hashes(
        &self,
        puzzle_hashes: &[String],
        start_height: Option<u32>,
        end_height: Option<u32>,
        include_spent_coins: bool,
    ) -> Result<Vec<CoinRecord>, ChiaQueryError> {
        self.post_extract(
            "get_coin_records_by_puzzle_hashes",
            &json!({
                "puzzle_hashes": puzzle_hashes,
                "start_height": start_height,
                "end_height": end_height,
                "include_spent_coins": include_spent_coins,
            }),
            "coin_records",
        )
        .await
    }

    pub async fn get_memos_by_coin_name(&self, name: &str) -> Result<Value, ChiaQueryError> {
        self.post_extract("get_memos_by_coin_name", &json!({ "name": name }), "memos")
            .await
    }

    pub async fn get_puzzle_and_solution(
        &self,
        coin_id: &str,
        height: Option<u32>,
    ) -> Result<CoinSpend, ChiaQueryError> {
        self.post_extract(
            "get_puzzle_and_solution",
            &json!({ "coin_id": coin_id, "height": height }),
            "coin_solution",
        )
        .await
    }

    /// Absence-aware [`get_puzzle_and_solution`](Self::get_puzzle_and_solution): `Ok(None)` when the
    /// coin is provably unspent/unknown (coinset returns `coin_solution: null`), `Err` on failure.
    pub async fn get_puzzle_and_solution_opt(
        &self,
        coin_id: &str,
        height: Option<u32>,
    ) -> Result<Option<CoinSpend>, ChiaQueryError> {
        self.post_extract_opt(
            "get_puzzle_and_solution",
            &json!({ "coin_id": coin_id, "height": height }),
            "coin_solution",
        )
        .await
    }

    pub async fn get_puzzle_and_solution_with_conditions(
        &self,
        coin_id: &str,
        height: Option<u32>,
    ) -> Result<CoinSpendWithConditions, ChiaQueryError> {
        let json = self
            .post(
                "get_puzzle_and_solution_with_conditions",
                &json!({ "coin_id": coin_id, "height": height }),
            )
            .await?;
        let coin_spend: CoinSpend = serde_json::from_value(json["coin_solution"].clone())
            .map_err(|e| ChiaQueryError::CoinsetApiError(e.to_string()))?;
        let conditions: Vec<Condition> =
            serde_json::from_value(json["conditions"].clone()).unwrap_or_default();
        Ok(CoinSpendWithConditions {
            coin_spend,
            conditions,
        })
    }

    pub async fn push_tx(&self, bundle: &SpendBundle) -> Result<TxStatus, ChiaQueryError> {
        let body = json!({ "spend_bundle": bundle });
        let json = self.post("push_tx", &body).await?;
        let status = json["status"].as_str().unwrap_or("UNKNOWN").to_string();
        Ok(TxStatus {
            status,
            success: true,
        })
    }

    // =======================================================================
    // Fees
    // =======================================================================

    pub async fn get_fee_estimate(
        &self,
        spend_bundle: Option<&SpendBundle>,
        target_times: Option<&[u64]>,
        spend_count: Option<u64>,
    ) -> Result<FeeEstimate, ChiaQueryError> {
        let mut body = json!({ "cost": 1 });
        if let Some(sb) = spend_bundle {
            body["spend_bundle"] = serde_json::to_value(sb)
                .map_err(|e| ChiaQueryError::InvalidRequest(e.to_string()))?;
        }
        if let Some(tt) = target_times {
            body["target_times"] = json!(tt);
        }
        if let Some(sc) = spend_count {
            body["spend_count"] = json!(sc);
        }
        let json = self.post("get_fee_estimate", &body).await?;
        serde_json::from_value(json)
            .map_err(|e| ChiaQueryError::CoinsetApiError(format!("parse fee_estimate: {e}")))
    }

    // =======================================================================
    // Full node / network
    // =======================================================================

    pub async fn get_aggsig_additional_data(&self) -> Result<String, ChiaQueryError> {
        self.post_extract("get_aggsig_additional_data", &json!({}), "additional_data")
            .await
    }

    pub async fn get_network_info(&self) -> Result<NetworkInfo, ChiaQueryError> {
        let json = self.post("get_network_info", &json!({})).await?;
        serde_json::from_value(json)
            .map_err(|e| ChiaQueryError::CoinsetApiError(format!("parse network_info: {e}")))
    }

    pub async fn get_blockchain_state(&self) -> Result<BlockchainState, ChiaQueryError> {
        self.post_extract("get_blockchain_state", &json!({}), "blockchain_state")
            .await
    }

    pub async fn get_network_space(
        &self,
        newer_block_header_hash: &str,
        older_block_header_hash: &str,
    ) -> Result<u64, ChiaQueryError> {
        self.post_extract(
            "get_network_space",
            &json!({
                "newer_block_header_hash": newer_block_header_hash,
                "older_block_header_hash": older_block_header_hash,
            }),
            "space",
        )
        .await
    }

    // =======================================================================
    // Mempool
    // =======================================================================

    pub async fn get_all_mempool_items(
        &self,
    ) -> Result<HashMap<String, MempoolItem>, ChiaQueryError> {
        self.post_extract("get_all_mempool_items", &json!({}), "mempool_items")
            .await
    }

    pub async fn get_all_mempool_tx_ids(&self) -> Result<Vec<String>, ChiaQueryError> {
        self.post_extract("get_all_mempool_tx_ids", &json!({}), "tx_ids")
            .await
    }

    pub async fn get_mempool_item_by_tx_id(
        &self,
        tx_id: &str,
    ) -> Result<MempoolItem, ChiaQueryError> {
        self.post_extract(
            "get_mempool_item_by_tx_id",
            &json!({ "tx_id": tx_id }),
            "mempool_item",
        )
        .await
    }

    pub async fn get_mempool_items_by_coin_name(
        &self,
        coin_name: &str,
        include_spent_coins: Option<bool>,
    ) -> Result<Vec<MempoolItem>, ChiaQueryError> {
        let mut body = json!({ "coin_name": coin_name });
        if let Some(inc) = include_spent_coins {
            body["include_spent_coins"] = json!(inc);
        }
        self.post_extract("get_mempool_items_by_coin_name", &body, "mempool_items")
            .await
    }
}

// ---------------------------------------------------------------------------
// Error-envelope parsing
// ---------------------------------------------------------------------------

/// Extract a human-readable message from a coinset.org error envelope.
///
/// A failing coinset.org response carries
/// `{ "error", "structuredError", "traceback", "success": false }`. The
/// `structuredError` field โ€” an object `{ code, data, message }` (or, on some
/// endpoints, a bare string) โ€” is the newer, stable summary and is preferred;
/// the legacy `error` string is the fallback; then a generic message.
///
/// `traceback` is deliberately IGNORED: it is opaque server-internal detail
/// (stack frames) and must never surface into user-facing output.
pub fn coinset_error_message(json: &Value) -> String {
    structured_error_message(json.get("structuredError"))
        .or_else(|| non_empty_str(json.get("error")))
        .unwrap_or_else(|| "unknown error".to_string())
}

/// Pull the message out of a `structuredError` value, accepting either a bare
/// string or an object exposing `message` (preferred) or `error`.
fn structured_error_message(value: Option<&Value>) -> Option<String> {
    match value? {
        Value::String(s) if !s.trim().is_empty() => Some(s.clone()),
        Value::Object(map) => {
            non_empty_str(map.get("message")).or_else(|| non_empty_str(map.get("error")))
        }
        _ => None,
    }
}

/// Interprets the `key` field of a `success: true` coinset envelope as a PROVABLE-absence signal.
///
/// A `null` (or absent) field means the queried record genuinely does not exist -> `Ok(None)`. A
/// present field that fails to deserialize is a malformed/unusable answer -> `Err` (never
/// `Ok(None)`), so an unparseable payload can never be mistaken for absence (SPEC ยง3).
fn optional_field<D: serde::de::DeserializeOwned>(
    json: &Value,
    key: &str,
) -> Result<Option<D>, ChiaQueryError> {
    match json.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(present) => serde_json::from_value(present.clone())
            .map(Some)
            .map_err(|e| ChiaQueryError::CoinsetApiError(format!("parse `{key}`: {e}"))),
    }
}

/// A trimmed, owned copy of a JSON string value, or `None` when absent/blank.
fn non_empty_str(value: Option<&Value>) -> Option<String> {
    value
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn prefers_structured_error_message_over_legacy_error() {
        // The real coinset.org error envelope (probed 2026-07-16): `structuredError`
        // is an object and rides beside the legacy `error` string + a `traceback`.
        let envelope = json!({
            "error": "Coin record 0xnothex not found",
            "structuredError": {
                "code": "COIN_RECORD_NOT_FOUND",
                "data": { "name": "nothex" },
                "message": "Coin record not found"
            },
            "success": false,
            "traceback": null
        });
        assert_eq!(coinset_error_message(&envelope), "Coin record not found");
    }

    #[test]
    fn traceback_is_never_surfaced() {
        let envelope = json!({
            "error": "boom",
            "structuredError": { "message": "clean summary" },
            "traceback": "Traceback (most recent call last): secret internals",
            "success": false
        });
        let msg = coinset_error_message(&envelope);
        assert_eq!(msg, "clean summary");
        assert!(!msg.contains("Traceback"));
    }

    #[test]
    fn accepts_structured_error_as_bare_string() {
        let envelope = json!({ "structuredError": "just a string", "success": false });
        assert_eq!(coinset_error_message(&envelope), "just a string");
    }

    #[test]
    fn falls_back_to_legacy_error_when_no_structured_error() {
        let envelope = json!({ "error": "legacy only", "success": false });
        assert_eq!(coinset_error_message(&envelope), "legacy only");
    }

    #[test]
    fn falls_back_to_legacy_when_structured_error_is_empty() {
        let envelope = json!({
            "error": "legacy wins",
            "structuredError": { "message": "   " },
            "success": false
        });
        assert_eq!(coinset_error_message(&envelope), "legacy wins");
    }

    #[test]
    fn generic_message_when_nothing_usable() {
        let envelope = json!({ "success": false });
        assert_eq!(coinset_error_message(&envelope), "unknown error");
    }

    // ---- optional_field: PROVABLE absence vs a malformed payload (SPEC ยง3) ----

    #[test]
    fn optional_field_null_is_provable_absence() {
        // A `success: true` envelope with a null record = the coin genuinely does not exist.
        let envelope = json!({ "success": true, "coin_record": null });
        let record: Option<CoinRecord> = optional_field(&envelope, "coin_record").unwrap();
        assert!(record.is_none());
    }

    #[test]
    fn optional_field_missing_key_is_absence() {
        let envelope = json!({ "success": true });
        let record: Option<CoinRecord> = optional_field(&envelope, "coin_record").unwrap();
        assert!(record.is_none());
    }

    #[test]
    fn optional_field_present_record_is_some() {
        let envelope = json!({
            "success": true,
            "coin_record": {
                "coin": { "parent_coin_info": "0x00", "puzzle_hash": "0x11", "amount": 1 },
                "confirmed_block_index": 5,
                "spent_block_index": 0,
                "spent": false,
                "coinbase": false,
                "timestamp": 123
            }
        });
        let record: Option<CoinRecord> = optional_field(&envelope, "coin_record").unwrap();
        assert_eq!(record.unwrap().confirmed_block_index, 5);
    }

    #[test]
    fn optional_field_unparseable_present_payload_is_error_not_absence() {
        // Present but malformed -> Err, NEVER Ok(None): an unusable answer must not read as absence.
        let envelope = json!({ "success": true, "coin_record": "not-an-object" });
        let result: Result<Option<CoinRecord>, _> = optional_field(&envelope, "coin_record");
        assert!(result.is_err());
    }
}