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
//! Interpretation of the TII params JSON schema into [`ParamType`] kinds.
//!
//! A TII embeds, for each transaction, a JSON schema describing its parameters
//! (and an optional environment schema). This module turns those schema nodes —
//! every shape `tx3c` can emit, see the SDK spec's `api-surface/args.md` — into
//! the [`ParamType`] model the rest of the SDK works with. Interpretation never
//! fails: any shape it does not recognize becomes [`ParamType::Unknown`].

use serde_json::Value;
use std::collections::HashMap;

/// Map of parameter names to their types.
///
/// Used to represent the complete set of parameters required for a transaction.
pub type ParamMap = HashMap<String, ParamType>;

/// Builds a parameter-type map from a JSON schema's `properties`. Never fails:
/// unrecognized property schemas yield [`ParamType::Unknown`]. `components` is the
/// TII's `components.schemas` table, used to resolve `#/components/schemas/<Name>`
/// refs to user-defined record / variant types.
pub(super) fn params_from_schema(schema: &Value, components: &HashMap<String, Value>) -> ParamMap {
    let mut params = ParamMap::new();

    if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
        for (key, value) in properties {
            params.insert(key.clone(), ParamType::from_json_schema(value, components));
        }
    }

    params
}

/// Type of a transaction parameter.
///
/// This enum represents the various types that transaction parameters can have,
/// including primitives, compound types, and references to TX3 core types. It is
/// built from the TII params JSON schema by [`ParamType::from_json_schema`], which
/// never fails — any shape it does not recognize becomes [`ParamType::Unknown`].
#[derive(Debug, Clone)]
pub enum ParamType {
    /// Byte array type (hex-encoded).
    Bytes,
    /// Integer type (signed or unsigned).
    Integer,
    /// Boolean type.
    Boolean,
    /// Unit type (`{ "type": "null" }`).
    Unit,
    /// UTXO reference in format `0x[64hex]#[index]`.
    UtxoRef,
    /// Bech32-encoded blockchain address.
    Address,
    /// A resolved UTxO object.
    Utxo,
    /// An asset identified at runtime by policy and name.
    AnyAsset,
    /// Homogeneous, variable-length sequence (`array` + `items`).
    List(Box<ParamType>),
    /// Fixed-length, positionally-typed sequence (`array` + `prefixItems`).
    Tuple(Vec<ParamType>),
    /// String-keyed homogeneous map (`object` + `additionalProperties`).
    Map(Box<ParamType>),
    /// User-defined record (`object` + `properties`), `(field name, type)` in
    /// **declared order** (the schema's `required` array, which `tx3c` emits in
    /// source order — `properties` is alphabetized and must not drive field
    /// order). Encoding maps the user's by-name object to positional fields.
    Record(Vec<(String, ParamType)>),
    /// User-defined tagged union (`oneOf`), externally tagged.
    Variant(Vec<VariantCase>),
    /// A schema shape that could not be interpreted; carries the raw schema.
    Unknown(Value),
}

/// One case of a [`ParamType::Variant`].
#[derive(Debug, Clone)]
pub struct VariantCase {
    /// The case tag (the single `required` key of the externally-tagged object).
    pub tag: String,
    /// The case payload (typically a [`ParamType::Record`]).
    pub fields: Box<ParamType>,
}

impl ParamType {
    /// Looks up a field type by name in a [`ParamType::Record`]; `None` for any
    /// other kind or an absent field.
    pub fn field(&self, name: &str) -> Option<&ParamType> {
        match self {
            ParamType::Record(fields) => {
                fields.iter().find(|(k, _)| k == name).map(|(_, ty)| ty)
            }
            _ => None,
        }
    }

