Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
ethereum-mysql
Ethereum types wrapper for seamless SQLx database integration.
This crate provides SQL-compatible wrappers for Ethereum types (SqlAddress
, SqlU256
), specifically designed for the SQLx async SQL toolkit. It supports multiple databases (MySQL, PostgreSQL, SQLite) through SQLx's feature system.
Features
- Multi-database support: MySQL, PostgreSQL, SQLite via SQLx
- Zero-cost abstractions: Wraps
alloy::primitives
types (Address
,U256
) - Complete type support:
SqlAddress
for Ethereum addresses,SqlU256
for large integers - Arithmetic operations: Full arithmetic support for
SqlU256
(+, -, *, /, %, bitwise, etc.) - 🆕 Primitive operations: Direct arithmetic with Rust primitives (
value * 2
,2 * value
) - Type conversions: Seamless conversion between
SqlU256
and Rust integer types - Compile-time macros: Create addresses at compile time with
sqladdress!
- Constants: Pre-defined useful constants like
SqlAddress::ZERO
,SqlU256::ZERO
- Serde support: Optional JSON serialization with serde
- SQLx native: Implements
sqlx::Type
,sqlx::Encode
, andsqlx::Decode
- Pure Rust: No C dependencies, works with SQLx's pure Rust philosophy
🎯 Key Advantages
🛡️ Automatic Type Safety & Validation
Unlike traditional approaches that require manual string validation, this library provides compile-time and runtime type safety:
// ❌ Traditional approach - error-prone manual validation
async
// ✅ Our approach - automatic validation
async
⚡ Zero Conversion Overhead
Direct database integration without intermediate conversions:
// ❌ Other libraries require conversion steps
let addr_str: String = query_scalar
.bind.fetch_one.await?;
let address = from_str?; // Extra conversion step
// ✅ Our library - direct type retrieval
let address: SqlAddress = query_scalar
.bind.fetch_one.await?; // Direct, no conversion needed
🔥 Intuitive Primitive Operations
Revolutionary arithmetic operations with Rust primitives:
// ❌ Traditional approach - verbose conversions
let fee_rate = U256 from;
let base = U256 from;
let fee = / base;
// ✅ Our approach - direct primitive arithmetic
let fee = balance * 25 / 10000; // Natural, intuitive syntax!
let doubled = balance * 2; // Works both ways
let tripled = 3 * balance; // Much cleaner code
🎯 Bulletproof API Development
Build Web3 APIs with confidence - invalid data is rejected before reaching your business logic:
// 🛡️ This struct definition provides automatic protection
// 🚀 Your handler focuses on business logic, not validation
async
Quick Start
Add to your Cargo.toml
:
# Basic usage default features
= "2.0.0"
# Enable sqlx feature
= { = "2.0.0", = false features = ["sqlx"] }
# Enable all features
= { = "2.0.0", = ["full"] }
Feature Flags
sqlx
- DB support via SQLxserde
- JSON serialization supportdefault
- Enable all features abovefull
- Enable all features above
Usage Examples
Basic Address Creation
use ;
use FromStr;
// Use the zero address constant
let zero = ZERO;
// Create from macro (compile-time validation)
let addr = sqladdress!;
// Create from string (runtime parsing)
let addr2 = from_str.unwrap;
// Create constant addresses
const ADMIN: SqlAddress = sqladdress!;
Basic U256 Usage
use SqlU256;
use FromStr;
// Create from various integer types
let small = from;
let large = from;
// Constants
let zero = ZERO;
// From strings (supports both decimal and hex)
let from_decimal = from_str.unwrap;
let from_hex = from_str.unwrap;
assert_eq!;
// Arithmetic operations
let a = from;
let b = from;
let sum = a + b; // 150
let difference = a - b; // 50
let product = a * b; // 5000
let quotient = a / b; // 2
let remainder = a % b; // 0
// 🆕 NEW: Direct primitive operations (no conversion needed!)
let doubled = a * 2; // SqlU256 * primitive
let tripled = 3 * a; // primitive * SqlU256
let fee = balance * 25 / 10000; // 0.25% fee calculation
let gas_cost = gas_price * 21000; // Direct gas calculation
// Advanced operations
let power = a.pow; // 100^3 = 1,000,000
let square = a.square; // 100^2 = 10,000
let gcd = from.gcd; // 4
// Safe operations
let checked_sum = a.checked_add; // Some(150)
let saturated = a.saturating_sub; // 0
// 🆕 NEW: Comparison operations
assert!; // 100 > 50
assert!; // 50 < 100
assert!; // 100 >= 100
assert!; // 0 < 100
// Min/max operations
let min_val = a.min; // 50
let max_val = a.max; // 100
// Sorting collections
let mut values = vec!;
values.sort; // [0, 100, 200, 300]
// 🔄 Converting back to original types
let sql_value = from;
// Method 1: .inner() - Get reference to inner U256 (zero-cost)
let u256_ref: &U256 = sql_value.inner;
println!;
// Method 2: .into() - Convert to owned U256 (always safe, no try needed!)
let u256_owned: U256 = sql_value.into;
println!;
// Method 3: Auto-deref (thanks to Deref trait)
let u256_deref: U256 = *sql_value; // Automatic dereference
// 🔄 Converting to Rust primitive types (these need try_into)
let back_to_u64: u64 = small.try_into.unwrap;
let too_large = large.; // Error - value too large for u64
// Display format (always hex)
println!; // "0x64"
SQLx Database Integration
use ;
use MySqlPool;
use FromStr;
async
JSON Serialization (with serde feature)
use ;
use ;
let user = User ;
let json = to_string?;
// {
// "id": 1,
// "wallet": "0x742d35Cc6635C0532925a3b8D42cC72b5c2A9A1d",
// "balance": "0x14d1120d7b160000",
// "staked_amount": "0xde0b6b3a7640000"
// }
let parsed: User = from_str?;
// JSON input accepts both formats for SqlU256
let json_with_decimal = r#"{
"id": 1,
"wallet": "0x742d35Cc6635C0532925a3b8D42cC72b5c2A9A1d",
"balance": "1500000000000000000",
"staked_amount": "0xde0b6b3a7640000"
}"#;
let parsed_mixed: User = from_str?;
🚀 Web3 API Integration (Type-Safe User Input)
One of the biggest advantages of this library is automatic validation of user input in API endpoints. No more manual address validation or conversion errors!
use ;
use ;
use MySqlPool;
// ✅ Request structs with automatic validation
// 🎯 API endpoint with zero manual validation needed
async
// 🎯 Example JSON requests that work automatically:
// ✅ Valid request - will be parsed successfully
let valid_json = r#"{
"from": "0x742d35Cc6635C0532925a3b8D42cC72b5c2A9A1d",
"to": "0x8ba1f109551bD432803012645Hac136c82C2c1",
"amount": "1000000000000000000"
}"#;
// ❌ Invalid address - will be rejected during deserialization
let invalid_json = r#"{
"from": "0xinvalid_address",
"to": "0x8ba1f109551bD432803012645Hac136c82C2c1",
"amount": "1000000000000000000"
}"#;
// ✅ Hex amount format also works
let hex_amount_json = r#"{
"from": "0x742d35Cc6635C0532925a3b8D42cC72b5c2A9A1d",
"to": "0x8ba1f109551bD432803012645Hac136c82C2c1",
"amount": "0xde0b6b3a7640000"
}"#;
// 🎯 Integration with web frameworks (example with Axum)
use ;
async
// 🎯 Benefits Summary:
// ✅ Zero manual validation code needed
// ✅ Invalid addresses rejected automatically
// ✅ Type-safe database operations
// ✅ Direct arithmetic with primitives
// ✅ Both hex and decimal input formats supported
// ✅ Impossible to forget validation steps
// ✅ Clean, readable business logic
Database Schema Examples
MySQL
INT AUTO_INCREMENT PRIMARY KEY,
wallet_address BINARY(20) NOT NULL,
balance BINARY(32) NOT NULL,
token_amount BINARY(32) DEFAULT NULL, -- Optional SqlU256 field
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_wallet (wallet_address),
INDEX idx_balance (balance)
);
(
id
Type Safety
// All these work seamlessly with the database
let wei_amount = from_str.unwrap; // 1 ETH
let gwei_price = from; // 20 Gwei
let block_number = from;
// Arithmetic operations work naturally
let total_cost = wei_amount + ; // gas calculation
let next_block = block_number + from;
// Database operations are type-safe
query
.bind // Stored as "0xde0b6b3a7640000"
.bind // Stored as "0x4a817c800"
.bind // Stored as "0x11a5140"
.execute.await?;
Why SQLx?
This library is built specifically for SQLx because:
- Pure Rust: No C dependencies or ORM overhead
- Compile-time safety: SQL queries are checked at compile time
- Async-first: Built for modern async Rust applications
- Multi-database: Single API for multiple database backends
- Performance: Zero-cost abstractions and prepared statements
Requirements
- Rust 1.75+ (2024 edition)
- sqlx_core 0.8+
- alloy 1.0+
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.