Alloy

Kết nối với 256 Blocks bằng Alloy cho Rust

Alloy là một thư viện Rust hiệu suất cao để kết nối các ứng dụng với blockchain. Đây là lựa chọn được khuyến nghị cho các dự án Rust mới, cung cấp API hiện đại với tài liệu xuất sắc.

Cài đặt

Thêm vào Cargo.toml của bạn:

[dependencies]
alloy = { version = "0.9", features = ["full"] }
tokio = { version = "1", features = ["full"] }
eyre = "0.6"

Bắt đầu nhanh

Kết nối với 256 Blocks bằng header X-API-Key:

use alloy::{
    providers::{Provider, ProviderBuilder},
    rpc::client::RpcClient,
    transports::http::{
        reqwest::{
            header::{HeaderMap, HeaderValue},
            Client,
        },
        Http,
    },
};
use eyre::Result;
 
#[tokio::main]
async fn main() -> Result<()> {
    // Set the X-API-Key header
    let mut headers = HeaderMap::new();
    headers.insert("X-API-Key", HeaderValue::from_static("your-api-key"));
 
    // Create the reqwest client with custom headers
    let client = Client::builder().default_headers(headers).build()?;
 
    // Create the HTTP transport
    let rpc_url = "https://rpc.256blocks.com/ethereum".parse()?;
    let http = Http::with_client(client, rpc_url);
    let rpc_client = RpcClient::new(http, false);
 
    // Create the provider
    let provider = ProviderBuilder::new().on_client(rpc_client);
 
    // Get the latest block number
    let block_number = provider.get_block_number().await?;
    println!("Latest block: {}", block_number);
 
    Ok(())
}

Đọc Số dư Tài khoản

use alloy::{
    primitives::{utils::format_units, Address},
    providers::{Provider, ProviderBuilder},
    rpc::client::RpcClient,
    transports::http::{
        reqwest::{
            header::{HeaderMap, HeaderValue},
            Client,
        },
        Http,
    },
};
use eyre::Result;
 
#[tokio::main]
async fn main() -> Result<()> {
    let mut headers = HeaderMap::new();
    headers.insert("X-API-Key", HeaderValue::from_static("your-api-key"));
 
    let client = Client::builder().default_headers(headers).build()?;
    let rpc_url = "https://rpc.256blocks.com/ethereum".parse()?;
    let http = Http::with_client(client, rpc_url);
    let rpc_client = RpcClient::new(http, false);
 
    let provider = ProviderBuilder::new().on_client(rpc_client);
 
    // Get account balance
    let address: Address = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb".parse()?;
    let balance = provider.get_balance(address).await?;
 
    // Convert wei to ether using format_units (preserves precision)
    let ether = format_units(balance, "ether")?;
    println!("Balance: {} ETH", ether);
 
    Ok(())
}

Đọc Dữ liệu Hợp đồng

use alloy::{
    primitives::{Address, U256},
    providers::{Provider, ProviderBuilder},
    rpc::client::RpcClient,
    sol,
    transports::http::{
        reqwest::{
            header::{HeaderMap, HeaderValue},
            Client,
        },
        Http,
    },
};
use eyre::Result;
 
// Define the ERC-20 interface using the sol! macro
sol! {
    #[sol(rpc)]
    interface IERC20 {
        function balanceOf(address account) external view returns (uint256);
        function decimals() external view returns (uint8);
        function symbol() external view returns (string);
    }
}
 
#[tokio::main]
async fn main() -> Result<()> {
    let mut headers = HeaderMap::new();
    headers.insert("X-API-Key", HeaderValue::from_static("your-api-key"));
 
    let client = Client::builder().default_headers(headers).build()?;
    let rpc_url = "https://rpc.256blocks.com/ethereum".parse()?;
    let http = Http::with_client(client, rpc_url);
    let rpc_client = RpcClient::new(http, false);
 
    let provider = ProviderBuilder::new().on_client(rpc_client);
 
    // USDC contract on Ethereum
    let usdc_address: Address = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48".parse()?;
    let account: Address = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb".parse()?;
 
    // Create contract instance
    let contract = IERC20::new(usdc_address, &provider);
 
    // Call contract methods
    let balance = contract.balanceOf(account).call().await?;
    let decimals = contract.decimals().call().await?;
 
    println!("USDC Balance: {}", balance._0);
    println!("Decimals: {}", decimals._0);
 
    Ok(())
}

Hỗ trợ Đa chuỗi

Kết nối với các chuỗi khác nhau bằng cách thay đổi endpoint:

use alloy::{
    providers::{Provider, ProviderBuilder},
    rpc::client::RpcClient,
    transports::http::{
        reqwest::{
            header::{HeaderMap, HeaderValue},
            Client,
        },
        Http,
    },
};
use eyre::Result;
 
fn create_provider(chain: &str, api_key: &str) -> Result<impl Provider> {
    let mut headers = HeaderMap::new();
    headers.insert("X-API-Key", HeaderValue::from_str(api_key)?);
 
    let client = Client::builder().default_headers(headers).build()?;
    let rpc_url = format!("https://rpc.256blocks.com/{}", chain).parse()?;
    let http = Http::with_client(client, rpc_url);
    let rpc_client = RpcClient::new(http, false);
 
    Ok(ProviderBuilder::new().on_client(rpc_client))
}
 
#[tokio::main]
async fn main() -> Result<()> {
    // Create providers for different chains
    let eth_provider = create_provider("ethereum", "your-api-key")?;
    let base_provider = create_provider("base", "your-api-key")?;
    let arb_provider = create_provider("arbitrum", "your-api-key")?;
    let polygon_provider = create_provider("polygon", "your-api-key")?;
 
    // Use providers...
    let eth_block = eth_provider.get_block_number().await?;
    println!("Ethereum block: {}", eth_block);
 
    Ok(())
}

Tài nguyên

Alloy | 256 Blocks