cow-rs 0.1.1

Rust SDK for the CoW Protocol: quoting, signing, posting and tracking orders, plus composable orders, on-chain reads and subgraph queries.
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
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
//! `MetadataApi` facade and IPFS fetch/upload helpers for `CoW` Protocol
//! app-data.
//!
//! This module provides two layers of API:
//!
//! 1. **Free functions** — stateless helpers like [`get_app_data_info`], [`validate_app_data_doc`],
//!    [`fetch_doc_from_cid`], and [`upload_app_data_to_pinata`] that operate on explicit
//!    parameters.
//!
//! 2. **[`MetadataApi`]** — an ergonomic facade that bundles an [`Ipfs`] configuration and
//!    delegates to the free functions, mirroring the `MetadataApi` class from the `TypeScript` SDK.
//!
//! Most users will interact through [`MetadataApi`]:
//!
//! ```rust
//! use cow_rs::app_data::{AppDataDoc, MetadataApi};
//!
//! let api = MetadataApi::new();
//! let doc = api.generate_app_data_doc("MyApp");
//! let info = api.get_app_data_info(&doc).unwrap();
//! println!("appData hex : {}", info.app_data_hex);
//! println!("CID         : {}", info.cid);
//! ```

use std::fmt;

use alloy_primitives::B256;
use serde::Deserialize;
use serde_json::json;

use crate::error::CowError;

use super::{
    cid::{appdata_hex_to_cid, cid_to_appdata_hex, extract_digest},
    hash::{appdata_hex, stringify_deterministic},
    types::{AppDataDoc, Metadata},
    validation::{ValidationError, validate_constraints},
};

/// Default IPFS gateway used when none is provided.
pub const DEFAULT_IPFS_READ_URI: &str = "https://cloudflare-ipfs.com/ipfs";

/// Default IPFS write URI (Pinata).
pub const DEFAULT_IPFS_WRITE_URI: &str = "https://api.pinata.cloud";

// ── Extra types ───────────────────────────────────────────────────────────────

/// Full app-data information derived from an [`AppDataDoc`].
///
/// Bundles the three representations of an order's app-data that are
/// needed at different stages of the order lifecycle:
///
/// - **`cid`** — used to store/retrieve the document on IPFS.
/// - **`app_data_content`** — the canonical JSON whose `keccak256` equals `app_data_hex`. Pin this
///   string on IPFS so solvers can read the metadata.
/// - **`app_data_hex`** — the 32-byte value placed in the on-chain order struct.
///
/// Obtain an instance via [`get_app_data_info`] or [`MetadataApi::get_app_data_info`].
///
/// # Example
///
/// ```
/// use cow_rs::app_data::{AppDataDoc, get_app_data_info};
///
/// let doc = AppDataDoc::new("MyDApp");
/// let info = get_app_data_info(&doc).unwrap();
/// assert!(info.app_data_hex.starts_with("0x"));
/// assert!(info.cid.starts_with('f'));
/// assert!(info.app_data_content.contains("MyDApp"));
/// ```
#[derive(Debug, Clone)]
pub struct AppDataInfo {
    /// IPFS `CIDv1` string for the order's app-data.
    pub cid: String,
    /// Canonical JSON string whose `keccak256` equals [`Self::app_data_hex`].
    pub app_data_content: String,
    /// `0x`-prefixed 32-byte hex used as `appData` in the on-chain order struct.
    pub app_data_hex: String,
}

impl AppDataInfo {
    /// Construct an [`AppDataInfo`] from its three constituent fields.
    ///
    /// Prefer [`get_app_data_info`] to derive all three values from an
    /// [`AppDataDoc`] automatically. Use this constructor only when you
    /// already have the CID, JSON content, and hex hash from an external
    /// source.
    ///
    /// # Parameters
    ///
    /// * `cid` — the IPFS `CIDv1` base16 string.
    /// * `app_data_content` — the canonical JSON string.
    /// * `app_data_hex` — the `0x`-prefixed 32-byte `keccak256` hex.
    ///
    /// # Returns
    ///
    /// A new [`AppDataInfo`] instance.
    #[must_use]
    pub fn new(
        cid: impl Into<String>,
        app_data_content: impl Into<String>,
        app_data_hex: impl Into<String>,
    ) -> Self {
        Self {
            cid: cid.into(),
            app_data_content: app_data_content.into(),
            app_data_hex: app_data_hex.into(),
        }
    }
}

impl fmt::Display for AppDataInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "app-data-info({}, {})", self.cid, self.app_data_hex)
    }
}

/// IPFS connection parameters for upload/fetch operations.
///
/// Configure read/write gateway URIs and optional Pinata API credentials.
/// Pass an instance to [`MetadataApi::with_ipfs`] or directly to
/// [`upload_app_data_to_pinata`].
///
/// # Example
///
/// ```
/// use cow_rs::app_data::Ipfs;
///
/// let ipfs = Ipfs::default()
///     .with_read_uri("https://my-gateway.io/ipfs")
///     .with_pinata("my-api-key", "my-api-secret");
/// assert_eq!(ipfs.read_uri.as_deref(), Some("https://my-gateway.io/ipfs"));
/// ```
#[derive(Debug, Clone, Default)]
pub struct Ipfs {
    /// IPFS read gateway URI (defaults to [`DEFAULT_IPFS_READ_URI`]).
    pub read_uri: Option<String>,
    /// IPFS write gateway URI (defaults to [`DEFAULT_IPFS_WRITE_URI`]).
    pub write_uri: Option<String>,
    /// Pinata API key for authenticated uploads.
    pub pinata_api_key: Option<String>,
    /// Pinata API secret for authenticated uploads.
    pub pinata_api_secret: Option<String>,
}