    /// Maps a built-in core `$ref` to its kind by trailing name, so both the
    /// canonical `…/tii#/$defs/<Name>` and legacy `…/core#<Name>` forms resolve.
    fn core_ref_type(reference: &str) -> Option<ParamType> {
        let name = reference.rsplit(['#', '/']).next().unwrap_or("");
        match name {
            "Bytes" => Some(ParamType::Bytes),
            "Address" => Some(ParamType::Address),
            "UtxoRef" => Some(ParamType::UtxoRef),
            "Utxo" => Some(ParamType::Utxo),
            "AnyAsset" => Some(ParamType::AnyAsset),
            _ => None,
        }
    }

    /// Resolves a `$ref` node: `#/components/schemas/<Name>` against the TII's
    /// `components` table (recursing into the resolved schema), otherwise a
    /// built-in core ref. An unresolved ref becomes [`ParamType::Unknown`].
    fn ref_type(schema: &Value, reference: &str, components: &HashMap<String, Value>) -> ParamType {
        if let Some(name) = reference.strip_prefix("#/components/schemas/") {
            return match components.get(name) {
                Some(resolved) => Self::from_json_schema(resolved, components),
                None => ParamType::Unknown(schema.clone()),
            };
        }

        Self::core_ref_type(reference).unwrap_or_else(|| ParamType::Unknown(schema.clone()))
    }

    /// Maps a `oneOf` array to a [`ParamType::Variant`] of externally-tagged cases.
    fn variant_type(cases: &[Value], components: &HashMap<String, Value>) -> ParamType {
        ParamType::Variant(
            cases
                .iter()
                .map(|case| Self::variant_case(case, components))
                .collect(),
        )
    }

    /// Interprets one externally-tagged `oneOf` branch into a [`VariantCase`].
    fn variant_case(case: &Value, components: &HashMap<String, Value>) -> VariantCase {
        let tag = case
            .get("required")
            .and_then(Value::as_array)
            .and_then(|r| r.first())
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string();

        let fields = case
            .get("properties")
            .and_then(Value::as_object)
            .and_then(|props| props.get(&tag))
            .map(|fields| Self::from_json_schema(fields, components))
            .unwrap_or_else(|| ParamType::Unknown(case.clone()));

        VariantCase {
            tag,
            fields: Box::new(fields),
        }
    }

    /// Maps an `array` schema: `prefixItems` → [`ParamType::Tuple`], `items` →
    /// [`ParamType::List`]. An array carrying neither becomes [`ParamType::Unknown`].
    fn array_type(schema: &Value, components: &HashMap<String, Value>) -> ParamType {
        if let Some(prefix) = schema.get("prefixItems").and_then(Value::as_array) {
            ParamType::Tuple(
                prefix
                    .iter()
                    .map(|el| Self::from_json_schema(el, components))
                    .collect(),
            )
        } else if let Some(items) = schema.get("items").filter(|i| i.is_object()) {
            ParamType::List(Box::new(Self::from_json_schema(items, components)))
        } else {
            ParamType::Unknown(schema.clone())
        }
    }

    /// Maps an `object` schema: `additionalProperties` → [`ParamType::Map`],
    /// `properties` → [`ParamType::Record`]. Neither present → [`ParamType::Unknown`].
    fn object_type(schema: &Value, components: &HashMap<String, Value>) -> ParamType {
        if let Some(value) = schema.get("additionalProperties").filter(|v| v.is_object()) {
            ParamType::Map(Box::new(Self::from_json_schema(value, components)))
        } else if let Some(props) = schema.get("properties").and_then(Value::as_object) {
            ParamType::Record(Self::record_fields(schema, props, components))
        } else {
            ParamType::Unknown(schema.clone())
        }
    }

    /// Builds record fields in declared order: the `required` array first (source
    /// order, as `tx3c` emits), then any remaining (alphabetized) `properties`.
    fn record_fields(
        schema: &Value,
        props: &serde_json::Map<String, Value>,
        components: &HashMap<String, Value>,
    ) -> Vec<(String, ParamType)> {
        let mut fields = Vec::with_capacity(props.len());
        let mut seen = std::collections::HashSet::new();

        if let Some(required) = schema.get("required").and_then(Value::as_array) {
            for name in required.iter().filter_map(Value::as_str) {
                if let Some(field_schema) = props.get(name) {
                    fields.push((name.to_string(), Self::from_json_schema(field_schema, components)));
                    seen.insert(name.to_string());
                }
            }
        }

        for (k, v) in props {
            if !seen.contains(k) {
                fields.push((k.clone(), Self::from_json_schema(v, components)));
            }
        }

        fields
    }

