clear-signing 0.1.0

ERC-7730 v2 clear signing library: decodes and formats Ethereum calldata and EIP-712 typed data for human-readable display.
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
//! Display configuration types: field formats, visibility rules, and layout groups.

use num_bigint::BigUint;
use serde::{de, Deserialize, Deserializer, Serialize};
use std::collections::HashMap;

/// Top-level display section of a descriptor.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DescriptorDisplay {
    /// Reusable field definitions that can be referenced via `$ref`.
    #[serde(default)]
    pub definitions: HashMap<String, DisplayField>,

    /// Map of format key → display format.
    /// For calldata: key is function signature like `"transfer(address,uint256)"`.
    /// For EIP-712: key is primary type name.
    pub formats: HashMap<String, DisplayFormat>,
}

/// Extract an intent string from a validated intent value.
pub fn intent_as_string(val: &serde_json::Value) -> String {
    match val {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Object(obj) => obj
            .iter()
            .map(|(label, value)| format!("{label}: {}", value.as_str().unwrap_or_default()))
            .collect::<Vec<_>>()
            .join(", "),
        _ => val.to_string(),
    }
}

fn deserialize_intent<'de, D>(deserializer: D) -> Result<Option<serde_json::Value>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
    let Some(value) = value else {
        return Ok(None);
    };

    match &value {
        serde_json::Value::String(_) => Ok(Some(value)),
        serde_json::Value::Object(obj) => {
            for (key, entry) in obj {
                if !entry.is_string() {
                    return Err(de::Error::custom(format!(
                        "intent object value for key '{}' must be a string",
                        key
                    )));
                }
            }
            Ok(Some(value))
        }
        _ => Err(de::Error::custom(
            "intent must be a string or a flat object of string values",
        )),
    }
}

/// A single display format for a function or message type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DisplayFormat {
    /// Optional format identifier (v2).
    #[serde(rename = "$id")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,

    /// Human-readable intent label (string or object per spec).
    #[serde(deserialize_with = "deserialize_intent")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub intent: Option<serde_json::Value>,

    /// Intent with `${path}` or `{name}` template variables for interpolation.
    #[serde(rename = "interpolatedIntent")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interpolated_intent: Option<String>,

    /// Ordered list of fields to display.
    #[serde(default)]
    pub fields: Vec<DisplayField>,

    /// Deprecated in v2 — list of excluded paths.
    #[serde(default)]
    pub excluded: Vec<String>,
}

/// A display field — can be a simple field, a field group, or a reference.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
#[allow(clippy::large_enum_variant)]
pub enum DisplayField {
    /// A reference to a definition: `{ "$ref": "$.display.definitions.foo", "path": "...", ... }`.
    ///
    /// Per ERC-7730 spec, a reference object carries `$ref` plus the field's own
    /// `path`, optional `params` (which override definition params), and `visible`.
    Reference {
        #[serde(rename = "$ref")]
        reference: String,

        /// Path to resolve in decoded arguments (from the referencing field).
        #[serde(skip_serializing_if = "Option::is_none")]
        path: Option<String>,

        /// Params that override/extend the definition's params.
        #[serde(skip_serializing_if = "Option::is_none")]
        params: Option<FormatParams>,

        /// Visibility rule (from the referencing field).
        #[serde(default = "default_visible")]
        visible: VisibleRule,
    },

    /// A grouped set of fields (v2): `{ "fieldGroup": { ... } }`.
    Group {
        #[serde(rename = "fieldGroup")]
        field_group: FieldGroup,
    },

    /// Direct spec group object: `{ "path": "...", "label": "...", "fields": [...] }`.
    Scope {
        #[serde(skip_serializing_if = "Option::is_none")]
        path: Option<String>,

        #[serde(skip_serializing_if = "Option::is_none")]
        label: Option<String>,

        #[serde(default)]
        iteration: Iteration,

        fields: Vec<DisplayField>,
    },