/// Result of validating an [`AppDataDoc`] against its schema.
///
/// Contains both human-readable error strings (for logging / display) and
/// typed [`ValidationError`] values (for programmatic inspection). An empty
/// [`typed_errors`](Self::typed_errors) list means the document is valid.
///
/// Obtain an instance via [`validate_app_data_doc`] or
/// [`MetadataApi::validate_app_data_doc`].
///
/// # Example
///
/// ```
/// use cow_rs::app_data::{AppDataDoc, validate_app_data_doc};
///
/// let result = validate_app_data_doc(&AppDataDoc::new("OK"));
/// assert!(result.is_valid());
/// assert!(!result.has_errors());
/// assert_eq!(result.error_count(), 0);
/// ```
#[derive(Debug, Clone)]
pub struct ValidationResult {
    /// Whether the document is valid (no errors found).
    pub success: bool,
    /// Human-readable validation errors (empty when `success` is true).
    ///
    /// Kept as `Vec<String>` for backwards compatibility with callers that
    /// only inspect the string messages; typed errors are in [`Self::typed_errors`].
    pub errors: Vec<String>,
    /// Structured, typed constraint violations (empty when `success` is true).
    pub typed_errors: Vec<ValidationError>,
}

impl ValidationResult {
    /// Construct a [`ValidationResult`] from a success flag and
    /// human-readable error list.
    ///
    /// The `typed_errors` field is initialised to an empty `Vec`. Callers
    /// typically use [`validate_app_data_doc`] instead, which populates
    /// both the string errors and typed errors automatically.
    ///
    /// # Parameters
    ///
    /// * `success` — whether the document is valid.
    /// * `errors` — human-readable error messages.
    ///
    /// # Returns
    ///
    /// A new [`ValidationResult`] with an empty `typed_errors` list.
    #[must_use]
    pub const fn new(success: bool, errors: Vec<String>) -> Self {
        Self { success, errors, typed_errors: Vec::new() }
    }

    /// Returns `true` when validation succeeded (no errors).
    ///
    /// Equivalent to checking `typed_errors.is_empty()`, but stored as a
    /// precomputed flag for convenience.
    #[must_use]
    pub const fn is_valid(&self) -> bool {
        self.success
    }

    /// Returns `true` when at least one constraint violation was found.
    ///
    /// The inverse of [`is_valid`](Self::is_valid).
    #[must_use]
    pub const fn has_errors(&self) -> bool {
        !self.typed_errors.is_empty()
    }

    /// Returns the number of typed constraint violations.
    ///
    /// # Returns
    ///
    /// `0` when the document is valid, `> 0` otherwise.
    #[must_use]
    pub const fn error_count(&self) -> usize {
        self.typed_errors.len()
    }

    /// Returns a slice of all typed constraint violations.
    ///
    /// Use this for programmatic inspection of validation errors. Each
    /// [`ValidationError`] variant carries enough context to build a
    /// diagnostic message.
    ///
    /// # Returns
    ///
    /// An empty slice when the document is valid.
    #[must_use]
    pub fn errors_ref(&self) -> &[ValidationError] {
        &self.typed_errors
    }

    /// Returns the first typed constraint violation, if any.
    ///
    /// Useful for quick "fail on first error" workflows.
    ///
    /// # Returns
    ///
    /// `None` when the document is valid, `Some(&error)` otherwise.
    #[must_use]
    pub fn first_error(&self) -> Option<&ValidationError> {
        self.typed_errors.first()
    }
}

impl fmt::Display for ValidationResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.success {
            f.write_str("valid")
        } else {
            write!(f, "invalid({} errors)", self.typed_errors.len())
        }
    }
}

impl Ipfs {
    /// Set the IPFS read gateway URI.
    ///
    /// Overrides the default [`DEFAULT_IPFS_READ_URI`] (`cloudflare-ipfs.com`)
    /// for all fetch operations.
    ///
    /// # Parameters
    ///
    /// * `uri` — the base URL of the IPFS read gateway (e.g. `"https://my-gateway.io/ipfs"`).
    ///
    /// # Returns
    ///
    /// `self` with `read_uri` set.
    #[must_use]
    pub fn with_read_uri(mut self, uri: impl Into<String>) -> Self {
        self.read_uri = Some(uri.into());
        self
    }

    /// Set the IPFS write gateway URI.
    ///
    /// Overrides the default [`DEFAULT_IPFS_WRITE_URI`] (`api.pinata.cloud`)
    /// for all upload operations.
    ///
    /// # Parameters
    ///
    /// * `uri` — the base URL of the IPFS write gateway.
    ///
    /// # Returns
    ///
    /// `self` with `write_uri` set.
    #[must_use]
    pub fn with_write_uri(mut self, uri: impl Into<String>) -> Self {
        self.write_uri = Some(uri.into());
        self
    }

    /// Set Pinata API credentials for authenticated uploads.
    ///
    /// Both the API key and secret are required for
    /// [`upload_app_data_to_pinata`] to succeed. Obtain them from the Pinata
    /// dashboard.
    ///
    /// # Parameters
    ///
    /// * `api_key` — your Pinata API key.
    /// * `api_secret` — your Pinata API secret.
    ///
    /// # Returns
    ///
    /// `self` with both `pinata_api_key` and `pinata_api_secret` set.
    #[must_use]
    pub fn with_pinata(
        mut self,
        api_key: impl Into<String>,
        api_secret: impl Into<String>,
    ) -> Self {
        self.pinata_api_key = Some(api_key.into());
        self.pinata_api_secret = Some(api_secret.into());
        self
    }
}

impl fmt::Display for Ipfs {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let uri = self.read_uri.as_deref().map_or("default", |s| s);
        write!(f, "ipfs(read={uri})")
    }
}

// ── AppDataInfo helpers ───────────────────────────────────────────────────────

/// Derive the full [`AppDataInfo`] from a document.
///
/// Performs three steps in sequence:
/// 1. Serialise `doc` to deterministic JSON via [`stringify_deterministic`].
/// 2. Compute `keccak256(json_bytes)` to get the `appData` hex.
/// 3. Convert the hex to a `CIDv1` string via [`appdata_hex_to_cid`].
///
/// Mirrors `getAppDataInfo` from the `@cowprotocol/app-data` `TypeScript`
/// package.
///
/// # Parameters
///
/// * `doc` — the [`AppDataDoc`] to derive info from.
///
/// # Returns
///
/// An [`AppDataInfo`] containing the canonical JSON, `0x`-prefixed hex
/// hash, and base16 `CIDv1` string.
///
/// # Errors
///
/// Returns [`CowError::AppData`] on serialisation or CID conversion failure.
///
/// # Example
///
/// ```
/// use cow_rs::app_data::{AppDataDoc, get_app_data_info};
///
/// let doc = AppDataDoc::new("CoW Swap");
/// let info = get_app_data_info(&doc)?;
/// assert!(!info.cid.is_empty());
/// assert!(info.app_data_hex.starts_with("0x"));
/// assert!(!info.app_data_content.is_empty());
/// # Ok::<(), cow_rs::error::CowError>(())
/// ```
pub fn get_app_data_info(doc: &AppDataDoc) -> Result<AppDataInfo, CowError> {
    let app_data_content = stringify_deterministic(doc)?;
    let hash: B256 = alloy_primitives::keccak256(app_data_content.as_bytes());
    let app_data_hex = format!("0x{}", alloy_primitives::hex::encode(hash.as_slice()));
    let cid = appdata_hex_to_cid(&app_data_hex)?;
    Ok(AppDataInfo { cid, app_data_content, app_data_hex })
}

