Skip to main content

iota_json_rpc_types/
display_template.rs

1// Copyright (c) 2026 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4//! Rendering of on-chain Display templates, shared by the JSON-RPC and GraphQL
5//! servers.
6//!
7//! A Display is a set of `key = template` entries published for a Move type,
8//! for example `name = "{name}"` or `image_url = "https://x.io/{id}.png"`.
9//! A `{field.path}` placeholder is replaced by the value of that field of the
10//! object and `\` makes the next character literal.
11
12use iota_types::base_types::RESOLVED_STD_OPTION;
13use move_core_types::annotated_value::{MoveStruct, MoveValue};
14
15use crate::{IotaMoveStruct, IotaMoveValue, IotaMoveVariant};
16
17/// Maximum total size in bytes of the rendered Display fields of one object.
18pub const MAX_DISPLAY_OUTPUT_SIZE: usize = 1024 * 1024;
19/// Maximum nesting depth of a placeholder path, counted in field names.
20///
21/// e.g. `{a.b.c}` has a depth of 3.
22pub const MAX_DISPLAY_NESTED_LEVEL: usize = 10;
23
24#[derive(thiserror::Error, Debug)]
25pub enum DisplayRenderError {
26    #[error("Display template value cannot be empty")]
27    TemplateValueEmpty,
28    #[error("Display template value of {0} exceeds maximum depth of {1}")]
29    ExceedsLookupDepth(usize, usize),
30    #[error("Vector is not supported as a Display value {0}")]
31    Vector(String),
32    #[error("Field value {0} cannot be found in struct")]
33    FieldNotFound(String),
34    #[error("Field value {path} cannot be found in variant {variant}")]
35    FieldNotFoundInVariant { path: String, variant: String },
36    #[error("Unexpected move value type for field {0}")]
37    UnexpectedMoveValue(String),
38    #[error("Rendered Display fields exceed the maximum size of {0} bytes")]
39    OutputTooLarge(usize),
40}
41
42/// Field lookup for rendering on-chain Display templates.
43///
44/// Resolves a dot-separated path (e.g. `owner.address` from `{owner.address}`)
45/// to the string that replaces the placeholder.
46pub trait DisplayFieldLookup {
47    /// Looks up a field by its path and returns its string representation.
48    ///
49    /// # Errors
50    /// Returns a [`DisplayRenderError`] if the path is empty, cannot be found,
51    /// exceeds nesting limits, or references an unsupported type (such as a vector).
52    fn get_display_value(&self, path: &str) -> Result<String, DisplayRenderError>;
53}
54
55/// Renders one Display template against `object`.
56///
57/// The template is read once, left to right. Plain text is copied, a
58/// `{path}` placeholder is replaced by `object.get_display_value(path)`, and
59/// `\` makes the next character literal. Substituted values are never read
60/// again, so a value that contains `{...}` stays as it is.
61///
62/// The rendered size is subtracted from `output_budget`, which is shared by
63/// all fields of one object. If the result would not fit, an error is
64/// returned and the budget is set to zero, so the remaining fields of the
65/// object fail without being rendered.
66pub fn render_display_template(
67    template: &str,
68    object: &impl DisplayFieldLookup,
69    output_budget: &mut usize,
70) -> Result<String, DisplayRenderError> {
71    if *output_budget == 0 {
72        return Err(DisplayRenderError::OutputTooLarge(MAX_DISPLAY_OUTPUT_SIZE));
73    }
74
75    let mut output = String::new();
76    // `{` and the text read after it, written out as it is if the placeholder
77    // is never closed.
78    let mut placeholder = String::new();
79    let mut var_name = String::new();
80    let mut in_braces = false;
81    let mut escaped = false;
82
83    for ch in template.chars() {
84        match ch {
85            '\\' if !escaped => {
86                escaped = true;
87                continue;
88            }
89            '{' if !escaped => {
90                if in_braces {
91                    // The earlier `{` was never closed, so it is plain text.
92                    output.push_str(&placeholder);
93                }
94                placeholder.clear();
95                placeholder.push('{');
96                in_braces = true;
97                var_name.clear();
98            }
99            '}' if !escaped && in_braces => {
100                in_braces = false;
101                placeholder.clear();
102                let value = object.get_display_value(&var_name)?;
103                if output.len() + value.len() > *output_budget {
104                    *output_budget = 0;
105                    return Err(DisplayRenderError::OutputTooLarge(MAX_DISPLAY_OUTPUT_SIZE));
106                }
107                output.push_str(&value);
108            }
109            _ if in_braces => {
110                if !escaped {
111                    var_name.push(ch);
112                }
113                placeholder.push(ch);
114            }
115            _ => output.push(ch),
116        }
117        escaped = false;
118    }
119    output.push_str(&placeholder);
120
121    if output.len() > *output_budget {
122        *output_budget = 0;
123        return Err(DisplayRenderError::OutputTooLarge(MAX_DISPLAY_OUTPUT_SIZE));
124    }
125    *output_budget -= output.len();
126    Ok(output)
127}
128
129/// Splits a dotted lookup path (e.g. `"owner.address"`) into its first part
130/// and the remaining parts.
131///
132/// # Errors
133/// - [`DisplayRenderError::TemplateValueEmpty`] if the path is empty or starts with a dot.
134/// - [`DisplayRenderError::ExceedsLookupDepth`] if the number of parts exceeds
135///   [`MAX_DISPLAY_NESTED_LEVEL`].
136fn split_path(path: &str) -> Result<(&str, Vec<&str>), DisplayRenderError> {
137    let mut parts = path.split('.');
138    let first = match parts.next() {
139        Some(first) if !first.is_empty() => first,
140        _ => return Err(DisplayRenderError::TemplateValueEmpty),
141    };
142    let rest: Vec<&str> = parts.collect();
143    if rest.len() + 1 > MAX_DISPLAY_NESTED_LEVEL {
144        return Err(DisplayRenderError::ExceedsLookupDepth(
145            rest.len() + 1,
146            MAX_DISPLAY_NESTED_LEVEL,
147        ));
148    }
149    Ok((first, rest))
150}
151
152/// Converts a leaf value into its string representation for template substitution.
153///
154/// - **Options:** Renders the `Some` value by these same rules, or returns an empty string (`""`)
155///   for `None`.
156/// - **Vectors:** Explicitly rejected as unsupported display values (returning
157///   [`DisplayRenderError::Vector`]).
158/// - **Primitives/Others:** Converted to string via `to_string()`.
159fn render_leaf(value: &IotaMoveValue, path: &str) -> Result<String, DisplayRenderError> {
160    match value {
161        IotaMoveValue::Option(move_option) => match move_option.as_ref() {
162            Some(inner) => render_leaf(inner, path),
163            None => Ok("".to_string()),
164        },
165        IotaMoveValue::Vector(_) => Err(DisplayRenderError::Vector(path.to_string())),
166        _ => Ok(value.to_string()),
167    }
168}
169
170/// Field lookup over the JSON-RPC representation of an object, used by the
171/// full node and the indexer.
172///
173/// Unlike the raw Move representation, framework types such as `String` and
174/// `UID` are already flattened to plain values, so a path like `id.id` fails
175/// here. A path may walk through nested structs and enum variants. Only the
176/// final value is converted for display, and it must be a scalar.
177impl DisplayFieldLookup for IotaMoveStruct {
178    fn get_display_value(&self, path: &str) -> Result<String, DisplayRenderError> {
179        let (first, rest) = split_path(path)?;
180        let mut current = get_iota_struct_field(self, first, path)?;
181        for part in rest {
182            current =
183                match current {
184                    IotaMoveValue::Struct(s) => get_iota_struct_field(s, part, path)?,
185                    IotaMoveValue::Variant(IotaMoveVariant {
186                        fields, variant, ..
187                    }) => fields.get(part).ok_or_else(|| {
188                        DisplayRenderError::FieldNotFoundInVariant {
189                            path: path.to_string(),
190                            variant: variant.clone(),
191                        }
192                    })?,
193                    _ => return Err(DisplayRenderError::UnexpectedMoveValue(path.to_string())),
194                };
195        }
196        render_leaf(current, path)
197    }
198}
199
200/// Returns the field named `part` of `move_struct`. `path` is the full
201/// placeholder path, used only in error messages.
202///
203/// # Errors
204/// - [`DisplayRenderError::FieldNotFound`] if the struct has no such field.
205/// - [`DisplayRenderError::UnexpectedMoveValue`] for a `Runtime` struct, whose fields are
206///   positional and cannot be looked up by name.
207fn get_iota_struct_field<'a>(
208    move_struct: &'a IotaMoveStruct,
209    part: &str,
210    path: &str,
211) -> Result<&'a IotaMoveValue, DisplayRenderError> {
212    match move_struct {
213        IotaMoveStruct::WithTypes { fields, .. } | IotaMoveStruct::WithFields(fields) => fields
214            .get(part)
215            .ok_or_else(|| DisplayRenderError::FieldNotFound(path.to_string())),
216        IotaMoveStruct::Runtime(_) => {
217            Err(DisplayRenderError::UnexpectedMoveValue(path.to_string()))
218        }
219    }
220}
221
222/// Field lookup over the raw Move representation of an object, used by
223/// GraphQL.
224///
225/// Unlike the JSON-RPC representation, the raw struct keeps framework types
226/// such as `String` and `UID` as nested structs, so a path may walk into
227/// them (e.g. `id.id`). Only the final value is converted for display, and it
228/// must still be a scalar.
229impl DisplayFieldLookup for MoveStruct {
230    fn get_display_value(&self, path: &str) -> Result<String, DisplayRenderError> {
231        let (first, rest) = split_path(path)?;
232        let mut current = get_move_struct_field(self, first)?;
233        for part in rest {
234            current = match current {
235                MoveValue::Struct(s) => get_move_struct_field(s, part)?,
236                _ => return Err(DisplayRenderError::UnexpectedMoveValue(path.to_string())),
237            };
238        }
239        // An `Option` is a struct holding a vector of zero or one element.
240        // Unwrap it here so that a vector inside is rejected before the value
241        // is copied.
242        while let MoveValue::Struct(s) = current {
243            let ty = &s.type_;
244            if (&ty.address, ty.module.as_ref(), ty.name.as_ref()) != RESOLVED_STD_OPTION {
245                break;
246            }
247            let Some((_, MoveValue::Vector(elements))) = s.fields.first() else {
248                break;
249            };
250            match elements.first() {
251                Some(inner) => current = inner,
252                None => return Ok("".to_string()),
253            }
254        }
255        if let MoveValue::Vector(_) = current {
256            return Err(DisplayRenderError::Vector(path.to_string()));
257        }
258        render_leaf(&current.clone().into(), path)
259    }
260}
261
262/// Returns the field named `part` of `move_struct`.
263///
264/// # Errors
265/// - [`DisplayRenderError::FieldNotFound`] if the struct has no such field.
266fn get_move_struct_field<'a>(
267    move_struct: &'a MoveStruct,
268    part: &str,
269) -> Result<&'a MoveValue, DisplayRenderError> {
270    move_struct
271        .fields
272        .iter()
273        .find_map(|(id, value)| (id.as_str() == part).then_some(value))
274        .ok_or_else(|| DisplayRenderError::FieldNotFound(part.to_string()))
275}
276
277#[cfg(test)]
278mod tests {
279    use move_core_types::{
280        account_address::AccountAddress, identifier::Identifier, language_storage::StructTag,
281    };
282
283    use super::*;
284
285    /// A `std::string::String` as it is stored on chain.
286    fn move_string(value: &str) -> MoveValue {
287        MoveValue::Struct(MoveStruct {
288            type_: StructTag {
289                address: AccountAddress::ONE,
290                module: Identifier::new("string").unwrap(),
291                name: Identifier::new("String").unwrap(),
292                type_params: vec![],
293            },
294            fields: vec![(
295                Identifier::new("bytes").unwrap(),
296                MoveValue::Vector(value.bytes().map(MoveValue::U8).collect()),
297            )],
298        })
299    }
300
301    /// The object as GraphQL sees it: raw Move values.
302    fn move_struct(fields: &[(&str, &str)]) -> MoveStruct {
303        MoveStruct {
304            type_: StructTag {
305                address: AccountAddress::TWO,
306                module: Identifier::new("test").unwrap(),
307                name: Identifier::new("Test").unwrap(),
308                type_params: vec![],
309            },
310            fields: fields
311                .iter()
312                .map(|(name, value)| (Identifier::new(*name).unwrap(), move_string(value)))
313                .collect(),
314        }
315    }
316
317    /// The same object as JSON-RPC sees it: converted, strings flattened.
318    fn iota_struct(fields: &[(&str, &str)]) -> IotaMoveStruct {
319        IotaMoveStruct::WithFields(
320            fields
321                .iter()
322                .map(|(name, value)| (name.to_string(), IotaMoveValue::String(value.to_string())))
323                .collect(),
324        )
325    }
326
327    const FIELDS: &[(&str, &str)] = &[
328        ("name", "Boar"),
329        ("id", "0x1"),
330        ("url", "https://x.io/{id}.png"), // value that itself contains a placeholder
331        ("path", "C:\\nft"),              // value with a backslash
332        ("i", "{i}{i}"),                  // each substitution adds two placeholders
333    ];
334
335    /// Renders through both lookups and checks they agree.
336    fn render(template: &str) -> Result<String, DisplayRenderError> {
337        let mut budget = MAX_DISPLAY_OUTPUT_SIZE;
338        let a = render_display_template(template, &move_struct(FIELDS), &mut budget);
339        let mut budget = MAX_DISPLAY_OUTPUT_SIZE;
340        let b = render_display_template(template, &iota_struct(FIELDS), &mut budget);
341        assert_eq!(
342            a.as_ref().map_err(ToString::to_string),
343            b.as_ref().map_err(ToString::to_string),
344            "MoveStruct and IotaMoveStruct lookups differ for {template:?}"
345        );
346        a
347    }
348
349    #[test]
350    fn test_render_display_template() {
351        let cases = [
352            ("no template", "no template"),
353            ("{name}", "Boar"),
354            ("A {name} with {id}", "A Boar with 0x1"),
355            ("{name}{name}", "BoarBoar"),
356            // A value is appended as text, never read as a template.
357            ("{url} {id}", "https://x.io/{id}.png 0x1"),
358            // A backslash inside a value is kept.
359            ("{path}", "C:\\nft"),
360            // Escapes.
361            ("\\{name\\}", "{name}"),
362            ("\\{name\\} is {name}", "{name} is Boar"),
363            ("{name} \\{name}", "Boar {name}"),
364            ("\\\\{name}", "\\Boar"),
365            ("a\\\\b", "a\\b"),
366            // Broken braces are plain text.
367            ("a } b", "a } b"),
368            ("unclosed {name", "unclosed {name"),
369            ("{a{name}", "{aBoar"),
370        ];
371        for (template, expected) in cases {
372            assert_eq!(render(template).unwrap(), expected, "template {template:?}");
373        }
374        assert!(matches!(
375            render("{missing}"),
376            Err(DisplayRenderError::FieldNotFound(_))
377        ));
378        assert!(matches!(
379            render("{}"),
380            Err(DisplayRenderError::TemplateValueEmpty)
381        ));
382        assert!(matches!(
383            render(&format!("{{{}}}", ["a"; 11].join("."))),
384            Err(DisplayRenderError::ExceedsLookupDepth(11, 10))
385        ));
386    }
387
388    #[test]
389    fn test_render_display_template_does_not_render_placeholders_in_values() {
390        // Each substituted value holds two placeholders. Expanding them again
391        // would double the output at every placeholder of the template.
392        let output = render(&"{i}".repeat(64)).unwrap();
393        assert_eq!(output, "{i}{i}".repeat(64));
394    }
395
396    #[test]
397    fn test_render_display_template_output_budget() {
398        let value = "x".repeat(1024);
399        let object = iota_struct(&[("v", &value)]);
400        let mut budget = 4 * 1024;
401
402        // Fits exactly in the budget.
403        let output = render_display_template(&"{v}".repeat(4), &object, &mut budget).unwrap();
404        assert_eq!(output.len(), 4 * 1024);
405        assert_eq!(budget, 0);
406
407        // Nothing is left, so even a template without placeholders fails.
408        assert!(matches!(
409            render_display_template("text", &object, &mut budget),
410            Err(DisplayRenderError::OutputTooLarge(_)),
411        ));
412
413        // A field that does not fit uses up the budget for the next fields.
414        let mut budget = 4 * 1024;
415        assert!(matches!(
416            render_display_template(&"{v}".repeat(5), &object, &mut budget),
417            Err(DisplayRenderError::OutputTooLarge(_)),
418        ));
419        assert_eq!(budget, 0);
420        assert!(matches!(
421            render_display_template("{v}", &object, &mut budget),
422            Err(DisplayRenderError::OutputTooLarge(_)),
423        ));
424    }
425
426    #[test]
427    fn test_nested_paths() {
428        // `{owner.address}` walks into the `owner` struct on both
429        // representations and renders its `address` field.
430        let mut owner = move_struct(&[("address", "0xabc")]);
431        owner.type_.name = Identifier::new("Owner").unwrap();
432        let mut object = move_struct(&[("name", "Boar")]);
433        object
434            .fields
435            .push((Identifier::new("owner").unwrap(), MoveValue::Struct(owner)));
436
437        let iota_object = IotaMoveStruct::WithFields(
438            [
439                (
440                    "name".to_string(),
441                    IotaMoveValue::String("Boar".to_string()),
442                ),
443                (
444                    "owner".to_string(),
445                    IotaMoveValue::Struct(iota_struct(&[("address", "0xabc")])),
446                ),
447            ]
448            .into_iter()
449            .collect(),
450        );
451
452        for template in ["{owner.address}", "{name} of {owner.address}"] {
453            let mut budget = MAX_DISPLAY_OUTPUT_SIZE;
454            let a = render_display_template(template, &object, &mut budget).unwrap();
455            let mut budget = MAX_DISPLAY_OUTPUT_SIZE;
456            let b = render_display_template(template, &iota_object, &mut budget).unwrap();
457            assert_eq!(a, b, "template {template:?}");
458            assert!(a.ends_with("0xabc"), "template {template:?} -> {a:?}");
459        }
460
461        // GraphQL walks the raw struct, so `name.bytes` resolves to the vector
462        // and is rejected as such; JSON-RPC has `name` flattened to a string.
463        let mut budget = MAX_DISPLAY_OUTPUT_SIZE;
464        assert!(matches!(
465            render_display_template("{name.bytes}", &move_struct(FIELDS), &mut budget),
466            Err(DisplayRenderError::Vector(_))
467        ));
468        assert!(matches!(
469            render_display_template("{name.bytes}", &iota_struct(FIELDS), &mut budget),
470            Err(DisplayRenderError::UnexpectedMoveValue(_))
471        ));
472    }
473
474    #[test]
475    fn test_option_value() {
476        let option = |value: Option<IotaMoveValue>| IotaMoveValue::Option(Box::new(value));
477        let object = IotaMoveStruct::WithFields(
478            [
479                (
480                    "some".to_string(),
481                    option(Some(IotaMoveValue::String("Boar".to_string()))),
482                ),
483                ("none".to_string(), option(None)),
484                (
485                    "vector".to_string(),
486                    option(Some(IotaMoveValue::Vector(vec![]))),
487                ),
488            ]
489            .into_iter()
490            .collect(),
491        );
492
493        let mut budget = MAX_DISPLAY_OUTPUT_SIZE;
494        assert_eq!(
495            render_display_template("{some}|{none}", &object, &mut budget).unwrap(),
496            "Boar|"
497        );
498        assert!(matches!(
499            render_display_template("{vector}", &object, &mut budget),
500            Err(DisplayRenderError::Vector(_))
501        ));
502    }
503}