    /// Creates a parameter type from a JSON schema node.
    ///
    /// Interprets every shape `tx3c` can emit (see the SDK spec's
    /// `api-surface/args.md`). It never fails: an unrecognized shape — including a
    /// bare `string`, an unresolved object, or an unknown `$ref` — becomes
    /// [`ParamType::Unknown`] carrying the raw schema.
    ///
    /// # Arguments
    ///
    /// * `schema` - The JSON schema node to interpret
    /// * `components` - The TII's `components.schemas` table, used to resolve
    ///   `#/components/schemas/<Name>` references to user-defined types
    pub fn from_json_schema(schema: &Value, components: &HashMap<String, Value>) -> ParamType {
        let Some(obj) = schema.as_object() else {
            return ParamType::Unknown(schema.clone());
        };

        if let Some(reference) = obj.get("$ref").and_then(Value::as_str) {
            return Self::ref_type(schema, reference, components);
        }

        if let Some(cases) = obj.get("oneOf").and_then(Value::as_array) {
            return Self::variant_type(cases, components);
        }

        match obj.get("type").and_then(Value::as_str) {
            Some("integer") => ParamType::Integer,
            Some("boolean") => ParamType::Boolean,
            Some("null") => ParamType::Unit,
            Some("array") => Self::array_type(schema, components),
            Some("object") => Self::object_type(schema, components),
            _ => ParamType::Unknown(schema.clone()),
        }
    }
}

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

    fn pt(schema: serde_json::Value) -> ParamType {
        ParamType::from_json_schema(&schema, &HashMap::new())
    }

    #[test]
    fn maps_primitives_and_unit() {
        assert!(matches!(pt(json!({"type": "integer"})), ParamType::Integer));
        assert!(matches!(pt(json!({"type": "boolean"})), ParamType::Boolean));
        assert!(matches!(pt(json!({"type": "null"})), ParamType::Unit));
    }

    #[test]
    fn maps_core_refs_in_both_url_forms() {
        for prefix in [
            "https://tx3.land/specs/v1beta0/tii#/$defs",
            "https://tx3.land/specs/v1beta0/core#",
        ] {
            // the legacy form has no trailing slash before the name; the canonical
            // form does — the trailing-name matcher handles both.
            let join = |name: &str| {
                if prefix.ends_with('#') {
                    format!("{prefix}{name}")
                } else {
                    format!("{prefix}/{name}")
                }
            };
            assert!(matches!(pt(json!({"$ref": join("Bytes")})), ParamType::Bytes));
            assert!(matches!(
                pt(json!({"$ref": join("Address")})),
                ParamType::Address
            ));
            assert!(matches!(
                pt(json!({"$ref": join("UtxoRef")})),
                ParamType::UtxoRef
            ));
            assert!(matches!(pt(json!({"$ref": join("Utxo")})), ParamType::Utxo));
            assert!(matches!(
                pt(json!({"$ref": join("AnyAsset")})),
                ParamType::AnyAsset
            ));
        }
    }

    #[test]
    fn maps_list_and_nested_list() {
        match pt(json!({"type": "array", "items": {"type": "integer"}})) {
            ParamType::List(inner) => assert!(matches!(*inner, ParamType::Integer)),
            other => panic!("expected list, got {other:?}"),
        }
        match pt(json!({"type": "array", "items": {"type": "array", "items": {"type": "boolean"}}})) {
            ParamType::List(inner) => match *inner {
                ParamType::List(deep) => assert!(matches!(*deep, ParamType::Boolean)),
                other => panic!("expected list(list), got {other:?}"),
            },
            other => panic!("expected list, got {other:?}"),
        }
    }

    #[test]
    fn maps_tuple_with_prefix_items() {
        let schema = json!({
            "type": "array",
            "prefixItems": [
                {"type": "integer"},
                {"$ref": "https://tx3.land/specs/v1beta0/tii#/$defs/Bytes"}
            ],
            "items": false
        });
        match pt(schema) {
            ParamType::Tuple(els) => {
                assert_eq!(els.len(), 2);
                assert!(matches!(els[0], ParamType::Integer));
                assert!(matches!(els[1], ParamType::Bytes));
            }
            other => panic!("expected tuple, got {other:?}"),
        }
    }

    #[test]
    fn maps_map_via_additional_properties() {
        match pt(json!({"type": "object", "additionalProperties": {"type": "integer"}})) {
            ParamType::Map(value) => assert!(matches!(*value, ParamType::Integer)),
            other => panic!("expected map, got {other:?}"),
        }
    }

    #[test]
    fn maps_record_via_properties() {
        let schema = json!({
            "type": "object",
            "properties": {"price": {"type": "integer"}, "live": {"type": "boolean"}},
            "required": ["price", "live"]
        });
        match pt(schema) {
            rec @ ParamType::Record(_) => {
                assert!(matches!(rec.field("price"), Some(ParamType::Integer)));
                assert!(matches!(rec.field("live"), Some(ParamType::Boolean)));
            }
            other => panic!("expected record, got {other:?}"),
        }
    }

    #[test]
    fn maps_variant_via_one_of() {
        let schema = json!({
            "oneOf": [
                {"type": "object", "additionalProperties": false, "required": ["Buy"],
                 "properties": {"Buy": {"type": "object", "properties": {}, "required": []}}},
                {"type": "object", "additionalProperties": false, "required": ["Sell"],
                 "properties": {"Sell": {"type": "object", "properties": {"price": {"type": "integer"}}, "required": ["price"]}}}
            ]
        });
        match pt(schema) {
            ParamType::Variant(cases) => {
                assert_eq!(cases.len(), 2);
                assert_eq!(cases[0].tag, "Buy");
                assert_eq!(cases[1].tag, "Sell");
                let sell_fields = &*cases[1].fields;
                assert!(matches!(sell_fields, ParamType::Record(_)));
                assert!(matches!(
                    sell_fields.field("price"),
                    Some(ParamType::Integer)
                ));
            }
            other => panic!("expected variant, got {other:?}"),
        }
    }

    #[test]
    fn resolves_component_refs_recursively() {
        let mut components = HashMap::new();
        components.insert(
            "AssetClass".to_string(),
            json!({
                "type": "object",
                "properties": {"policy": {"$ref": "https://tx3.land/specs/v1beta0/tii#/$defs/Bytes"}},
                "required": ["policy"]
            }),
        );
        let schema = json!({"$ref": "#/components/schemas/AssetClass"});
        match ParamType::from_json_schema(&schema, &components) {
            rec @ ParamType::Record(_) => assert!(matches!(rec.field("policy"), Some(ParamType::Bytes))),
            other => panic!("expected record, got {other:?}"),
        }
        // Missing component → Unknown, never panics.
        let missing = json!({"$ref": "#/components/schemas/Nope"});
        assert!(matches!(
            ParamType::from_json_schema(&missing, &components),
            ParamType::Unknown(_)
        ));
    }

    #[test]
    fn unrecognized_shapes_fall_back_to_unknown() {
        assert!(matches!(pt(json!({"type": "string"})), ParamType::Unknown(_)));
        assert!(matches!(pt(json!({})), ParamType::Unknown(_)));
        assert!(matches!(pt(json!("nonsense")), ParamType::Unknown(_)));
        assert!(matches!(
            pt(json!({"$ref": "https://example.com/Weird"})),
            ParamType::Unknown(_)
        ));
        assert!(matches!(
            pt(json!({"type": "array"})),
            ParamType::Unknown(_)
        ));
    }
}