/// Derive [`AppDataInfo`] from a pre-serialised app-data JSON string.
///
/// Unlike [`get_app_data_info`], this function does **not** re-serialise
/// the document — it treats `json` as the canonical pre-image and hashes
/// it directly with `keccak256`. Use this when you have a string that was
/// already produced by [`stringify_deterministic`] and must not be
/// re-encoded, or when you received a JSON string from an external source
/// and want to compute its on-chain hash.
///
/// # Parameters
///
/// * `json` — the canonical JSON string to hash.
///
/// # Returns
///
/// An [`AppDataInfo`] where `app_data_content` is `json` verbatim.
///
/// # Errors
///
/// Returns [`CowError::AppData`] on `CID` conversion failure.
///
/// # Example
///
/// ```
/// use cow_rs::app_data::{AppDataDoc, MetadataApi, stringify_deterministic};
///
/// let doc = AppDataDoc::new("CoW Swap");
/// let canonical_json = stringify_deterministic(&doc)?;
/// let api = MetadataApi::new();
/// let info = api.get_app_data_info_from_str(&canonical_json)?;
/// assert!(info.app_data_hex.starts_with("0x"));
/// assert_eq!(info.app_data_content, canonical_json);
/// # Ok::<(), cow_rs::error::CowError>(())
/// ```
pub fn get_app_data_info_from_str(json: &str) -> Result<AppDataInfo, CowError> {
    let hash: alloy_primitives::B256 = alloy_primitives::keccak256(json.as_bytes());
    let app_data_hex = format!("0x{}", alloy_primitives::hex::encode(hash.as_slice()));
    let cid = appdata_hex_to_cid(&app_data_hex)?;
    Ok(AppDataInfo { cid, app_data_content: json.to_owned(), app_data_hex })
}

/// Validate an [`AppDataDoc`] against all `CoW` Protocol app-data rules.
///
/// Runs up to three independent checks and merges their results into a
/// single [`ValidationResult`]:
///
/// 1. **Version check** — `version` must be non-empty and parse as semver `x.y.z`.
/// 2. **Business-rule constraints** — `appCode` length, hook address format, `partnerFee`
///    basis-point caps, and similar field-level rules enforced by the private `validation` helper
///    module.
/// 3. **JSON Schema validation** — *(only when the `schema-validation` feature is enabled; on by
///    default for native targets, off by default on wasm)* the serialised document is checked
///    against the bundled upstream schema via the `schema` module, catching structural drift that
///    the hand-written business rules do not cover (missing required fields, unknown properties,
///    regex violations, `anyOf` variants, …).
///
/// Returns a [`ValidationResult`] that lists every violation found. An
/// empty [`ValidationResult::typed_errors`] list means the document is
/// fully valid.
///
/// # Example
///
/// ```
/// use cow_rs::app_data::{AppDataDoc, validate_app_data_doc};
///
/// let doc = AppDataDoc::new("CoW Swap");
/// let result = validate_app_data_doc(&doc);
/// assert!(result.is_valid());
/// assert!(!result.has_errors());
/// ```
#[must_use]
pub fn validate_app_data_doc(doc: &AppDataDoc) -> ValidationResult {
    let mut typed_errors: Vec<ValidationError> = Vec::new();

    // ── Version check ──────────────────────────────────────────────────────
    if doc.version.is_empty() {
        typed_errors.push(ValidationError::InvalidVersion("version must not be empty".to_owned()));
    } else {
        // Expect semver format: \d+\.\d+\.\d+
        let parts: Vec<&str> = doc.version.split('.').collect();
        if parts.len() != 3 || parts.iter().any(|p| p.parse::<u32>().is_err()) {
            typed_errors.push(ValidationError::InvalidVersion(format!(
                "version '{}' is not valid semver",
                doc.version
            )));
        }
    }

    // ── Business-rule checks (appCode, hooks, partnerFee, orderClass, …) ──
    validate_constraints(doc, &mut typed_errors);

    // ── Structural JSON Schema check ───────────────────────────────────────
    //
    // Dispatches on `doc.version`: [`super::schema::validate`] selects the
    // bundled schema matching the document's declared version and returns
    // either a list of violations or an `UnsupportedVersion` error. Both
    // outcomes flow into the combined `ValidationResult`.
    #[cfg(feature = "schema-validation")]
    match super::schema::validate(doc) {
        Ok(()) => {}
        Err(super::schema::SchemaError::Violations(violations)) => {
            for v in violations {
                typed_errors
                    .push(ValidationError::SchemaViolation { path: v.path, message: v.message });
            }
        }
        Err(super::schema::SchemaError::UnsupportedVersion { requested, supported }) => {
            typed_errors.push(ValidationError::SchemaViolation {
                path: "/version".to_owned(),
                message: format!(
                    "AppData version `{requested}` is not backed by a bundled schema in \
                     this build (supported: {})",
                    supported.join(", ")
                ),
            });
        }
    }

    // Render string representations once, in sync with the typed list.
    let string_errors: Vec<String> = typed_errors.iter().map(|e| e.to_string()).collect();

    let success = typed_errors.is_empty();
    ValidationResult { success, errors: string_errors, typed_errors }
}

// ── IPFS fetch ────────────────────────────────────────────────────────────────

