helpers.rs
Overview
This file provides utility functions and trait implementations primarily for type conversions, formatting large integers, logging initialization, and parsing custom data structures. It facilitates data transformation and formatting related to numeric types and blockchain-specific data representations within the application. The utilities help bridge raw data formats with application-friendly types and representations, supporting consistent handling and display of numeric and currency data.
Traits and Their Implementations
ToBool Trait
Purpose: Converts an
Option<i64>into anOption<bool>based on integer values.Method:
fn to_bool(&self) -> Option<bool>
Behavior:
Some(0)returnsSome(false).Some(1)returnsSome(true).Any other value or
NonereturnsNone.
Usage Example:
let val: Option<i64> = Some(1); let bool_val = val.to_bool(); // Some(true)
ToInt Trait
Purpose: Converts an
Option<i64>orOption<usize>into anOption<i32>, with overflow checks.Method:
fn to_int(&self) -> Option<i32>
Behavior:
Returns
Some(i32)if the input value fits withini32::MAX.Logs a warning and returns
Noneif conversion would overflow.Returns
Noneif the input isNone.
Usage Example:
let val: Option<i64> = Some(123); let int_val = val.to_int(); // Some(123)
ToOptU64 Trait
Purpose: Converts an
Option<i64>into anOption<u64>.Method:
fn to_opt_u64(&self) -> Option<u64>
Behavior:
Maps
Some(i64)toSome(u64)by direct cast.Returns
Noneif input isNone.
Usage Example:
let val: Option<i64> = Some(42); let u64_val = val.to_opt_u64(); // Some(42u64)
ToFloat Trait
Purpose: Converts an
Option<i64>into anOption<f64>.Method:
fn to_float(&self) -> Option<f64>
Behavior:
Maps
Some(i64)toSome(f64)by casting.Returns
Noneif input isNone.
Usage Example:
let val: Option<i64> = Some(42); let float_val = val.to_float(); // Some(42.0)
Functions
format_big_int
Signature:
pub fn format_big_int(value: Option<String>, format: Option<BigIntFormat>) -> Option<String>Purpose: Formats a hexadecimal string representing a big integer into either decimal or hexadecimal string format.
Parameters:
value: Optional hex string representing the big integer (without "0x" prefix).format: Optional format specifier (BigIntFormat::DECfor decimal).
Returns: An
Option<String>containing the formatted number as a string orNoneif input is invalid.Behavior:
Parses the input hex string into a
BigInt.If
formatis decimal, outputs decimal string.Otherwise, outputs hex string prefixed with "0x" or "-0x" for negative values.
Usage Example:
let hex_str = Some("f744df471cf".to_string()); let formatted = format_big_int(hex_str, None); // Some("0xf744df471cf")
format_big_int_dec
Signature:
pub fn format_big_int_dec(str: Option<String>, format: Option<BigIntFormat>) -> Option<String>Purpose: Formats a decimal string representation of a big integer into either decimal or hexadecimal string format.
Parameters:
str: Optional decimal string representing the big integer.format: Optional format specifier (BigIntFormat::DECfor decimal).
Returns: An
Option<String>containing the formatted number as a string orNoneif input is invalid.Behavior:
Parses the decimal string into a
BigInt.Returns formatted string similar to
format_big_int.
Usage Example:
let dec_str = Some("123456789".to_string()); let formatted = format_big_int_dec(dec_str, Some(BigIntFormat::DEC)); // Some("123456789")
u64_to_string
Signature:
pub fn u64_to_string(value: u64) -> StringPurpose: Encodes a
u64value into a custom hexadecimal string format.Parameters:
value: The unsigned 64-bit integer to convert.
Returns: A hexadecimal
Stringwith a length prefix.Behavior:
Converts the number to a hex string.
Inserts the length of the hex string (minus one) as a hex digit at the start.
Usage Example:
let val = 255u64; let encoded = u64_to_string(val); // e.g., "1ff"
init_tracing
Signature:
pub fn init_tracing()Purpose: Initializes the logging/tracing system with different verbosity levels based on the
NODE_VERBOSEenvironment variable.Behavior:
If
NODE_VERBOSEis set and non-empty, sets several targets toTRACElevel for detailed logs.Otherwise, sets default log levels (
INFOfor gql_server,TRACEfor others).Disables SQLX logging.
Configures output to stderr, disables ANSI colors, includes thread IDs.
Usage: Called during application startup to enable structured logging.
ecc_from_bytes
Signature:
pub fn ecc_from_bytes(bytes: Option<Vec<u8>>) -> anyhow::Result<Option<Vec<OtherCurrency>>>Purpose: Parses a serialized ExtraCurrencyCollection from raw bytes and extracts a vector of
OtherCurrencyinstances.Parameters:
bytes: Optional raw bytes representing a serialized BOC (Bag of Cells) data structure.
Returns: An
anyhow::Resultwrapping anOption<Vec<OtherCurrency>>. ReturnsNoneif input bytes areNone.Behavior:
Reads the provided bytes as a single root BOC.
Deserializes to
ExtraCurrencyCollection.Iterates over currencies, mapping each to an
OtherCurrencywith currency code and value.
Usage Example:
let raw_bytes: Option<Vec<u8>> = Some(vec![/* serialized data */]); let currencies = ecc_from_bytes(raw_bytes)?;
query_order_by_str
Signature:
pub fn query_order_by_str(order_by: Option<Vec<Option<QueryOrderBy>>>) -> StringPurpose: Converts a vector of optional
QueryOrderByitems into a SQLORDER BYclause string.Parameters:
order_by: Optional list of optionalQueryOrderByobjects.
Returns: A
Stringrepresenting theORDER BYclause or an empty string if input is empty or invalid.Behavior:
Filters out invalid or missing entries.
Normalizes the field
"id"to"block_id".Joins formatted order clauses with commas.
Usage Example:
let order_by = Some(vec![Some(QueryOrderBy { path: Some("id".to_string()), direction: Some("ASC".to_string()) })]); let sql_order = query_order_by_str(order_by); // " ORDER BY block_id ASC "
Test Module
Contains a unit test for
format_big_intthat verifies formatting behavior for various hexadecimal input strings, including zero, positive, and negative values.
Important Implementation Details
The file leverages the
num::BigIntlibrary for arbitrary precision integer parsing and formatting.Conversion traits carefully handle overflow and invalid values, logging warnings where appropriate.
The
ecc_from_bytesfunction uses TON blockchain-specific utilities (read_single_root_boc,ExtraCurrencyCollection) to deserialize and extract currency data, indicating interaction with blockchain data structures.The logging setup in
init_tracingusestracing_subscriberto configure layered logging with target-specific filters.
Interactions with Other System Components
Uses types from
crate::schema::graphqlfor currency and ordering representations, linking it to GraphQL schema definitions.Integrates with the
tvm_blockandtvm_typescrates for blockchain data deserialization, indicating connections with blockchain data processing modules.The logging initialization affects the entire application's logging behavior, impacting modules such as
gql_server,data_loader,blockchain_api, andsqlx.
Mermaid Diagram
flowchart TD
A[Traits] -->|ToBool| B[Option<i64> to Option<bool>]
A -->|ToInt| C[Option<i64>/Option<usize> to Option<i32>]
A -->|ToOptU64| D[Option<i64> to Option<u64>]
A -->|ToFloat| E[Option<i64> to Option<f64>]
F[Functions]
F --> G[format_big_int]
F --> H[format_big_int_dec]
F --> I[u64_to_string]
F --> J[init_tracing]
F --> K[ecc_from_bytes]
F --> L[query_order_by_str]
K --> M[tvm_types::read_single_root_boc]
K --> N[tvm_block::ExtraCurrencyCollection]
L --> O[crate::schema::graphql_ext::QueryOrderBy]
J --> P[tracing_subscriber::registry]
J --> Q[tracing_subscriber::filter::Targets]
style A fill:#f9f,stroke:#333,stroke-width:1px
style F fill:#bbf,stroke:#333,stroke-width:1px