xrpl_wasm_stdlib/
lib.rs

1#![doc = include_str!("../../README.md")]
2#![no_std]
3
4// Re-export the r_address macro for convenient access
5pub use xrpl_address_macro::r_address;
6
7pub mod core;
8pub mod host;
9pub mod sfield;
10pub mod types;
11
12/// Complete Developer Guide
13///
14/// This comprehensive guide covers everything you need to develop smart escrows using
15/// the XRPL WebAssembly Standard Library, from getting started to advanced development.
16///
17/// All internal links work properly within this single documentation page.
18#[cfg(doc)]
19#[doc = include_str!("../../docs/comprehensive-guide.md")]
20pub mod guide {}
21
22/// This function is called on panic but only in the WASM architecture. In non-WASM (e.g., in the
23/// Host Simulator) the standard lib is available, which includes a panic handler.
24#[cfg(target_arch = "wasm32")]
25#[panic_handler]
26fn panic(_info: &::core::panic::PanicInfo) -> ! {
27    // This instruction will halt execution of the WASM module.
28    // It's the WASM equivalent of a trap or an unrecoverable error.
29    ::core::arch::wasm32::unreachable();
30}
31
32fn hex_char_to_nibble(c: u8) -> Option<u8> {
33    match c {
34        b'0'..=b'9' => Some(c - b'0'),
35        b'a'..=b'f' => Some(c - b'a' + 10),
36        b'A'..=b'F' => Some(c - b'A' + 10),
37        _ => None,
38    }
39}
40
41/// Decode a 64-hex-character string into a 32-byte array.
42///
43/// The input must be exactly 64 hexadecimal ASCII bytes (lower- or upper-case).
44/// Returns `None` if any character is not a valid hex digit.
45///
46/// Example:
47/// ```
48/// # use xrpl_wasm_stdlib::decode_hex_32;
49/// let hex = *b"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
50/// let bytes = decode_hex_32(&hex).unwrap();
51/// assert_eq!(bytes.len(), 32);
52/// ```
53pub fn decode_hex_32(hex: &[u8; 64]) -> Option<[u8; 32]> {
54    let mut out = [0u8; 32];
55    let mut i = 0;
56    while i < 32 {
57        let high = hex_char_to_nibble(hex[i * 2])?;
58        let low = hex_char_to_nibble(hex[i * 2 + 1])?;
59        out[i] = (high << 4) | low;
60        i += 1;
61    }
62    Some(out)
63}
64
65/// Decode a 40-hex-character string into a 20-byte array.
66///
67/// The input must be exactly 40 hexadecimal ASCII bytes.
68/// Returns `None` if any character is not a valid hex digit.
69///
70/// Example:
71/// ```
72/// # use xrpl_wasm_stdlib::decode_hex_20;
73/// let hex = *b"00112233445566778899aabbccddeeff00112233";
74/// let bytes = decode_hex_20(&hex).unwrap();
75/// assert_eq!(bytes.len(), 20);
76/// ```
77pub fn decode_hex_20(hex: &[u8; 40]) -> Option<[u8; 20]> {
78    let mut out = [0u8; 20];
79    let mut i = 0;
80    while i < 20 {
81        let high = hex_char_to_nibble(hex[i * 2])?;
82        let low = hex_char_to_nibble(hex[i * 2 + 1])?;
83        out[i] = (high << 4) | low;
84        i += 1;
85    }
86    Some(out)
87}