/// Fetch an [`AppDataDoc`] from IPFS by its `CIDv1`.
///
/// Sends a GET request to `{ipfs_uri}/{cid}` and deserialises the JSON
/// response into an [`AppDataDoc`].
///
/// # Parameters
///
/// * `cid` — the `CIDv1` base16 string identifying the document.
/// * `ipfs_uri` — optional gateway base URL. Defaults to [`DEFAULT_IPFS_READ_URI`] when `None`.
///
/// # Returns
///
/// The deserialised [`AppDataDoc`].
///
/// # Errors
///
/// Returns [`CowError::Http`] or [`CowError::Parse`] on failure.
///
/// # Example
///
/// ```no_run
/// use cow_rs::app_data::fetch_doc_from_cid;
///
/// # async fn example() -> Result<(), cow_rs::error::CowError> {
/// let cid = "bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi";
/// let doc = fetch_doc_from_cid(cid, None).await?;
/// assert!(!doc.version.is_empty());
/// # Ok(())
/// # }
/// ```
pub async fn fetch_doc_from_cid(cid: &str, ipfs_uri: Option<&str>) -> Result<AppDataDoc, CowError> {
    let base = ipfs_uri.map_or(DEFAULT_IPFS_READ_URI, |s| s);
    let url = format!("{base}/{cid}");
    let text = reqwest::get(&url).await?.text().await?;
    serde_json::from_str(&text)
        .map_err(|e| CowError::Parse { field: "app_data_doc", reason: e.to_string() })
}

/// Fetch an [`AppDataDoc`] from IPFS using a hex `appData` value.
///
/// Converts `app_data_hex` to a `CIDv1` via
/// [`appdata_hex_to_cid`], then delegates
/// to [`fetch_doc_from_cid`] for the actual HTTP fetch.
///
/// # Parameters
///
/// * `app_data_hex` — the `0x`-prefixed 32-byte hex value from the on-chain order struct.
/// * `ipfs_uri` — optional gateway base URL (defaults to [`DEFAULT_IPFS_READ_URI`]).
///
/// # Returns
///
/// The deserialised [`AppDataDoc`].
///
/// # Errors
///
/// Returns [`CowError::AppData`], [`CowError::Http`], or [`CowError::Parse`].
///
/// # Example
///
/// ```no_run
/// use cow_rs::app_data::fetch_doc_from_app_data_hex;
///
/// # async fn example() -> Result<(), cow_rs::error::CowError> {
/// let hex = "0x0000000000000000000000000000000000000000000000000000000000000000";
/// let doc = fetch_doc_from_app_data_hex(hex, None).await?;
/// assert!(!doc.version.is_empty());
/// # Ok(())
/// # }
/// ```
pub async fn fetch_doc_from_app_data_hex(
    app_data_hex: &str,
    ipfs_uri: Option<&str>,
) -> Result<AppDataDoc, CowError> {
    let cid = appdata_hex_to_cid(app_data_hex)?;
    fetch_doc_from_cid(&cid, ipfs_uri).await
}

// ── IPFS upload ───────────────────────────────────────────────────────────────

/// Response from the Pinata `pinJSONToIPFS` endpoint.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct PinataResponse {
    ipfs_hash: String,
}

/// Upload an [`AppDataDoc`] to IPFS via the Pinata pinning service.
///
/// The document is first serialised to deterministic JSON and hashed via
/// [`get_app_data_info`], then uploaded to
/// `{write_uri}/pinning/pinJSONToIPFS` using the provided Pinata API
/// credentials. The canonical JSON is pinned as `pinataContent` and the
/// `keccak256` hex is stored as `pinataMetadata.name`.
///
/// # Parameters
///
/// * `doc` — the [`AppDataDoc`] to upload.
/// * `ipfs` — the [`Ipfs`] configuration containing Pinata credentials and optional gateway URIs.
///
/// # Returns
///
/// The IPFS CID hash string returned by Pinata on success.
///
/// # Errors
///
/// Returns [`CowError::AppData`] when no Pinata credentials are configured,
/// [`CowError::Http`] on transport failure, or [`CowError::Api`] when Pinata
/// returns a non-2xx status code.
///
/// # Example
///
/// ```no_run
/// use cow_rs::app_data::{AppDataDoc, Ipfs, upload_app_data_to_pinata};
///
/// # async fn example() -> Result<(), cow_rs::error::CowError> {
/// let doc = AppDataDoc::new("CoW Swap");
/// let ipfs = Ipfs::default().with_pinata("my-api-key", "my-api-secret");
/// let cid = upload_app_data_to_pinata(&doc, &ipfs).await?;
/// assert!(!cid.is_empty());
/// # Ok(())
/// # }
/// ```
pub async fn upload_app_data_to_pinata(doc: &AppDataDoc, ipfs: &Ipfs) -> Result<String, CowError> {
    let api_key = ipfs
        .pinata_api_key
        .as_deref()
        .ok_or_else(|| CowError::AppData("pinata_api_key is required for IPFS upload".into()))?;
    let api_secret = ipfs
        .pinata_api_secret
        .as_deref()
        .ok_or_else(|| CowError::AppData("pinata_api_secret is required for IPFS upload".into()))?;

    let info = get_app_data_info(doc)?;
    let write_uri = ipfs.write_uri.as_deref().map_or(DEFAULT_IPFS_WRITE_URI, |s| s);
    let url = format!("{write_uri}/pinning/pinJSONToIPFS");

    let content: serde_json::Value = serde_json::from_str(&info.app_data_content)
        .map_err(|e| CowError::AppData(e.to_string()))?;

    let body = json!({
        "pinataContent": content,
        "pinataOptions": { "cidVersion": 1 },
        "pinataMetadata": { "name": info.app_data_hex }
    });

    let resp = reqwest::Client::new()
        .post(&url)
        .header("pinata_api_key", api_key)
        .header("pinata_secret_api_key", api_secret)
        .json(&body)
        .send()
        .await?;

    let status = resp.status().as_u16();
    let text = resp.text().await?;
    if status != 200 {
        return Err(CowError::Api { status, body: text });
    }

    let pinata: PinataResponse =
        serde_json::from_str(&text).map_err(|e| CowError::AppData(e.to_string()))?;
    Ok(pinata.ipfs_hash)
}

// ── Legacy helpers ───────────────────────────────────────────────────────────

