Getting Started
Alloy (Rust)
Connect to PulseChain using the Alloy Rust crate.
Connect to PulseChain using Alloy, the modern Rust library for Ethereum. Alloy is the recommended Rust crate for EVM interaction.
Setup
Add to Cargo.toml:
[dependencies]
alloy = { version = "1", features = ["provider-http", "rpc-types"] }
tokio = { version = "1", features = ["full"] }
eyre = "0.6"
Connect and query
use alloy::providers::{Provider, ProviderBuilder};
use eyre::Result;
#[tokio::main]
async fn main() -> Result<()> {
let rpc_url = "https://rpc.pulsechain.box".parse()?;
let provider = ProviderBuilder::new().connect_http(rpc_url);
let chain_id = provider.get_chain_id().await?;
println!("Chain ID: {}", chain_id); // 369
let block_number = provider.get_block_number().await?;
println!("Block number: {}", block_number);
Ok(())
}
Get balance
use alloy::providers::{Provider, ProviderBuilder};
use eyre::Result;
#[tokio::main]
async fn main() -> Result<()> {
let rpc_url = "https://rpc.pulsechain.box".parse()?;
let provider = ProviderBuilder::new().connect_http(rpc_url);
let address = "0x3693693693693693693693693693693693693693".parse()?;
let balance = provider.get_balance(address).await?;
println!("Balance: {} wei", balance);
Ok(())
}
Get block
use alloy::eips::BlockNumberOrTag;
use alloy::providers::{Provider, ProviderBuilder};
use eyre::Result;
#[tokio::main]
async fn main() -> Result<()> {
let rpc_url = "https://rpc.pulsechain.box".parse()?;
let provider = ProviderBuilder::new().connect_http(rpc_url);
let block = provider
.get_block_by_number(BlockNumberOrTag::Latest)
.await?;
if let Some(block) = block {
println!("Hash: {}", block.header.hash);
println!("Transactions: {}", block.transactions.len());
}
Ok(())
}
Read contract (ERC-20 balance)
use alloy::primitives::{address, U256};
use alloy::providers::{Provider, ProviderBuilder};
use alloy::sol;
use eyre::Result;
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 rpc_url = "https://rpc.pulsechain.box".parse()?;
let provider = ProviderBuilder::new().connect_http(rpc_url);
// WPLS contract
let wpls = IERC20::new(
address!("0xA1077a294dDE1B09bB078844df40758a5D0f9a27"),
&provider,
);
let symbol = wpls.symbol().call().await?;
let decimals = wpls.decimals().call().await?;
println!("Token: {} (decimals: {})", symbol, decimals);
Ok(())
}
For contract calls, add the sol-macro feature:
alloy = { version = "1", features = ["provider-http", "rpc-types", "sol-macro", "contract"] }
