Skip to main content

ledger_engine/
nftindex.rs

1//! What NFT transactions do to tokens, for the NFT index (`nft_info`,
2//! `nft_history`, `nfts_by_issuer`), following Clio's `NFTHelpers`.
3//!
4//! Only successful transactions count. Each one lists the tokens whose history
5//! it belongs to; a mint, a burn or an accepted offer also gives the token's
6//! owner after it (a burn marks the token burned), a mint and NFTokenModify its
7//! URI. Owners come from the metadata, the way Clio finds them: the minted token
8//! is the one added to the NFT pages, and the owner of a page is the first 20
9//! bytes of its key.
10//!
11//! Within a ledger the last change of each kind wins. Clio keeps one record per
12//! token per ledger, so a token minted and then sold in the same ledger loses
13//! its URI and its place in the issuer's list there; here the mint's URI and
14//! issuer entry stay.
15
16use std::collections::{BTreeMap, BTreeSet};
17
18use serde_json::{Map, Value};
19
20use crate::ledger::Ledger;
21use crate::xrpl_json;
22
23pub type TokenId = [u8; 32];
24
25/// What one transaction did.
26#[derive(Debug, Default, PartialEq, Eq)]
27pub struct NftTx {
28    /// Tokens whose history includes this transaction, without repeats.
29    pub tokens: Vec<TokenId>,
30    /// Owner after the transaction, and whether the token is burned.
31    pub owner: Option<(TokenId, [u8; 20], bool)>,
32    /// URI after the transaction (empty if it has none).
33    pub uri: Option<(TokenId, Vec<u8>)>,
34    /// The token was minted.
35    pub minted: bool,
36}
37
38/// What a ledger did to tokens.
39#[derive(Debug, Default, PartialEq, Eq)]
40pub struct NftLedger {
41    /// Token, TransactionIndex and position in the ledger's transaction list.
42    pub txs: Vec<(TokenId, u32, u32)>,
43    pub owners: BTreeMap<TokenId, ([u8; 20], bool)>,
44    pub uris: BTreeMap<TokenId, Vec<u8>>,
45    pub minted: BTreeSet<TokenId>,
46    /// Transactions whose effect could not be read, with the reason. Their
47    /// history entries are kept; the owner or URI change is not.
48    pub problems: Vec<String>,
49}
50
51/// TransactionType of a serialized transaction without decoding it: the
52/// field is first in canonical order.
53fn tx_type(tx: &[u8]) -> Option<&'static str> {
54    if tx.len() < 3 || tx[0] != 0x12 {
55        return None;
56    }
57    xrpl_json::definitions().transaction_type(u16::from_be_bytes([tx[1], tx[2]]))
58}
59
60fn h256(v: Option<&Value>) -> Option<TokenId> {
61    v.and_then(Value::as_str)
62        .and_then(|s| hex::decode(s).ok())
63        .and_then(|b| b.try_into().ok())
64}
65
66fn account(v: Option<&Value>) -> Option<[u8; 20]> {
67    v.and_then(Value::as_str)
68        .and_then(crate::api::decode_account)
69}
70
71/// Affected nodes as (kind, node): kind is CreatedNode, ModifiedNode or DeletedNode.
72fn nodes(meta: &Map<String, Value>) -> Vec<(&str, &Map<String, Value>)> {
73    meta.get("AffectedNodes")
74        .and_then(Value::as_array)
75        .into_iter()
76        .flatten()
77        .filter_map(Value::as_object)
78        .filter_map(|n| {
79            let (k, v) = n.iter().next()?;
80            Some((k.as_str(), v.as_object()?))
81        })
82        .collect()
83}
84
85fn entry_type(node: &Map<String, Value>) -> &str {
86    node.get("LedgerEntryType")
87        .and_then(Value::as_str)
88        .unwrap_or_default()
89}
90
91fn fields<'a>(node: &'a Map<String, Value>, which: &str) -> Option<&'a Map<String, Value>> {
92    node.get(which).and_then(Value::as_object)
93}
94
95/// Token IDs of an NFTokens array.
96fn token_ids(f: Option<&Map<String, Value>>) -> Option<Vec<TokenId>> {
97    let arr = f?.get("NFTokens")?.as_array()?;
98    Some(
99        arr.iter()
100            .filter_map(|t| h256(t.get("NFToken").and_then(|n| n.get("NFTokenID"))))
101            .collect(),
102    )
103}
104
105/// Owner of an NFT page: the first 20 bytes of its key.
106fn page_owner(node: &Map<String, Value>) -> Option<[u8; 20]> {
107    h256(node.get("LedgerIndex")).and_then(|k| k[..20].try_into().ok())
108}
109
110fn uri_of(tx: &Map<String, Value>) -> Vec<u8> {
111    tx.get("URI")
112        .and_then(Value::as_str)
113        .and_then(|s| hex::decode(s).ok())
114        .unwrap_or_default()
115}
116
117fn mint(tx: &Map<String, Value>, meta: &Map<String, Value>) -> Result<NftTx, String> {
118    let (mut prev, mut fin) = (Vec::new(), Vec::new());
119    let mut owner = None;
120    for (kind, n) in nodes(meta) {
121        if entry_type(n) != "NFTokenPage" {
122            continue;
123        }
124        if owner.is_none() {
125            owner = page_owner(n);
126        }
127        if kind == "CreatedNode" {
128            fin.extend(token_ids(fields(n, "NewFields")).unwrap_or_default());
129        } else {
130            // A page linked to a new one changes only its links: no tokens before.
131            let Some(p) = token_ids(fields(n, "PreviousFields")) else {
132                continue;
133            };
134            prev.extend(p);
135            fin.extend(token_ids(fields(n, "FinalFields")).unwrap_or_default());
136        }
137    }
138    prev.sort_unstable();
139    fin.sort_unstable();
140    let added = fin
141        .iter()
142        .zip(prev.iter().map(Some).chain(std::iter::repeat(None)))
143        .find(|(f, p)| Some(*f) != *p)
144        .map(|(f, _)| *f);
145    match (added, owner) {
146        (Some(id), Some(o)) if fin.len() == prev.len() + 1 => Ok(NftTx {
147            tokens: vec![id],
148            owner: Some((id, o, false)),
149            uri: Some((id, uri_of(tx))),
150            minted: true,
151        }),
152        _ => Err("NFTokenMint: no minted token in the metadata".into()),
153    }
154}
155
156fn burn(tx: &Map<String, Value>, meta: &Map<String, Value>) -> Result<NftTx, String> {
157    let id = h256(tx.get("NFTokenID")).ok_or("NFTokenBurn without NFTokenID")?;
158    for (kind, n) in nodes(meta) {
159        if entry_type(n) != "NFTokenPage" || kind == "CreatedNode" {
160            continue;
161        }
162        // The page held the token before the burn: in PreviousFields if the
163        // page was changed, else in FinalFields of a page deleted unchanged.
164        let before = if n.contains_key("PreviousFields") {
165            token_ids(fields(n, "PreviousFields"))
166        } else if kind == "DeletedNode" {
167            token_ids(fields(n, "FinalFields"))
168        } else {
169            None
170        };
171        if before.is_some_and(|b| b.contains(&id))
172            && let Some(o) = page_owner(n)
173        {
174            return Ok(NftTx {
175                tokens: vec![id],
176                owner: Some((id, o, true)),
177                ..NftTx::default()
178            });
179        }
180    }
181    Err("NFTokenBurn: owner at burn time not found".into())
182}
183
184fn accept(tx: &Map<String, Value>, meta: &Map<String, Value>) -> Result<NftTx, String> {
185    let ns = nodes(meta);
186    let offer = |field: &str| -> Option<&Map<String, Value>> {
187        let key = h256(tx.get(field))?;
188        ns.iter()
189            .find(|(_, n)| h256(n.get("LedgerIndex")) == Some(key))
190            .and_then(|(_, n)| fields(n, "FinalFields"))
191    };
192    let done = |id, o| NftTx {
193        tokens: vec![id],
194        owner: Some((id, o, false)),
195        ..NftTx::default()
196    };
197    // With a buy offer the new owner is the buyer.
198    if tx.contains_key("NFTokenBuyOffer") {
199        let f = offer("NFTokenBuyOffer").ok_or("NFTokenAcceptOffer: buy offer not in metadata")?;
200        let id = h256(f.get("NFTokenID")).ok_or("buy offer without NFTokenID")?;
201        let o = account(f.get("Owner")).ok_or("buy offer without Owner")?;
202        return Ok(done(id, o));
203    }
204    // Otherwise the page that now holds the token and isn't the seller's.
205    let f = offer("NFTokenSellOffer").ok_or("NFTokenAcceptOffer: sell offer not in metadata")?;
206    let id = h256(f.get("NFTokenID")).ok_or("sell offer without NFTokenID")?;
207    let seller = account(f.get("Owner")).ok_or("sell offer without Owner")?;
208    for (kind, n) in &ns {
209        if entry_type(n) != "NFTokenPage" || *kind == "DeletedNode" {
210            continue;
211        }
212        let Some(o) = page_owner(n).filter(|o| *o != seller) else {
213            continue;
214        };
215        let now = if *kind == "CreatedNode" {
216            fields(n, "NewFields")
217        } else {
218            fields(n, "FinalFields")
219        };
220        if token_ids(now).is_some_and(|t| t.contains(&id)) {
221            return Ok(done(id, o));
222        }
223    }
224    Err("NFTokenAcceptOffer: new owner not found".into())
225}
226
227/// The tokens of the offers a cancel deleted, each once.
228fn cancel(meta: &Map<String, Value>) -> NftTx {
229    let mut tokens: Vec<TokenId> = nodes(meta)
230        .into_iter()
231        .filter(|(_, n)| entry_type(n) == "NFTokenOffer")
232        .filter_map(|(_, n)| h256(fields(n, "FinalFields")?.get("NFTokenID")))
233        .collect();
234    tokens.sort_unstable();
235    tokens.dedup();
236    NftTx {
237        tokens,
238        ..NftTx::default()
239    }
240}
241
242/// What a transaction did to tokens, from its JSON; `Ok(None)` if it is not
243/// a successful NFT transaction.
244pub fn nft_tx_json(
245    tx: &Map<String, Value>,
246    meta: &Map<String, Value>,
247) -> Result<Option<NftTx>, String> {
248    if meta.get("TransactionResult").and_then(Value::as_str) != Some("tesSUCCESS") {
249        return Ok(None);
250    }
251    let token = || h256(tx.get("NFTokenID")).ok_or("no NFTokenID");
252    let out = match tx.get("TransactionType").and_then(Value::as_str) {
253        Some("NFTokenMint") => mint(tx, meta)?,
254        Some("NFTokenBurn") => burn(tx, meta)?,
255        Some("NFTokenAcceptOffer") => accept(tx, meta)?,
256        Some("NFTokenCancelOffer") => cancel(meta),
257        Some("NFTokenCreateOffer") => NftTx {
258            tokens: vec![token()?],
259            ..NftTx::default()
260        },
261        Some("NFTokenModify") => {
262            let id = token()?;
263            NftTx {
264                tokens: vec![id],
265                uri: Some((id, uri_of(tx))),
266                ..NftTx::default()
267            }
268        }
269        _ => return Ok(None),
270    };
271    Ok(Some(out))
272}
273
274/// What a ledger's transactions did to tokens, applied in TransactionIndex
275/// order. It never fails: a transaction that can't be decoded or read (say, a
276/// field from an amendment this build doesn't know) goes to `problems`, so the
277/// index never holds up loading.
278pub fn nft_ledger(ledger: &Ledger) -> NftLedger {
279    let mut found = Vec::new();
280    let mut out = NftLedger::default();
281    for (pos, (tx, meta)) in ledger.transactions.iter().enumerate() {
282        let Some(kind) = tx_type(tx).filter(|t| t.starts_with("NFToken")) else {
283            continue;
284        };
285        let id = hex::encode_upper(witness_core::shamap::tx_id(tx));
286        let decoded = xrpl_json::transaction(tx).and_then(|t| {
287            let m = xrpl_json::metadata(meta)?;
288            let index = m
289                .get("TransactionIndex")
290                .and_then(Value::as_u64)
291                .and_then(|i| u32::try_from(i).ok())
292                .ok_or("metadata without TransactionIndex")?;
293            Ok((t, m, index))
294        });
295        let (t, m, index) = match decoded {
296            Ok(d) => d,
297            Err(e) => {
298                out.problems.push(format!("{id} {kind}: {e}"));
299                continue;
300            }
301        };
302        let r = nft_tx_json(&t, &m).map_err(|e| format!("{id} {kind}: {e}"));
303        found.push((index, pos as u32, r, h256(t.get("NFTokenID"))));
304    }
305    found.sort_by_key(|f| f.0);
306    for (index, pos, r, named) in found {
307        match r {
308            Ok(Some(x)) => {
309                for t in &x.tokens {
310                    out.txs.push((*t, index, pos));
311                }
312                if let Some((t, o, burned)) = x.owner {
313                    out.owners.insert(t, (o, burned));
314                }
315                if let Some((t, u)) = x.uri {
316                    out.uris.insert(t, u);
317                }
318                if x.minted
319                    && let Some(t) = x.tokens.first()
320                {
321                    out.minted.insert(*t);
322                }
323            }
324            Ok(None) => {}
325            Err(e) => {
326                // The history entry is still known when the transaction names its token.
327                if let Some(t) = named {
328                    out.txs.push((t, index, pos));
329                }
330                out.problems.push(e);
331            }
332        }
333    }
334    out
335}
336
337/// The tokens of an NFT page in the state, as rows that put each token at
338/// the page's owner: the starting point for a store whose history begins
339/// after the first NFTs, as Clio fills its tables from its first ledger.
340pub fn nft_page(key: &[u8; 32], data: &[u8]) -> Option<NftLedger> {
341    // LedgerEntryType 0x0050, the first field of an object.
342    if data.len() < 3 || data[0] != 0x11 || u16::from_be_bytes([data[1], data[2]]) != 0x0050 {
343        return None;
344    }
345    let node = xrpl_json::ledger_entry(key, data).ok()?;
346    let owner: [u8; 20] = key[..20].try_into().ok()?;
347    let mut out = NftLedger::default();
348    for t in node.get("NFTokens")?.as_array()? {
349        let n = t.get("NFToken")?;
350        let id = h256(n.get("NFTokenID"))?;
351        let uri = n
352            .get("URI")
353            .and_then(Value::as_str)
354            .and_then(|s| hex::decode(s).ok())
355            .unwrap_or_default();
356        out.owners.insert(id, (owner, false));
357        out.uris.insert(id, uri);
358        out.minted.insert(id);
359    }
360    Some(out)
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366    use serde_json::json;
367
368    fn obj(v: Value) -> Map<String, Value> {
369        v.as_object().cloned().unwrap()
370    }
371
372    fn id(b: u8) -> String {
373        hex::encode_upper([b; 32])
374    }
375
376    fn page(owner: u8, low: u8) -> String {
377        let mut k = [owner; 32];
378        k[20..].fill(low);
379        hex::encode_upper(k)
380    }
381
382    fn tokens(ids: &[u8]) -> Value {
383        json!(
384            ids.iter()
385                .map(|b| json!({"NFToken": {"NFTokenID": id(*b)}}))
386                .collect::<Vec<_>>()
387        )
388    }
389
390    const OK: &str = "tesSUCCESS";
391
392    #[test]
393    fn mint_finds_the_added_token_and_owner() {
394        let tx = obj(json!({"TransactionType": "NFTokenMint", "URI": "ABCD"}));
395        let meta = obj(json!({"TransactionResult": OK, "AffectedNodes": [
396            {"ModifiedNode": {"LedgerEntryType": "AccountRoot", "LedgerIndex": id(9)}},
397            {"ModifiedNode": {"LedgerEntryType": "NFTokenPage", "LedgerIndex": page(7, 0xFF),
398                "PreviousFields": {"NFTokens": tokens(&[1, 3])},
399                "FinalFields": {"NFTokens": tokens(&[1, 2, 3])}}},
400        ]}));
401        let r = nft_tx_json(&tx, &meta).unwrap().unwrap();
402        assert_eq!(r.tokens, vec![[2; 32]]);
403        assert_eq!(r.owner, Some(([2; 32], [7; 20], false)));
404        assert_eq!(r.uri, Some(([2; 32], vec![0xAB, 0xCD])));
405        assert!(r.minted);
406    }
407
408    #[test]
409    fn mint_into_a_new_page_and_a_page_relinked_only() {
410        let tx = obj(json!({"TransactionType": "NFTokenMint"}));
411        let meta = obj(json!({"TransactionResult": OK, "AffectedNodes": [
412            {"CreatedNode": {"LedgerEntryType": "NFTokenPage", "LedgerIndex": page(7, 0x10),
413                "NewFields": {"NFTokens": tokens(&[1, 4])}}},
414            {"ModifiedNode": {"LedgerEntryType": "NFTokenPage", "LedgerIndex": page(7, 0xFF),
415                "PreviousFields": {"NFTokens": tokens(&[1, 5])},
416                "FinalFields": {"NFTokens": tokens(&[5])}}},
417            {"ModifiedNode": {"LedgerEntryType": "NFTokenPage", "LedgerIndex": page(7, 0x01),
418                "PreviousFields": {"NextPageMin": page(7, 0xFF)},
419                "FinalFields": {"NFTokens": tokens(&[0])}}},
420        ]}));
421        let r = nft_tx_json(&tx, &meta).unwrap().unwrap();
422        assert_eq!(r.tokens, vec![[4; 32]]);
423        assert_eq!(r.uri, Some(([4; 32], vec![])));
424    }
425
426    #[test]
427    fn burn_takes_the_owner_from_the_page_that_held_it() {
428        let tx = obj(json!({"TransactionType": "NFTokenBurn", "NFTokenID": id(2)}));
429        let meta = obj(json!({"TransactionResult": OK, "AffectedNodes": [
430            {"DeletedNode": {"LedgerEntryType": "NFTokenPage", "LedgerIndex": page(8, 0xFF),
431                "FinalFields": {"NFTokens": tokens(&[2])}}},
432        ]}));
433        let r = nft_tx_json(&tx, &meta).unwrap().unwrap();
434        assert_eq!(r.owner, Some(([2; 32], [8; 20], true)));
435        assert!(!r.minted);
436    }
437
438    #[test]
439    fn accept_by_buy_or_sell_offer() {
440        let buyer = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh";
441        let tx = obj(json!({"TransactionType": "NFTokenAcceptOffer", "NFTokenBuyOffer": id(5)}));
442        let meta = obj(json!({"TransactionResult": OK, "AffectedNodes": [
443            {"DeletedNode": {"LedgerEntryType": "NFTokenOffer", "LedgerIndex": id(5),
444                "FinalFields": {"NFTokenID": id(2), "Owner": buyer}}},
445        ]}));
446        let r = nft_tx_json(&tx, &meta).unwrap().unwrap();
447        let b = crate::api::decode_account(buyer).unwrap();
448        assert_eq!(r.owner, Some(([2; 32], b, false)));
449
450        let seller = crate::xrpl_json::account(&[8; 20]);
451        let tx = obj(json!({"TransactionType": "NFTokenAcceptOffer", "NFTokenSellOffer": id(6)}));
452        let meta = obj(json!({"TransactionResult": OK, "AffectedNodes": [
453            {"DeletedNode": {"LedgerEntryType": "NFTokenOffer", "LedgerIndex": id(6),
454                "FinalFields": {"NFTokenID": id(2), "Owner": seller}}},
455            {"ModifiedNode": {"LedgerEntryType": "NFTokenPage", "LedgerIndex": page(8, 0xFF),
456                "PreviousFields": {"NFTokens": tokens(&[2, 3])},
457                "FinalFields": {"NFTokens": tokens(&[3])}}},
458            {"CreatedNode": {"LedgerEntryType": "NFTokenPage", "LedgerIndex": page(9, 0xFF),
459                "NewFields": {"NFTokens": tokens(&[2])}}},
460        ]}));
461        let r = nft_tx_json(&tx, &meta).unwrap().unwrap();
462        assert_eq!(r.owner, Some(([2; 32], [9; 20], false)));
463    }
464
465    #[test]
466    fn cancel_lists_each_token_once_and_failures_are_ignored() {
467        let tx = obj(json!({"TransactionType": "NFTokenCancelOffer"}));
468        let meta = obj(json!({"TransactionResult": OK, "AffectedNodes": [
469            {"DeletedNode": {"LedgerEntryType": "NFTokenOffer", "LedgerIndex": id(5),
470                "FinalFields": {"NFTokenID": id(2)}}},
471            {"DeletedNode": {"LedgerEntryType": "NFTokenOffer", "LedgerIndex": id(6),
472                "FinalFields": {"NFTokenID": id(2)}}},
473            {"DeletedNode": {"LedgerEntryType": "NFTokenOffer", "LedgerIndex": id(7),
474                "FinalFields": {"NFTokenID": id(1)}}},
475        ]}));
476        let r = nft_tx_json(&tx, &meta).unwrap().unwrap();
477        assert_eq!(r.tokens, vec![[1; 32], [2; 32]]);
478        assert_eq!(r.owner, None);
479        let failed = obj(json!({"TransactionResult": "tecNO_ENTRY", "AffectedNodes": []}));
480        assert_eq!(nft_tx_json(&tx, &failed), Ok(None));
481    }
482
483    #[test]
484    fn modify_sets_the_uri_only() {
485        let tx = obj(json!({"TransactionType": "NFTokenModify", "NFTokenID": id(2)}));
486        let meta = obj(json!({"TransactionResult": OK, "AffectedNodes": []}));
487        let r = nft_tx_json(&tx, &meta).unwrap().unwrap();
488        assert_eq!(r.uri, Some(([2; 32], vec![])));
489        assert_eq!(r.owner, None);
490    }
491}