/// Internal helper for deriving [`AppDataInfo`] from either a document or a
/// pre-serialised JSON string, using a pluggable CID derivation function.
///
/// This is the Rust equivalent of `_appDataToCidAux` in the `TypeScript` SDK.
#[allow(
    clippy::type_complexity,
    reason = "mirrors the TypeScript SDK's pluggable CID derivation pattern"
)]
fn app_data_to_cid_aux(
    full_app_data: &str,
    derive_cid: fn(&str) -> Result<String, CowError>,
) -> Result<AppDataInfo, CowError> {
    let cid = derive_cid(full_app_data)?;
    let app_data_hex = extract_digest(&cid)?;

    if app_data_hex.is_empty() {
        return Err(CowError::AppData(format!(
            "Could not extract appDataHex from calculated cid {cid}"
        )));
    }

    Ok(AppDataInfo { cid, app_data_content: full_app_data.to_owned(), app_data_hex })
}

/// Internal CID derivation using the legacy `sha2-256` / `dag-pb` method.
///
/// **Note**: The original `TypeScript` SDK used `ipfs-only-hash` with `CIDv0`. This Rust
/// implementation uses `keccak256` as the hash but wraps it in the legacy CID
/// prefix for structural compatibility. True legacy CID reproduction would
/// require an `sha2-256` IPFS chunker which is not included.
///
/// This is the Rust equivalent of `_appDataToCidLegacy` in the `TypeScript` SDK.
#[allow(deprecated, reason = "wraps the deprecated legacy CID function intentionally")]
fn app_data_to_cid_legacy(full_app_data_json: &str) -> Result<String, CowError> {
    let hash = alloy_primitives::keccak256(full_app_data_json.as_bytes());
    let app_data_hex = format!("0x{}", alloy_primitives::hex::encode(hash.as_slice()));
    super::cid::app_data_hex_to_cid_legacy(&app_data_hex)
}

/// Derive [`AppDataInfo`] using the legacy method.
///
/// Uses `JSON.stringify`-equivalent serialisation (plain `serde_json::to_string`) and
/// legacy CID encoding for backwards compatibility.
///
/// # Errors
///
/// Returns [`CowError::AppData`] on serialisation or CID failure.
#[deprecated(
    note = "Use get_app_data_info instead — legacy CID encoding is no longer used by CoW Protocol"
)]
pub fn get_app_data_info_legacy(doc: &AppDataDoc) -> Result<AppDataInfo, CowError> {
    // Legacy mode uses plain JSON.stringify (non-deterministic key order)
    let full_app_data = serde_json::to_string(doc).map_err(|e| CowError::AppData(e.to_string()))?;
    app_data_to_cid_aux(&full_app_data, app_data_to_cid_legacy)
}

/// Internal helper that fetches a document from IPFS via a pluggable
/// hex-to-CID conversion function.
///
/// This is the Rust equivalent of `_fetchDocFromCidAux` in the `TypeScript` SDK.
#[allow(
    clippy::type_complexity,
    reason = "mirrors the TypeScript SDK's pluggable hex-to-CID conversion pattern"
)]
async fn fetch_doc_from_cid_aux(
    hex_to_cid: fn(&str) -> Result<String, CowError>,
    app_data_hex: &str,
    ipfs_uri: Option<&str>,
) -> Result<AppDataDoc, CowError> {
    let cid = hex_to_cid(app_data_hex).map_err(|e| {
        CowError::AppData(format!("Error decoding AppData: appDataHex={app_data_hex}, message={e}"))
    })?;

    if cid.is_empty() {
        return Err(CowError::AppData("Error getting serialized CID".into()));
    }

    fetch_doc_from_cid(&cid, ipfs_uri).await
}

/// Fetch an [`AppDataDoc`] from IPFS using the legacy CID derivation method.
///
/// Converts `app_data_hex` to a CID using the legacy `dag-pb` / `sha2-256`
/// encoding, then fetches the content from IPFS.
///
/// # Errors
///
/// Returns [`CowError::AppData`], [`CowError::Http`], or [`CowError::Parse`].
#[deprecated(
    note = "Use fetch_doc_from_app_data_hex instead — legacy CID encoding is no longer used by CoW Protocol"
)]
#[allow(
    deprecated,
    reason = "this function is itself deprecated and wraps other deprecated functions"
)]
pub async fn fetch_doc_from_app_data_hex_legacy(
    app_data_hex: &str,
    ipfs_uri: Option<&str>,
) -> Result<AppDataDoc, CowError> {
    fetch_doc_from_cid_aux(super::cid::app_data_hex_to_cid_legacy, app_data_hex, ipfs_uri).await
}

/// Upload an [`AppDataDoc`] to IPFS via Pinata using the legacy method.
///
/// The document is pinned to Pinata, and the resulting CID is used to extract
/// the `appData` hex digest.
///
/// # Errors
///
/// Returns [`CowError::AppData`] when credentials are missing or the CID
/// extraction fails, [`CowError::Http`] on transport failure, or
/// [`CowError::Api`] on a non-2xx Pinata response.
#[deprecated(
    note = "Use upload_app_data_to_pinata instead — legacy Pinata pinning relied on implicit encoding"
)]
pub async fn upload_metadata_doc_to_ipfs_legacy(
    doc: &AppDataDoc,
    ipfs: &Ipfs,
) -> Result<IpfsUploadResult, CowError> {
    let cid = upload_app_data_to_pinata_legacy(doc, ipfs).await?;
    let app_data = extract_digest(&cid)?;
    Ok(IpfsUploadResult { app_data, cid })
}

/// Result of uploading metadata to IPFS (legacy).
#[derive(Debug, Clone)]
pub struct IpfsUploadResult {
    /// The `appData` hex digest extracted from the CID.
    pub app_data: String,
    /// The IPFS CID of the pinned content.
    pub cid: String,
}

impl fmt::Display for IpfsUploadResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ipfs-upload(cid={}, appData={})", self.cid, self.app_data)
    }
}

/// Internal legacy Pinata upload (pins with default `CIDv0` encoding).
///
/// This is the Rust equivalent of `_pinJsonInPinataIpfs` in the `TypeScript` SDK.
async fn upload_app_data_to_pinata_legacy(
    doc: &AppDataDoc,
    ipfs: &Ipfs,
) -> Result<String, CowError> {
    let api_key = ipfs
        .pinata_api_key
        .as_deref()
        .ok_or_else(|| CowError::AppData("You need to pass IPFS api credentials.".into()))?;
    let api_secret = ipfs
        .pinata_api_secret
        .as_deref()
        .ok_or_else(|| CowError::AppData("You need to pass IPFS api credentials.".into()))?;

    if api_key.is_empty() || api_secret.is_empty() {
        return Err(CowError::AppData("You need to pass IPFS api credentials.".into()));
    }

    let content: serde_json::Value =
        serde_json::to_value(doc).map_err(|e| CowError::AppData(e.to_string()))?;

    let body = json!({
        "pinataContent": content,
        "pinataMetadata": { "name": "appData" }
    });

    let write_uri = ipfs.write_uri.as_deref().map_or(DEFAULT_IPFS_WRITE_URI, |s| s);
    let url = format!("{write_uri}/pinning/pinJSONToIPFS");

    let resp = reqwest::Client::new()
        .post(&url)
        .header("Content-Type", "application/json")
        .header("pinata_api_key", api_key)
        .header("pinata_secret_api_key", api_secret)
        .json(&body)
        .send()
        .await?;

    let status = resp.status().as_u16();
    let text = resp.text().await?;
    if status != 200 {
        return Err(CowError::Api { status, body: text });
    }

    let pinata: PinataResponse =
        serde_json::from_str(&text).map_err(|e| CowError::AppData(e.to_string()))?;
    Ok(pinata.ipfs_hash)
}

// ── Schema helpers ──────────────────────────────────────────────────────────

/// Known app-data schema versions.
const KNOWN_SCHEMA_VERSIONS: &[&str] = &["0.7.0", "1.3.0"];

/// Import (look up) an app-data schema by version string.
///
/// In the `TypeScript` SDK this dynamically imports a JSON schema file. In
/// Rust, supported schema versions are compiled-in. Returns a placeholder
/// [`AppDataDoc`] with the `version` field set to indicate which schema was
/// requested.
///
/// Currently known versions: `"0.7.0"`, `"1.3.0"`.
///
/// Mirrors `importSchema` from the `@cowprotocol/app-data` `TypeScript`
/// package.
///
/// # Parameters
///
/// * `version` — semver string (e.g. `"1.3.0"`).
///
/// # Returns
///
/// An [`AppDataDoc`] with the requested version and empty metadata.
///
/// # Errors
///
/// Returns [`CowError::AppData`] if `version` is not a valid semver string
/// or is not a known schema version.
///
/// # Example
///
/// ```
/// use cow_rs::app_data::import_schema;
///
/// let doc = import_schema("1.3.0").unwrap();
/// assert_eq!(doc.version, "1.3.0");
///
/// assert!(import_schema("99.0.0").is_err()); // unknown version
/// assert!(import_schema("not-semver").is_err());
/// ```
pub fn import_schema(version: &str) -> Result<AppDataDoc, CowError> {
    // Validate semver format
    let re_parts: Vec<&str> = version.split('.').collect();
    if re_parts.len() != 3 || re_parts.iter().any(|p| p.parse::<u32>().is_err()) {
        return Err(CowError::AppData(format!("AppData version {version} is not a valid version")));
    }

    if !KNOWN_SCHEMA_VERSIONS.contains(&version) {
        return Err(CowError::AppData(format!("AppData version {version} doesn't exist")));
    }

    Ok(AppDataDoc {
        version: version.to_owned(),
        app_code: None,
        environment: None,
        metadata: Metadata::default(),
    })
}

/// Get the app-data schema for a given version.
///
/// Wraps [`import_schema`] and converts errors to [`CowError::AppData`].
///
/// Mirrors `getAppDataSchema` from the `@cowprotocol/app-data` `TypeScript`
/// package.
///
/// # Parameters
///
/// * `version` — semver string (e.g. `"1.3.0"`).
///
/// # Returns
///
/// An [`AppDataDoc`] placeholder with the requested version.
///
/// # Errors
///
/// Returns [`CowError::AppData`] when the version doesn't exist or is not
/// valid semver.
pub fn get_app_data_schema(version: &str) -> Result<AppDataDoc, CowError> {
    import_schema(version).map_err(|e| CowError::AppData(format!("{e}")))
}

// ── MetadataApi ───────────────────────────────────────────────────────────────

/// High-level facade mirroring `MetadataApi` from the `TypeScript` SDK.
///
/// All operations are available as free functions in this module;
/// `MetadataApi` groups them under a single type that carries an optional
/// [`Ipfs`] configuration, so callers do not have to thread IPFS settings
/// through every call.
///
/// # Typical workflow
///
/// ```rust
/// use cow_rs::app_data::{Ipfs, MetadataApi};
///
/// // 1. Create the API (with optional IPFS config).
/// let api = MetadataApi::new();
///
/// // 2. Build an app-data document.
/// let doc = api.generate_app_data_doc("MyDApp");
///
/// // 3. Validate it.
/// let result = api.validate_app_data_doc(&doc);
/// assert!(result.is_valid());
///
/// // 4. Derive the hash + CID.
/// let info = api.get_app_data_info(&doc).unwrap();
/// assert!(info.app_data_hex.starts_with("0x"));
/// ```
#[derive(Debug, Clone, Default)]
pub struct MetadataApi {
    /// Optional IPFS configuration.
    pub ipfs: Ipfs,
}

impl MetadataApi {
    /// Create a new [`MetadataApi`] with default IPFS settings.
    ///
    /// Uses [`DEFAULT_IPFS_READ_URI`] for fetching and
    /// [`DEFAULT_IPFS_WRITE_URI`] for uploads. No Pinata credentials are
    /// configured — set them via [`with_ipfs`](Self::with_ipfs) if you need
    /// upload capability.
    ///
    /// # Returns
    ///
    /// A new [`MetadataApi`] with default [`Ipfs`] configuration.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a [`MetadataApi`] with custom IPFS configuration.
    ///
    /// # Parameters
    ///
    /// * `ipfs` — the [`Ipfs`] settings (gateway URIs, Pinata credentials).
    ///
    /// # Returns
    ///
    /// A new [`MetadataApi`] using the given configuration.
    ///
    /// # Example
    ///
    /// ```
    /// use cow_rs::app_data::{Ipfs, MetadataApi};
    ///
    /// let api = MetadataApi::with_ipfs(
    ///     Ipfs::default().with_read_uri("https://my-gateway.io/ipfs").with_pinata("key", "secret"),
    /// );
    /// ```
    #[must_use]
    pub const fn with_ipfs(ipfs: Ipfs) -> Self {
        Self { ipfs }
    }

