Basic Usage of Neo Rust SDK

This guide covers the fundamental concepts and common operations you'll perform with the Neo Rust SDK.

Project Structure

A typical Neo Rust SDK project might have the following structure:

Project Structure
my-neo-project/
├── Cargo.toml
├── src/
│   ├── main.rs
│   ├── wallet.rs
│   ├── transactions.rs
│   └── contracts.rs
└── assets/
    └── wallet.json

Common Imports

The Neo Rust SDK provides a convenient prelude module that imports most commonly used types and functions:

main.rs
// Import everything from the prelude module
use neo3::prelude::*;

// For more selective imports
// use neo3::wallet::Wallet;
// use neo3::tx::Transaction;
// use neo3::network::NeoClient;
// use neo3::crypto::{KeyPair, Hash160};

Error Handling

The Neo Rust SDK uses a custom Result type for error handling:

error_handling.rs
use neo3::prelude::*;

fn main() -> Result<()> {
    // Using the ? operator with Result
    let wallet = Wallet::load("wallet.json", "password")?;
    
    // Or with explicit handling
    match Wallet::load("wallet.json", "wrong_password") {
        Ok(wallet) => println!("Wallet loaded successfully"),
        Err(e) => eprintln!("Failed to load wallet: {}", e),
    }
    
    Ok(())
}

Asynchronous Operations

Many Neo Rust SDK operations are asynchronous, using the Rust async/await syntax:

async_example.rs
use neo3::prelude::*;

async fn get_balance(address: &str) -> Result<u64> {
    // Connect to Neo TestNet
    let client = NeoClient::connect_to_testnet().await?;
    
    // Get NEO balance for the address
    let balance = client.get_neo_balance(address).await?;
    
    Ok(balance)
}

// Using with tokio runtime
#[tokio::main]
async fn main() -> Result<()> {
    let address = "NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv";
    let balance = get_balance(address).await?;
    println!("NEO balance for {}: {}", address, balance);
    
    Ok(())
}

Basic Wallet Operations

Here are some common wallet operations using the Neo Rust SDK:

wallet_example.rs
use neo3::prelude::*;

fn wallet_examples() -> Result<()> {
    // Create a new wallet
    let mut wallet = Wallet::new();
    
    // Create a new account
    let account = wallet.create_account()?;
    println!("New account address: {}", account.address());
    
    // Save wallet to file
    wallet.save("my_wallet.json", "password123")?;
    
    // Load wallet from file
    let loaded_wallet = Wallet::load("my_wallet.json", "password123")?;
    
    // Get default account
    let default_account = loaded_wallet.default_account()?;
    
    // Check if address is valid
    let is_valid = Address::is_valid("NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv");
    
    Ok(())
}

Next Steps

Now that you've learned the basics of using the Neo Rust SDK, you can: