Skip to main content

ledger_engine/
nft.rs

1//! NFT methods, as in Clio 2.8. account_nfts, nft_buy_offers and
2//! nft_sell_offers read the ledger state; nft_info, nft_history and
3//! nfts_by_issuer read the NFT index (`nftindex`, kept in the state store),
4//! and answer `notReady` until its backfill is done.
5//!
6//! account_nfts walks the account's NFT pages from the last one down through
7//! `PreviousPageMin`; `limit` counts pages, and the marker is the key of the
8//! next page. The offer methods walk the token's buy or sell offer directory
9//! like the owner directory; their marker is the key of the first offer of
10//! the next page, and that offer comes back as the first one of the page.
11
12use serde_json::{Map, Value, json};
13
14use crate::api::{
15    Engine, Res, RpcError, account_id, decode_account, internal, invalid_params, keylet, rpc_err,
16    time_iso,
17};
18use crate::owned::{corrupt, h256};
19use crate::state::{AccountTx, TxPosition};
20use crate::xrpl_json;
21
22const NFTS_LIMIT_MIN: u32 = 20;
23const NFTS_LIMIT_MAX: u32 = 400;
24const NFTS_LIMIT_DEFAULT: u32 = 100;
25const OFFERS_LIMIT_MIN: u32 = 50;
26const OFFERS_LIMIT_MAX: u32 = 500;
27const OFFERS_LIMIT_DEFAULT: u32 = 250;
28const HISTORY_LIMIT_MAX: u32 = 100;
29const HISTORY_LIMIT_DEFAULT: u32 = 50;
30const ISSUER_LIMIT_MAX: u32 = 100;
31const ISSUER_LIMIT_DEFAULT: u32 = 50;
32
33/// The parts an NFTokenID is made of.
34#[derive(Debug, PartialEq, Eq)]
35pub(crate) struct TokenId {
36    pub flags: u16,
37    pub transfer_fee: u16,
38    pub issuer: [u8; 20],
39    pub taxon: u32,
40    pub serial: u32,
41}
42
43/// Splits an NFTokenID; the taxon is stored ciphered with the serial
44/// (xrpld's `cipheredTaxon`), so it is deciphered here.
45pub(crate) fn token_id(id: &[u8; 32]) -> TokenId {
46    let be16 = |i: usize| u16::from_be_bytes([id[i], id[i + 1]]);
47    let be32 = |i: usize| u32::from_be_bytes([id[i], id[i + 1], id[i + 2], id[i + 3]]);
48    let serial = be32(28);
49    let mut issuer = [0u8; 20];
50    issuer.copy_from_slice(&id[4..24]);
51    TokenId {
52        flags: be16(0),
53        transfer_fee: be16(2),
54        issuer,
55        taxon: be32(24) ^ 384_160_001u32.wrapping_mul(serial).wrapping_add(2459),
56        serial,
57    }
58}
59
60/// `limit` as Clio takes it: an integer of at least 1, clamped to [min, max].
61fn limit(p: &Map<String, Value>, min: u32, max: u32, default: u32) -> Res<u32> {
62    match p.get("limit") {
63        None => Ok(default),
64        Some(v) => v
65            .as_u64()
66            .filter(|n| *n >= 1)
67            .and_then(|n| u32::try_from(n).ok())
68            .map(|n| n.clamp(min, max))
69            .ok_or_else(|| invalid_params("Invalid parameters.")),
70    }
71}
72
73/// An optional 256-bit hex field, with Clio's errors.
74fn hex256(p: &Map<String, Value>, key: &str) -> Res<Option<[u8; 32]>> {
75    match p.get(key) {
76        None => Ok(None),
77        Some(Value::String(s)) => hex::decode(s)
78            .ok()
79            .and_then(|b| <[u8; 32]>::try_from(b).ok())
80            .map(Some)
81            .ok_or_else(|| invalid_params(&format!("{key}Malformed"))),
82        Some(_) => Err(invalid_params(&format!("{key}NotString"))),
83    }
84}
85
86fn entry_type(node: &Map<String, Value>) -> &str {
87    node.get("LedgerEntryType")
88        .and_then(Value::as_str)
89        .unwrap_or_default()
90}
91
92/// One NFToken of a page as account_nfts shows it: the stored fields, then
93/// the parts of the ID.
94fn token_json(key: &[u8; 32], token: &Value) -> Res<Value> {
95    let mut o = token
96        .get("NFToken")
97        .and_then(Value::as_object)
98        .cloned()
99        .ok_or_else(|| corrupt(key, "NFTokens entry without NFToken"))?;
100    let id = o
101        .get("NFTokenID")
102        .and_then(Value::as_str)
103        .and_then(|s| hex::decode(s).ok())
104        .and_then(|b| <[u8; 32]>::try_from(b).ok())
105        .ok_or_else(|| corrupt(key, "NFToken without NFTokenID"))?;
106    let t = token_id(&id);
107    o.insert("Flags".into(), json!(t.flags));
108    o.insert("Issuer".into(), json!(xrpl_json::account(&t.issuer)));
109    o.insert("NFTokenTaxon".into(), json!(t.taxon));
110    o.insert("nft_serial".into(), json!(t.serial));
111    if t.transfer_fee != 0 {
112        o.insert("TransferFee".into(), json!(t.transfer_fee));
113    }
114    Ok(Value::Object(o))
115}
116
117/// An offer as nft_buy_offers and nft_sell_offers show it.
118fn offer_json(key: &[u8; 32], node: &Map<String, Value>) -> Res<Value> {
119    let mut o = Map::new();
120    o.insert("nft_offer_index".into(), json!(hex::encode_upper(key)));
121    o.insert(
122        "flags".into(),
123        json!(node.get("Flags").and_then(Value::as_u64).unwrap_or(0)),
124    );
125    for (out, field) in [("owner", "Owner"), ("amount", "Amount")] {
126        let v = node
127            .get(field)
128            .ok_or_else(|| corrupt(key, &format!("NFTokenOffer without {field}")))?;
129        o.insert(out.into(), v.clone());
130    }
131    if let Some(d) = node.get("Destination") {
132        o.insert("destination".into(), d.clone());
133    }
134    if let Some(e) = node.get("Expiration") {
135        o.insert("expiration".into(), e.clone());
136    }
137    Ok(Value::Object(o))
138}
139
140/// A required account field with Clio's `accountValidator` errors.
141fn account_field(p: &Map<String, Value>, key: &str) -> Res<[u8; 20]> {
142    match p.get(key) {
143        None => Err(invalid_params(&format!("Required field '{key}' missing"))),
144        Some(Value::String(s)) => {
145            decode_account(s).ok_or_else(|| rpc_err("actMalformed", 35, format!("{key}Malformed")))
146        }
147        Some(_) => Err(invalid_params(&format!("{key}NotString"))),
148    }
149}
150
151/// An optional field that must be a boolean.
152fn bool_field(p: &Map<String, Value>, key: &str) -> Res<bool> {
153    match p.get(key) {
154        None => Ok(false),
155        Some(Value::Bool(b)) => Ok(*b),
156        Some(_) => Err(invalid_params("Invalid parameters.")),
157    }
158}
159
160/// `ledger_index_min` or `_max` of nft_history: a 32-bit integer, -1 for none.
161fn bound(p: &Map<String, Value>, key: &str) -> Res<Option<u32>> {
162    match p.get(key) {
163        None => Ok(None),
164        Some(v) => match v.as_i64().and_then(|n| i32::try_from(n).ok()) {
165            Some(-1) => Ok(None),
166            Some(n) => u32::try_from(n)
167                .map(Some)
168                .map_err(|_| invalid_params("Invalid parameters.")),
169            None => Err(invalid_params("Invalid parameters.")),
170        },
171    }
172}
173
174fn not_ready() -> RpcError {
175    rpc_err("notReady", 13, "Not ready to handle this request.")
176}
177
178/// The fields nft_info and each nfts_by_issuer entry share.
179fn token_info(m: &mut Map<String, Value>, id: &[u8; 32]) {
180    let t = token_id(id);
181    m.insert("flags".into(), json!(t.flags));
182    m.insert("transfer_fee".into(), json!(t.transfer_fee));
183    m.insert("issuer".into(), json!(xrpl_json::account(&t.issuer)));
184    m.insert("nft_taxon".into(), json!(t.taxon));
185    m.insert("nft_serial".into(), json!(t.serial));
186}
187
188impl Engine {
189    /// The NFT index is filled down to its start.
190    fn nft_ready(&self) -> Res<()> {
191        match self.state.nft_coverage().map_err(internal)? {
192            Some(_) => Ok(()),
193            None => Err(not_ready()),
194        }
195    }
196
197    pub(crate) fn nft_info(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
198        let id = hex256(p, "nft_id")?
199            .ok_or_else(|| invalid_params("Required field 'nft_id' missing"))?;
200        let seq = self.resolve(p)?;
201        self.nft_ready()?;
202        let (at, owner, burned) = self
203            .state
204            .nft_at(&id, seq)
205            .map_err(internal)?
206            .ok_or_else(|| rpc_err("objectNotFound", 92, "NFT not found"))?;
207        let uri = self.state.nft_uri_at(&id, seq).map_err(internal)?;
208        let mut m = Map::new();
209        m.insert("nft_id".into(), json!(hex::encode_upper(id)));
210        m.insert("ledger_index".into(), json!(at));
211        m.insert("owner".into(), json!(xrpl_json::account(&owner)));
212        m.insert("is_burned".into(), json!(burned));
213        token_info(&mut m, &id);
214        m.insert("validated".into(), json!(true));
215        m.insert(
216            "uri".into(),
217            json!(hex::encode_upper(uri.unwrap_or_default())),
218        );
219        Ok(m)
220    }
221
222    /// Clio's `NFTsByIssuerHandler`: the issuer's tokens by taxon and ID, each
223    /// as of the ledger asked; a token minted after it is left out, but still
224    /// counts toward the page.
225    pub(crate) fn nfts_by_issuer(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
226        let issuer = account_field(p, "issuer")?;
227        let taxon = match p.get("nft_taxon") {
228            None => None,
229            Some(v) => Some(
230                v.as_u64()
231                    .and_then(|n| u32::try_from(n).ok())
232                    .ok_or_else(|| invalid_params("Invalid parameters."))?,
233            ),
234        };
235        let limit = limit(p, 1, ISSUER_LIMIT_MAX, ISSUER_LIMIT_DEFAULT)?;
236        let marker = hex256(p, "marker")?;
237        let seq = self.resolve_state(p)?;
238        if self.fetch(&keylet(b'a', &[&issuer]), seq)?.is_none() {
239            return Err(rpc_err("actNotFound", 19, "Account not found."));
240        }
241        self.nft_ready()?;
242        let after = marker.map(|c| (taxon.unwrap_or_else(|| token_id(&c).taxon), c));
243        let ids = self
244            .state
245            .nfts_by_issuer(&issuer, taxon, after, limit as usize)
246            .map_err(internal)?;
247        let mut nfts = Vec::with_capacity(ids.len());
248        for id in &ids {
249            crate::limits::check_rpc()?;
250            let Some((at, owner, burned)) = self.state.nft_at(id, seq).map_err(internal)? else {
251                continue;
252            };
253            let uri = self.state.nft_uri_at(id, seq).map_err(internal)?;
254            let mut n = Map::new();
255            n.insert("nft_id".into(), json!(hex::encode_upper(id)));
256            n.insert("ledger_index".into(), json!(at));
257            n.insert("owner".into(), json!(xrpl_json::account(&owner)));
258            n.insert("is_burned".into(), json!(burned));
259            n.insert(
260                "uri".into(),
261                json!(hex::encode_upper(uri.unwrap_or_default())),
262            );
263            token_info(&mut n, id);
264            nfts.push(Value::Object(n));
265        }
266        let mut m = Map::new();
267        m.insert("issuer".into(), json!(xrpl_json::account(&issuer)));
268        m.insert("limit".into(), json!(limit));
269        m.insert("ledger_index".into(), json!(seq));
270        m.insert("nfts".into(), Value::Array(nfts));
271        m.insert("validated".into(), json!(true));
272        if ids.len() == limit as usize
273            && let Some(last) = ids.last()
274        {
275            m.insert("marker".into(), json!(hex::encode_upper(last)));
276        }
277        if let Some(t) = taxon {
278            m.insert("nft_taxon".into(), json!(t));
279        }
280        Ok(m)
281    }
282
283    /// Clio's `NFTHistoryHandler`. Unlike account_tx, the marker of a
284    /// forward page is the position right after the last transaction, and
285    /// transactions carry neither ctid nor the synthetic NFT fields.
286    pub(crate) fn nft_history(&self, p: &Map<String, Value>, api: u32) -> Res<Map<String, Value>> {
287        let id = hex256(p, "nft_id")?
288            .ok_or_else(|| invalid_params("Required field 'nft_id' missing"))?;
289        let (lo, hi) = (bound(p, "ledger_index_min")?, bound(p, "ledger_index_max")?);
290        let binary = bool_field(p, "binary")?;
291        let forward = bool_field(p, "forward")?;
292        let take = match p.get("limit") {
293            None => None,
294            Some(_) => Some(limit(p, 1, HISTORY_LIMIT_MAX, HISTORY_LIMIT_DEFAULT)?),
295        };
296        let marker = match p.get("marker") {
297            None => None,
298            Some(Value::Object(mk)) => {
299                let part = |k: &str| -> Res<u32> {
300                    match mk.get(k) {
301                        None => Err(invalid_params(&format!("Required field '{k}' missing"))),
302                        Some(v) => v
303                            .as_u64()
304                            .and_then(|n| u32::try_from(n).ok())
305                            .ok_or_else(|| invalid_params("Invalid parameters.")),
306                    }
307                };
308                Some(TxPosition {
309                    ledger: part("ledger")?,
310                    index: part("seq")?,
311                })
312            }
313            Some(_) => return Err(invalid_params("invalidMarker")),
314        };
315        let (range_min, range_max) = self.range()?;
316        if let Some(m) = marker {
317            crate::api::marker_in_range(m, range_max)?;
318        }
319        let (mut min, mut max) = (range_min, range_max);
320        if let Some(lo) = lo {
321            if lo > range_max || lo < range_min {
322                return Err(rpc_err("lgrIdxMalformed", 58, "ledgerSeqMinOutOfRange"));
323            }
324            min = lo;
325        }
326        if let Some(hi) = hi {
327            if hi > range_max || hi < range_min {
328                return Err(rpc_err("lgrIdxMalformed", 58, "ledgerSeqMaxOutOfRange"));
329            }
330            max = hi;
331        }
332        if min > max {
333            return Err(rpc_err("lgrIdxsInvalid", 57, "Ledger indexes invalid."));
334        }
335        // Like Clio, `"validated"` counts as no ledger given.
336        let index_given = p
337            .get("ledger_index")
338            .is_some_and(|v| crate::api::as_u32(v).is_some());
339        if p.contains_key("ledger_hash") || index_given {
340            if lo.is_some() || hi.is_some() {
341                return Err(invalid_params("containsLedgerSpecifierAndRange"));
342            }
343            let seq = self.resolve(p)?;
344            (min, max) = (seq, seq);
345        }
346        self.nft_ready()?;
347        let n = take.unwrap_or(HISTORY_LIMIT_DEFAULT) as usize;
348        let cursor = marker.unwrap_or(if forward {
349            TxPosition {
350                ledger: min,
351                index: 0,
352            }
353        } else {
354            TxPosition {
355                ledger: max,
356                index: i32::MAX as u32,
357            }
358        });
359        // Clio reads positions from the cursor on going forward, and strictly
360        // before it going back; the range only cuts the page afterwards.
361        let list = if forward {
362            let end = TxPosition {
363                ledger: u32::MAX,
364                index: u32::MAX,
365            };
366            self.state.nft_txs(&id, cursor, end, true, n)
367        } else {
368            let end = match (cursor.ledger, cursor.index) {
369                (0, 0) => None,
370                (l, 0) => Some(TxPosition {
371                    ledger: l - 1,
372                    index: u32::MAX,
373                }),
374                (l, i) => Some(TxPosition {
375                    ledger: l,
376                    index: i - 1,
377                }),
378            };
379            match end {
380                Some(e) => self.state.nft_txs(
381                    &id,
382                    TxPosition {
383                        ledger: 0,
384                        index: 0,
385                    },
386                    e,
387                    false,
388                    n,
389                ),
390                None => Ok(Vec::new()),
391            }
392        }
393        .map_err(internal)?;
394        let mut next = None;
395        if list.len() == n
396            && let Some(last) = list.last()
397        {
398            next = Some(if forward {
399                TxPosition {
400                    ledger: last.at.ledger,
401                    index: last.at.index.wrapping_add(1),
402                }
403            } else {
404                last.at
405            });
406        }
407        let mut keep: Vec<AccountTx> = Vec::with_capacity(list.len());
408        for t in list {
409            if (t.at.ledger < min && !forward) || (t.at.ledger > max && forward) {
410                next = None;
411                break;
412            }
413            if t.at.ledger > max && !forward {
414                continue;
415            }
416            keep.push(t);
417        }
418        let mut out = Vec::with_capacity(keep.len());
419        self.txs_at(&keep, &mut |t, tx, meta, h| {
420            let mut obj = Map::new();
421            if binary {
422                obj.insert("tx_blob".into(), json!(hex::encode_upper(tx)));
423                obj.insert(
424                    if api > 1 { "meta_blob" } else { "meta" }.into(),
425                    json!(hex::encode_upper(meta)),
426                );
427                obj.insert("ledger_index".into(), json!(t.at.ledger));
428                obj.insert("date".into(), json!(h.close_time));
429            } else {
430                let e = self.expand(tx, meta, t.at.ledger, api, false, false)?;
431                let mut tj = e.tx;
432                tj.insert("ledger_index".into(), json!(t.at.ledger));
433                tj.insert("date".into(), json!(h.close_time));
434                if api > 1 {
435                    obj.insert("ledger_index".into(), json!(t.at.ledger));
436                    if let Some(hv) = tj.remove("hash") {
437                        obj.insert("hash".into(), hv);
438                    }
439                    obj.insert("close_time_iso".into(), json!(time_iso(h.close_time)));
440                    obj.insert("ledger_hash".into(), json!(hex::encode_upper(h.hash())));
441                }
442                obj.insert("meta".into(), Value::Object(e.meta));
443                obj.insert(
444                    if api > 1 { "tx_json" } else { "tx" }.into(),
445                    Value::Object(tj),
446                );
447            }
448            obj.insert("validated".into(), json!(true));
449            out.push(Value::Object(obj));
450            Ok(())
451        })?;
452        let mut m = Map::new();
453        m.insert("nft_id".into(), json!(hex::encode_upper(id)));
454        m.insert("ledger_index_min".into(), json!(min));
455        m.insert("ledger_index_max".into(), json!(max));
456        m.insert("transactions".into(), Value::Array(out));
457        m.insert("validated".into(), json!(true));
458        if let Some(mk) = next {
459            m.insert(
460                "marker".into(),
461                json!({"ledger": mk.ledger, "seq": mk.index}),
462            );
463        }
464        if let Some(l) = take {
465            m.insert("limit".into(), json!(l));
466        }
467        Ok(m)
468    }
469
470    pub(crate) fn account_nfts(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
471        // Clio checks the fields in this order: account, marker, limit.
472        account_id(
473            p.get("account")
474                .ok_or_else(|| invalid_params("Required field 'account' missing"))?,
475        )?;
476        let marker = hex256(p, "marker")?;
477        let limit = limit(p, NFTS_LIMIT_MIN, NFTS_LIMIT_MAX, NFTS_LIMIT_DEFAULT)?;
478        let (account, seq, hash) = self.owner_of(p)?;
479        let mut m = Map::new();
480        m.insert("ledger_hash".into(), json!(hex::encode_upper(hash)));
481        m.insert("ledger_index".into(), json!(seq));
482        m.insert("validated".into(), json!(true));
483        m.insert("account".into(), p["account"].clone());
484        m.insert("limit".into(), json!(limit));
485        let mut key = marker.unwrap_or_else(|| {
486            let mut last = [0xFFu8; 32];
487            last[..20].copy_from_slice(&account);
488            last
489        });
490        let mut nfts = Vec::new();
491        let Some(mut data) = self.fetch(&key, seq)? else {
492            if marker.is_some() {
493                return Err(invalid_params(
494                    "Marker field does not match any valid Page ID",
495                ));
496            }
497            m.insert("account_nfts".into(), Value::Array(nfts));
498            return Ok(m);
499        };
500        let mut node = xrpl_json::ledger_entry(&key, &data).map_err(internal)?;
501        // Like Clio, only the type of the marker's object is checked, not whose page it is.
502        if entry_type(&node) != "NFTokenPage" {
503            return Err(invalid_params(
504                "Marker matches Page ID from another Account",
505            ));
506        }
507        let mut pages = 0;
508        loop {
509            crate::limits::check_rpc()?;
510            for t in node
511                .get("NFTokens")
512                .and_then(Value::as_array)
513                .ok_or_else(|| corrupt(&key, "NFT page without NFTokens"))?
514            {
515                nfts.push(token_json(&key, t)?);
516            }
517            pages += 1;
518            let previous = h256(&node, "PreviousPageMin");
519            if previous == [0; 32] {
520                break;
521            }
522            if pages == limit {
523                m.insert("marker".into(), json!(hex::encode_upper(previous)));
524                break;
525            }
526            data = self.fetch(&previous, seq)?.ok_or_else(|| {
527                corrupt(
528                    &previous,
529                    "PreviousPageMin points to a nonexistent NFT page",
530                )
531            })?;
532            key = previous;
533            node = xrpl_json::ledger_entry(&key, &data).map_err(internal)?;
534        }
535        m.insert("account_nfts".into(), Value::Array(nfts));
536        Ok(m)
537    }
538
539    pub(crate) fn nft_buy_offers(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
540        self.nft_offers(p, b'h')
541    }
542
543    pub(crate) fn nft_sell_offers(&self, p: &Map<String, Value>) -> Res<Map<String, Value>> {
544        self.nft_offers(p, b'i')
545    }
546
547    /// Clio's `NFTOffersHandlerBase::iterateOfferDirectory`.
548    fn nft_offers(&self, p: &Map<String, Value>, space: u8) -> Res<Map<String, Value>> {
549        let id = hex256(p, "nft_id")?
550            .ok_or_else(|| invalid_params("Required field 'nft_id' missing"))?;
551        let limit = limit(p, OFFERS_LIMIT_MIN, OFFERS_LIMIT_MAX, OFFERS_LIMIT_DEFAULT)?;
552        let marker = hex256(p, "marker")?;
553        let seq = self.resolve_state(p)?;
554        let root = keylet(space, &[&id]);
555        if self.fetch(&root, seq)?.is_none() {
556            return Err(rpc_err("objectNotFound", 92, "notFound"));
557        }
558        let mut offers = Vec::new();
559        // Without a marker one more offer than the limit is read: it starts
560        // the next page. With one, the marker's offer comes first and counts
561        // as that extra one.
562        let (reserve, after, hint) = match marker {
563            Some(k) => {
564                let node = self
565                    .fetch(&k, seq)?
566                    .map(|d| xrpl_json::ledger_entry(&k, &d).map_err(internal))
567                    .transpose()?
568                    .filter(|n| entry_type(n) == "NFTokenOffer" && h256(n, "NFTokenID") == id)
569                    .ok_or_else(|| invalid_params("Invalid parameters."))?;
570                // Clio passes the u64 page number on as u32.
571                let hint = node
572                    .get("NFTokenOfferNode")
573                    .and_then(Value::as_str)
574                    .and_then(|s| u64::from_str_radix(s, 16).ok())
575                    .unwrap_or(0) as u32;
576                offers.push((k, node));
577                (limit, k, hint)
578            }
579            None => (limit + 1, [0; 32], 0),
580        };
581        let (keys, _) = self.dir_walk(&root, seq, reserve, after, hint)?;
582        let objects = self.state.get_many(&keys, seq).map_err(internal)?;
583        let mut walked = 0;
584        for (key, data) in keys.iter().zip(objects) {
585            let data =
586                data.ok_or_else(|| corrupt(key, "offer from the NFT offer directory is missing"))?;
587            let node = xrpl_json::ledger_entry(key, &data).map_err(internal)?;
588            if entry_type(&node) == "NFTokenOffer" {
589                offers.push((*key, node));
590                walked += 1;
591            }
592        }
593        let mut m = Map::new();
594        m.insert("nft_id".into(), p["nft_id"].clone());
595        m.insert("validated".into(), json!(true));
596        let mut next = None;
597        if walked == reserve {
598            next = offers.pop().map(|(k, _)| k);
599        }
600        let offers = offers
601            .iter()
602            .map(|(k, n)| offer_json(k, n))
603            .collect::<Res<Vec<_>>>()?;
604        m.insert("offers".into(), Value::Array(offers));
605        if let Some(k) = next {
606            m.insert("marker".into(), json!(hex::encode_upper(k)));
607            m.insert("limit".into(), json!(limit));
608        }
609        Ok(m)
610    }
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616
617    #[test]
618    fn token_id_parts() {
619        // An NFT minted with flags 8, a 5% transfer fee, taxon 0, serial 0.
620        let mut id = [0u8; 32];
621        id[0..2].copy_from_slice(&8u16.to_be_bytes());
622        id[2..4].copy_from_slice(&5000u16.to_be_bytes());
623        id[4..24].copy_from_slice(&[7u8; 20]);
624        id[24..28].copy_from_slice(&2459u32.to_be_bytes());
625        let t = token_id(&id);
626        assert_eq!(
627            t,
628            TokenId {
629                flags: 8,
630                transfer_fee: 5000,
631                issuer: [7; 20],
632                taxon: 0,
633                serial: 0,
634            }
635        );
636    }
637
638    #[test]
639    fn limits_and_hex_fields_like_clio() {
640        let p = |v: Value| v.as_object().cloned().unwrap();
641        assert_eq!(limit(&p(json!({})), 20, 400, 100), Ok(100));
642        assert_eq!(limit(&p(json!({"limit": 1})), 20, 400, 100), Ok(20));
643        assert_eq!(limit(&p(json!({"limit": 9999})), 20, 400, 100), Ok(400));
644        assert!(limit(&p(json!({"limit": 0})), 20, 400, 100).is_err());
645        assert!(limit(&p(json!({"limit": "5"})), 20, 400, 100).is_err());
646        assert_eq!(hex256(&p(json!({})), "marker"), Ok(None));
647        let e = hex256(&p(json!({"marker": 5})), "marker").unwrap_err();
648        assert_eq!(e.message, "markerNotString");
649        let e = hex256(&p(json!({"marker": "AB"})), "marker").unwrap_err();
650        assert_eq!(e.message, "markerMalformed");
651    }
652}