    /// Generate a minimal [`AppDataDoc`] for `app_code`.
    ///
    /// # Example
    ///
    /// ```
    /// use cow_rs::app_data::MetadataApi;
    ///
    /// let api = MetadataApi::new();
    /// let doc = api.generate_app_data_doc("CoW Swap");
    /// assert_eq!(doc.app_code.as_deref(), Some("CoW Swap"));
    /// ```
    #[must_use]
    pub fn generate_app_data_doc(&self, app_code: impl Into<String>) -> AppDataDoc {
        AppDataDoc::new(app_code)
    }

    /// Validate an [`AppDataDoc`].
    ///
    /// # Example
    ///
    /// ```
    /// use cow_rs::app_data::{AppDataDoc, MetadataApi};
    ///
    /// let api = MetadataApi::new();
    /// let doc = AppDataDoc::new("CoW Swap");
    /// let result = api.validate_app_data_doc(&doc);
    /// assert!(result.is_valid());
    /// ```
    #[must_use]
    pub fn validate_app_data_doc(&self, doc: &AppDataDoc) -> ValidationResult {
        validate_app_data_doc(doc)
    }

    /// Compute the `keccak256` hash of `doc` as a [`B256`].
    ///
    /// Delegates to [`appdata_hex`]. The document
    /// is serialised to deterministic JSON before hashing.
    ///
    /// # Parameters
    ///
    /// * `doc` — the [`AppDataDoc`] to hash.
    ///
    /// # Returns
    ///
    /// A 32-byte [`B256`] digest.
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`] on serialisation failure.
    pub fn appdata_hex(&self, doc: &AppDataDoc) -> Result<B256, CowError> {
        appdata_hex(doc)
    }

    /// Derive the full [`AppDataInfo`] (JSON content, hex hash, CID) from
    /// `doc`.
    ///
    /// Delegates to [`get_app_data_info`]. This is the most common method
    /// for obtaining everything needed to submit an order and pin data on
    /// IPFS.
    ///
    /// # Parameters
    ///
    /// * `doc` — the [`AppDataDoc`] to process.
    ///
    /// # Returns
    ///
    /// An [`AppDataInfo`] with canonical JSON, hex hash, and CID.
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`].
    ///
    /// # Example
    ///
    /// ```
    /// use cow_rs::app_data::{AppDataDoc, MetadataApi};
    ///
    /// let api = MetadataApi::new();
    /// let doc = AppDataDoc::new("CoW Swap");
    /// let info = api.get_app_data_info(&doc)?;
    /// assert!(info.app_data_hex.starts_with("0x"));
    /// # Ok::<(), cow_rs::error::CowError>(())
    /// ```
    pub fn get_app_data_info(&self, doc: &AppDataDoc) -> Result<AppDataInfo, CowError> {
        get_app_data_info(doc)
    }

    /// Derive [`AppDataInfo`] from a pre-serialised JSON string.
    ///
    /// Hashes `json` directly without re-serialising, preserving the exact
    /// byte sequence as the canonical `keccak256` pre-image.
    ///
    /// # Parameters
    ///
    /// * `json` — the canonical JSON string.
    ///
    /// # Returns
    ///
    /// An [`AppDataInfo`] where `app_data_content` is `json` verbatim.
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`].
    pub fn get_app_data_info_from_str(&self, json: &str) -> Result<AppDataInfo, CowError> {
        get_app_data_info_from_str(json)
    }

    /// Convert `app_data_hex` to a `CIDv1` base16 string.
    ///
    /// Delegates to
    /// [`appdata_hex_to_cid`].
    ///
    /// # Parameters
    ///
    /// * `app_data_hex` — the `appData` hex value, with or without `0x`.
    ///
    /// # Returns
    ///
    /// A base16 `CIDv1` string (prefix `f`).
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`].
    pub fn app_data_hex_to_cid(&self, app_data_hex: &str) -> Result<String, CowError> {
        appdata_hex_to_cid(app_data_hex)
    }

    /// Extract the `appData` hex digest from a `CIDv1` string.
    ///
    /// Delegates to
    /// [`cid_to_appdata_hex`].
    ///
    /// # Parameters
    ///
    /// * `cid` — a base16 multibase CID string.
    ///
    /// # Returns
    ///
    /// A `0x`-prefixed hex string of the 32-byte digest.
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`].
    pub fn cid_to_app_data_hex(&self, cid: &str) -> Result<String, CowError> {
        cid_to_appdata_hex(cid)
    }

    /// Fetch an [`AppDataDoc`] from IPFS by `CIDv1`.
    ///
    /// Uses the configured `ipfs.read_uri` or [`DEFAULT_IPFS_READ_URI`]
    /// when no custom gateway is set.
    ///
    /// # Parameters
    ///
    /// * `cid` — the `CIDv1` base16 string identifying the document on IPFS.
    ///
    /// # Returns
    ///
    /// The deserialised [`AppDataDoc`].
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::Http`] on network failure or
    /// [`CowError::Parse`] if the response is not valid JSON.
    pub async fn fetch_doc_from_cid(&self, cid: &str) -> Result<AppDataDoc, CowError> {
        let uri = self.ipfs.read_uri.as_deref();
        fetch_doc_from_cid(cid, uri).await
    }

    /// Fetch an [`AppDataDoc`] from IPFS by `appData` hex value.
    ///
    /// Converts `app_data_hex` to a `CIDv1`, then fetches the document
    /// from the configured IPFS gateway.
    ///
    /// # Parameters
    ///
    /// * `app_data_hex` — the `0x`-prefixed 32-byte hex value.
    ///
    /// # Returns
    ///
    /// The deserialised [`AppDataDoc`].
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`], [`CowError::Http`], or
    /// [`CowError::Parse`].
    pub async fn fetch_doc_from_app_data_hex(
        &self,
        app_data_hex: &str,
    ) -> Result<AppDataDoc, CowError> {
        let uri = self.ipfs.read_uri.as_deref();
        fetch_doc_from_app_data_hex(app_data_hex, uri).await
    }

    /// Upload `doc` to IPFS via the Pinata pinning service.
    ///
    /// The document is serialised to deterministic JSON, hashed, and
    /// pinned to Pinata. Requires [`Ipfs::pinata_api_key`] and
    /// [`Ipfs::pinata_api_secret`] to be set on the configured [`Ipfs`]
    /// instance.
    ///
    /// # Parameters
    ///
    /// * `doc` — the [`AppDataDoc`] to upload.
    ///
    /// # Returns
    ///
    /// The IPFS `CIDv1` hash string of the pinned content.
    ///
    /// # Errors
    ///
    /// Returns [`CowError::AppData`] when credentials are missing,
    /// [`CowError::Http`] on transport failure, or [`CowError::Api`] on a
    /// non-2xx Pinata response.
    pub async fn upload_app_data(&self, doc: &AppDataDoc) -> Result<String, CowError> {
        upload_app_data_to_pinata(doc, &self.ipfs).await
    }

    /// Derive [`AppDataInfo`] using the legacy CID encoding method.
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`].
    #[deprecated(note = "Use get_app_data_info instead")]
    #[allow(
        deprecated,
        reason = "this method is itself deprecated and delegates to a deprecated function"
    )]
    pub fn get_app_data_info_legacy(&self, doc: &AppDataDoc) -> Result<AppDataInfo, CowError> {
        get_app_data_info_legacy(doc)
    }

    /// Fetch an [`AppDataDoc`] from IPFS using the legacy CID derivation.
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`], [`CowError::Http`], or [`CowError::Parse`].
    #[deprecated(note = "Use fetch_doc_from_app_data_hex instead")]
    #[allow(
        deprecated,
        reason = "this method is itself deprecated and delegates to a deprecated function"
    )]
    pub async fn fetch_doc_from_app_data_hex_legacy(
        &self,
        app_data_hex: &str,
    ) -> Result<AppDataDoc, CowError> {
        let uri = self.ipfs.read_uri.as_deref();
        fetch_doc_from_app_data_hex_legacy(app_data_hex, uri).await
    }

    /// Upload `doc` to IPFS via Pinata using the legacy method.
    ///
    /// # Errors
    ///
    /// Returns [`CowError::AppData`], [`CowError::Http`], or [`CowError::Api`].
    #[deprecated(note = "Use upload_app_data instead")]
    #[allow(
        deprecated,
        reason = "this method is itself deprecated and delegates to a deprecated function"
    )]
    pub async fn upload_metadata_doc_to_ipfs_legacy(
        &self,
        doc: &AppDataDoc,
    ) -> Result<IpfsUploadResult, CowError> {
        upload_metadata_doc_to_ipfs_legacy(doc, &self.ipfs).await
    }

    /// Get the app-data schema for a given version.
    ///
    /// Delegates to [`get_app_data_schema`]. Currently known versions:
    /// `"0.7.0"`, `"1.3.0"`.
    ///
    /// # Parameters
    ///
    /// * `version` — semver string (e.g. `"1.3.0"`).
    ///
    /// # Returns
    ///
    /// An [`AppDataDoc`] placeholder with the requested version.
    ///
    /// # Errors
    ///
    /// Returns [`CowError::AppData`] when the version doesn't exist.
    pub fn get_app_data_schema(&self, version: &str) -> Result<AppDataDoc, CowError> {
        get_app_data_schema(version)
    }

    /// Import a schema by version string.
    ///
    /// Delegates to [`import_schema`].
    ///
    /// # Parameters
    ///
    /// * `version` — semver string.
    ///
    /// # Returns
    ///
    /// An [`AppDataDoc`] placeholder with the requested version.
    ///
    /// # Errors
    ///
    /// Returns [`CowError::AppData`] if the version is invalid or unknown.
    pub fn import_schema(&self, version: &str) -> Result<AppDataDoc, CowError> {
        import_schema(version)
    }

    /// Convert `app_data_hex` to a CID using the legacy method.
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`].
    #[deprecated(note = "Use app_data_hex_to_cid instead")]
    #[allow(
        deprecated,
        reason = "this method is itself deprecated and delegates to a deprecated function"
    )]
    pub fn app_data_hex_to_cid_legacy(&self, app_data_hex: &str) -> Result<String, CowError> {
        super::cid::app_data_hex_to_cid_legacy(app_data_hex)
    }

    /// Parse a CID string into its constituent [`CidComponents`](super::cid::CidComponents).
    ///
    /// Delegates to [`parse_cid`](super::cid::parse_cid). Only base16
    /// CIDs (prefix `f` or `F`) are supported.
    ///
    /// # Parameters
    ///
    /// * `ipfs_hash` — a multibase-encoded CID string.
    ///
    /// # Returns
    ///
    /// A [`CidComponents`](super::cid::CidComponents) with version, codec,
    /// hash function, hash length, and raw digest.
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`].
    pub fn parse_cid(&self, ipfs_hash: &str) -> Result<super::cid::CidComponents, CowError> {
        super::cid::parse_cid(ipfs_hash)
    }

    /// Decode raw CID bytes into their constituent [`CidComponents`](super::cid::CidComponents).
    ///
    /// Delegates to [`decode_cid`](super::cid::decode_cid).
    ///
    /// # Parameters
    ///
    /// * `bytes` — raw CID bytes (`[version, codec, hash_fn, hash_len, ...digest]`).
    ///
    /// # Returns
    ///
    /// A [`CidComponents`](super::cid::CidComponents) with the parsed fields.
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`] if the slice is too short.
    pub fn decode_cid(&self, bytes: &[u8]) -> Result<super::cid::CidComponents, CowError> {
        super::cid::decode_cid(bytes)
    }

    /// Extract the multihash digest from a CID string as `0x`-prefixed hex.
    ///
    /// Delegates to [`extract_digest`].
    ///
    /// # Parameters
    ///
    /// * `cid` — a base16 multibase CID string.
    ///
    /// # Returns
    ///
    /// A `0x`-prefixed hex string of the raw digest bytes.
    ///
    /// # Errors
    ///
    /// Propagates [`CowError::AppData`].
    pub fn extract_digest(&self, cid: &str) -> Result<String, CowError> {
        super::cid::extract_digest(cid)
    }
}

impl fmt::Display for MetadataApi {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("metadata-api")
    }
}