    /// A simple field with path, label, format, etc.
    Simple {
        /// Path to resolve in decoded arguments. Optional when `value` is provided.
        #[serde(skip_serializing_if = "Option::is_none")]
        path: Option<String>,

        label: String,

        /// Literal constant value (alternative to `path`).
        #[serde(skip_serializing_if = "Option::is_none")]
        value: Option<String>,

        #[serde(skip_serializing_if = "Option::is_none")]
        format: Option<FieldFormat>,

        #[serde(skip_serializing_if = "Option::is_none")]
        params: Option<FormatParams>,

        /// Separator string for array-typed values.
        #[serde(skip_serializing_if = "Option::is_none")]
        separator: Option<String>,

        #[serde(default = "default_visible")]
        visible: VisibleRule,
    },
}

fn default_visible() -> VisibleRule {
    VisibleRule::Always
}

/// A field group — replaces v1's `nestedFields`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldGroup {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,

    #[serde(default)]
    pub iteration: Iteration,

    pub fields: Vec<DisplayField>,
}

/// How grouped fields should be iterated for display.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Iteration {
    #[default]
    Sequential,
    Bundled,
}

/// Visibility rule for a field.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(untagged)]
pub enum VisibleRule {
    /// Boolean shorthand: true = Always, false = Never.
    Bool(bool),

    /// String shorthand: "always", "never", or "optional".
    Named(VisibleLiteral),

    /// Conditional visibility.
    Condition(VisibleCondition),

    /// Default: always visible.
    #[default]
    Always,
}

/// Named visibility literals accepted by the current spec.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum VisibleLiteral {
    Always,
    Never,
    Optional,
}

/// Conditional visibility: `ifNotIn` or `mustMatch`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VisibleCondition {
    #[serde(rename = "ifNotIn")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub if_not_in: Option<Vec<serde_json::Value>>,

    #[serde(rename = "mustMatch", alias = "mustBe")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub must_match: Option<Vec<serde_json::Value>>,
}

impl VisibleCondition {
    pub fn hides_for_if_not_in(&self, value: &serde_json::Value) -> bool {
        self.if_not_in
            .as_ref()
            .is_some_and(|excluded| excluded.contains(value))
    }

    pub fn matches_must_match(&self, value: &serde_json::Value) -> bool {
        self.must_match
            .as_ref()
            .is_none_or(|required| required.contains(value))
    }
}

/// Field format types.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum FieldFormat {
    TokenAmount,
    Amount,
    Date,
    #[serde(rename = "enum")]
    Enum,
    Address,
    AddressName,
    Number,
    Raw,
    TokenTicker,
    ChainId,
    Calldata,
    NftName,
    Duration,
    Unit,
    /// ERC-7930 interoperable address format.
    InteroperableAddressName,
}

/// Format parameters — varies by format type.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormatParams {
    /// Token address path for tokenAmount/tokenTicker (resolved from calldata).
    #[serde(rename = "tokenPath")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token_path: Option<String>,

    /// Static token address or `$.metadata.constants.*` ref for tokenAmount/tokenTicker.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,

    /// Native currency address — single address or array of addresses/constant refs.
    /// Per spec: "Either a string or an array of strings."
    #[serde(rename = "nativeCurrencyAddress")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub native_currency_address: Option<NativeCurrencyAddress>,

    /// Static chain ID for cross-chain token resolution.
    #[serde(rename = "chainId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chain_id: Option<u64>,

    /// Dynamic chain ID path from calldata.
    #[serde(rename = "chainIdPath")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chain_id_path: Option<String>,

    /// Enum lookup key in metadata.enums.
    #[serde(rename = "enumPath")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enum_path: Option<String>,

    /// `$ref` enum reference path (v2): e.g., `"$.metadata.enums.interestRateMode"`.
    #[serde(rename = "$ref")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ref_path: Option<String>,

    /// Map reference key in metadata.maps.
    #[serde(rename = "mapReference")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub map_reference: Option<String>,

    /// Threshold for max-amount display (v2).
    /// Value or `"$.metadata.constants.max"` reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threshold: Option<String>,

    /// Message to display when amount >= threshold (e.g., "All", "Max").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,

    /// Unit base symbol (e.g., "%", "bps", "h") for the `unit` format.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base: Option<String>,

    /// Decimal places for the `unit` format (default 0).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decimals: Option<u8>,

    /// Whether to use SI prefix notation for the `unit` format.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefix: Option<bool>,

    /// Encryption parameters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encryption: Option<EncryptionParams>,

    /// Date encoding: `"timestamp"` (default) or `"blockheight"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encoding: Option<String>,

    /// Path to resolve which selector to use for nested calldata decoding.
    #[serde(rename = "selectorPath")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selector_path: Option<String>,

    /// Constant selector override for nested calldata decoding.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selector: Option<String>,

    /// Path to the callee address for nested calldata (e.g., "to").
    #[serde(rename = "calleePath")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub callee_path: Option<String>,

    /// Constant callee address for nested calldata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub callee: Option<String>,

    /// Path to the value amount for nested calldata (injected as `@.value` in inner context).
    #[serde(rename = "amountPath")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount_path: Option<String>,

    /// Constant native amount for nested calldata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub amount: Option<UintLiteral>,

    /// Path to the spender/from address for nested calldata (injected as `@.from` in inner context).
    #[serde(rename = "spenderPath")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub spender_path: Option<String>,

    /// Constant spender/from address for nested calldata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub spender: Option<String>,

    /// Address types for addressName format (spec: "eoa", "contract", etc.).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub types: Option<Vec<String>>,

    /// Trusted name sources for addressName format (spec: "ens", "local").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sources: Option<Vec<String>>,

    /// Sender address check for addressName format.
    #[serde(rename = "senderAddress")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sender_address: Option<SenderAddress>,

    /// Path to the collection address for nftName format.
    #[serde(rename = "collectionPath")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collection_path: Option<String>,

    /// Constant collection address for nftName format.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub collection: Option<String>,
}

/// Native currency address — single address or array of addresses/constant refs.
/// Per ERC-7730 spec: "Either a string or an array of strings."
/// Values may be `$.metadata.constants.xxx` references resolved at comparison time.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum NativeCurrencyAddress {
    Single(String),
    Multiple(Vec<String>),
}

impl NativeCurrencyAddress {
    /// Check if `addr` matches any native currency address, resolving `$.metadata.constants.*` refs.
    pub fn matches(&self, addr: &str, constants: &HashMap<String, serde_json::Value>) -> bool {
        let items: Vec<&str> = match self {
            NativeCurrencyAddress::Single(s) => vec![s.as_str()],
            NativeCurrencyAddress::Multiple(v) => v.iter().map(|s| s.as_str()).collect(),
        };
        items.iter().any(|item| {
            let resolved = if let Some(key) = item.strip_prefix("$.metadata.constants.") {
                constants.get(key).and_then(|v| v.as_str()).unwrap_or(item)
            } else {
                item
            };
            resolved.eq_ignore_ascii_case(addr)
        })
    }
}

/// Sender address — can be a single address or an array of addresses/paths.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SenderAddress {
    Single(String),
    Multiple(Vec<String>),
}

/// Unsigned integer literal for descriptor params.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UintLiteral {
    Number(u64),
    String(String),
}

impl UintLiteral {
    pub fn to_biguint(&self) -> Option<BigUint> {
        match self {
            UintLiteral::Number(value) => Some(BigUint::from(*value)),
            UintLiteral::String(value) => {
                let trimmed = value.trim();
                if let Some(hex) = trimmed
                    .strip_prefix("0x")
                    .or_else(|| trimmed.strip_prefix("0X"))
                {
                    let bytes = hex::decode(hex).ok()?;
                    Some(BigUint::from_bytes_be(&bytes))
                } else {
                    trimmed.parse::<BigUint>().ok()
                }
            }
        }
    }
}

/// Encryption parameters for encrypted fields.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionParams {
    /// Encryption scheme identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheme: Option<String>,

    /// Type of the plaintext content.
    #[serde(rename = "plaintextType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plaintext_type: Option<String>,

    #[serde(rename = "fallbackLabel")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fallback_label: Option<String>,
}