Skip to main content

Crate neo3

Crate neo3 

Source
Expand description

Neo Logo

§NeoRust SDK

A production-focused Rust SDK for the Neo N3 blockchain.

Crates.io Documentation License: MIT

§Features

This crate provides several feature flags to customize functionality:

  • futures: Enables async/futures support for asynchronous blockchain operations. This is recommended for most applications that need to interact with the Neo blockchain without blocking.

  • ledger: Enables Ledger hardware wallet types. The feature gate is compile-checked, but production use should include real-device signing tests in your release environment.

  • yubi / mock-hsm: Enables YubiHSM support, or the YubiHSM mock backend for tests.

  • sgx: Experimental Intel SGX compile gate. Host builds compile the flag, but enclave builds require an SGX target/toolchain and dedicated validation.

  • no_std: Experimental dependency feature forwarding for specialized builds. It is not certified as general embedded or wasm32-unknown-unknown support.

To enable specific features in your project, modify your Cargo.toml as follows:

[dependencies]
neo3 = { version = "1.2", features = ["futures", "ledger"] }

You can disable default features with:

neo3 = { version = "1.2", default-features = false, features = ["futures"] }

§Overview

NeoRust is a complete SDK designed to make Neo N3 blockchain development in Rust intuitive, type-safe, and productive. The library provides full support for all Neo N3 features and follows Rust best practices for reliability and performance.

§New in v1.0.x

  • WebSocket Support: Real-time blockchain events with automatic reconnection
  • HD Wallets (BIP-39/44): Deterministic wallet generation and derivation
  • Transaction Simulation: Preview fees, VM state, and state changes before sending
  • High-Level SDK API: Simplified entrypoint (Neo) for common operations
  • Enhanced Error Handling: Consistent NeoError with recovery suggestions

§Core Modules

NeoRust is organized into specialized modules, each handling specific aspects of Neo N3:

  • neo_builder: Transaction construction and script building
  • neo_clients: Neo node interaction and RPC client implementations
  • neo_codec: Serialization and deserialization of Neo data structures
  • neo_config: Configuration for networks and client settings
  • neo_contract: Smart contract interaction and token standards
  • neo_crypto: Cryptographic primitives and operations
  • neo_error: Unified error handling
  • neo_fs: NeoFS distributed storage system integration
  • neo_protocol: Core blockchain protocol implementations
  • neo_types: Core data types and primitives for Neo N3
  • neo_utils: General utility functions
  • neo_wallets: Wallet management for Neo N3
  • neo_x: Neo X EVM compatibility layer

§Quick Start

Import all essential types and traits using the prelude:

use neo3::prelude::*;

§Complete Example

Here’s a comprehensive example showcasing common operations with the NeoRust SDK:

use neo3::neo_protocol::{Account, AccountTrait};
use neo3::neo_clients::{HttpProvider, RpcClient, APITrait};

async fn neo_example() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to Neo TestNet
    let provider = HttpProvider::new("https://testnet1.neo.org:443")?;
    let client = RpcClient::new(provider);
     
    // Get basic blockchain information
    let block_height = client.get_block_count().await?;
    println!("Connected to Neo TestNet at height: {}", block_height);
     
    // Create a new wallet account
    let account = Account::create()?;
    println!("New account created:");
    println!("  Address:     {}", account.get_address());
    println!("  Script Hash: {}", account.get_script_hash());
     
    // Get version information
    let version = client.get_version().await?;
    println!("Node version: {}", version.user_agent);
     
    Ok(())
}

§Usage Examples

§Connecting to a Neo N3 node

use neo3::neo_clients::{HttpProvider, RpcClient, APITrait};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to Neo N3 MainNet
    let provider = HttpProvider::new("https://mainnet1.neo.org:443")?;
    let client = RpcClient::new(provider);
     
    // Get basic blockchain information
    let block_count = client.get_block_count().await?;
    println!("Current block count: {}", block_count);
     
    let version = client.get_version().await?;
    println!("Node version: {}", version.user_agent);
     
    Ok(())
}

§Creating and sending a transaction

use neo3::neo_clients::{HttpProvider, RpcClient, APITrait};
use neo3::neo_protocol::{Account, AccountTrait};
use neo3::neo_types::{ScriptHash, ContractParameter, ScriptHashExtension};
use neo3::neo_builder::{ScriptBuilder, TransactionBuilder, AccountSigner};
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize the JSON-RPC provider
    let provider = HttpProvider::new("https://testnet1.neo.org:443")?;
    let client = RpcClient::new(provider);

    // Create accounts for the sender and recipient
    // Load sender key from an environment variable to avoid hardcoding secrets.
    let sender_wif = std::env::var("NEO_WIF")?;
    let sender = Account::from_wif(&sender_wif)?;
    let recipient = ScriptHash::from_address("NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc")?;

    // Get the GAS token contract
    let gas_token_hash = ScriptHash::from_str("d2a4cff31913016155e38e474a2c06d08be276cf")?;
     
    // Build the transaction using the ScriptBuilder
    let script = ScriptBuilder::new()
        .contract_call(
            &gas_token_hash,
            "transfer",
            &[
                ContractParameter::h160(&sender.get_script_hash()),
                ContractParameter::h160(&recipient),
                ContractParameter::integer(1_0000_0000), // 1 GAS (8 decimals)
                ContractParameter::any(),
            ],
            None,
        )?
        .to_bytes();
     
    // Create and configure the transaction
    let mut tx_builder = TransactionBuilder::with_client(&client);
    tx_builder
        .set_script(Some(script))
        .set_signers(vec![AccountSigner::called_by_entry(&sender)?.into()])?
        .valid_until_block(client.get_block_count().await? + 5760)?; // Valid for ~1 day

    // Sign the transaction
    let mut tx = tx_builder.sign().await?;

    // Send the transaction
    let result = tx.send_tx().await?;
    println!("Transaction sent: {}", result.hash);

    // Wait for the transaction to be confirmed
    println!("Waiting for confirmation...");
    tx.track_tx(10).await?;
    println!("Transaction confirmed!");

    // Get the application log
    let app_log = tx.get_application_log(&client).await?;
    println!("Application log: {:?}", app_log);

    Ok(())
}

§Interacting with a smart contract

use neo3::neo_clients::{HttpProvider, RpcClient, APITrait};
use neo3::neo_types::ScriptHash;
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to Neo N3 TestNet
    let provider = HttpProvider::new("https://testnet1.neo.org:443")?;
    let client = RpcClient::new(provider);
     
    // Get the NEO token contract
    let neo_token = ScriptHash::from_str("ef4073a0f2b305a38ec4050e4d3d28bc40ea63f5")?;
     
    // Call a read-only method (doesn't require signing)
    let result = client
        .invoke_function(&neo_token, "symbol".to_string(), vec![], None)
        .await?;
     
    // Parse the result
    if let Some(item) = result.stack.first() {
        println!("NEO Token Symbol: {:?}", item);
    }
     
    // Get the total supply
    let supply_result = client
        .invoke_function(&neo_token, "totalSupply".to_string(), vec![], None)
        .await?;
     
    println!("Total Supply Result: {:?}", supply_result);
     
    Ok(())
}

§Working with NEP-17 tokens

use neo3::neo_clients::{HttpProvider, RpcClient, APITrait};
use neo3::neo_protocol::{Account, AccountTrait};
use neo3::neo_types::{ScriptHash, ContractParameter};
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to Neo N3 TestNet
    let provider = HttpProvider::new("https://testnet1.neo.org:443")?;
    let client = RpcClient::new(provider);
     
    // Create an account from WIF (Wallet Import Format)
    let wif = std::env::var("NEO_WIF")?;
    let account = Account::from_wif(&wif)?;
     
    // Get account information
    println!("Account address: {}", account.get_address());
    println!("Account script hash: {}", account.get_script_hash());
     
    // Get GAS token balance for the account
    let gas_token = ScriptHash::from_str("d2a4cff31913016155e38e474a2c06d08be276cf")?;
     
    let balance_result = client
        .invoke_function(
            &gas_token,
            "balanceOf".to_string(),
            vec![ContractParameter::h160(&account.get_script_hash())],
            None,
        )
        .await?;
     
    // Parse the balance result
    if let Some(item) = balance_result.stack.first() {
        println!("GAS Balance: {:?}", item);
    }
     
    Ok(())
}

§Using the Neo Name Service (NNS)

use neo3::neo_clients::{HttpProvider, RpcClient, APITrait};
use neo3::neo_types::{ContractParameter, ScriptHash};
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to Neo N3 TestNet
    let provider = HttpProvider::new("https://testnet1.neo.org:443")?;
    let client = RpcClient::new(provider);
     
    // NNS contract on TestNet (use MainNet hash for production)
    let nns_contract = ScriptHash::from_str("50ac1c37690cc2cfc594472833cf57505d5f46de")?;
     
    // Check if a name is available
    let available_result = client
        .invoke_function(
            &nns_contract,
            "isAvailable".to_string(),
            vec![ContractParameter::string("myname.neo".to_string())],
            None,
        )
        .await?;
     
    if let Some(item) = available_result.stack.first() {
        println!("Is 'myname.neo' available: {:?}", item);
    }
     
    Ok(())
}

For more usage examples, refer to the examples directory in the repository.

§Project Structure

NeoRust
├── examples
│   ├── neo_nodes          - Examples for connecting to Neo nodes
│   ├── neo_transactions   - Examples for creating and sending transactions
│   ├── neo_smart_contracts - Examples for interacting with smart contracts
│   ├── neo_wallets        - Examples for wallet management
│   ├── neo_nep17_tokens   - Examples for working with NEP-17 tokens
│   └── neo_nns            - Examples for using the Neo Name Service
└── src
    ├── neo_builder        - Transaction and script building utilities
    ├── neo_clients        - Neo node interaction clients (RPC and WebSocket)
    ├── neo_codec          - Encoding and decoding for Neo-specific data structures
    ├── neo_config         - Network and client configuration management
    ├── neo_contract       - Smart contract interaction abstractions
    ├── neo_crypto         - Neo-specific cryptographic operations
    ├── neo_protocol       - Neo network protocol implementation
    ├── neo_sgx            - Experimental SGX enclave scaffolding
    ├── neo_types          - Core Neo ecosystem data types
    └── neo_wallets        - Neo asset and account management

§Module Overview

  • neo_builder: Transaction and script building utilities.

    • Transaction construction and signing
    • Script building for contract calls
    • Network fee calculation
  • neo_clients: Neo node interaction clients.

    • HTTP, WebSocket, and IPC providers
    • JSON-RPC client implementation
    • Event subscription and notification handling
  • neo_codec: Encoding and decoding for Neo-specific data structures.

    • Binary serialization and deserialization
    • Neo VM script encoding
  • neo_config: Network and client configuration management.

    • Network magic numbers
    • Client settings
  • neo_contract: Smart contract interaction abstractions.

    • Contract invocation and deployment
    • NEP-17 token standard implementation
    • Native contracts (GAS, NEO, etc.)
    • Neo Name Service (NNS) support
  • neo_crypto: Neo-specific cryptographic operations.

    • Key generation and management
    • Signing and verification
    • Hashing functions
  • neo_protocol: Neo network protocol implementation.

    • Account management
    • Address formats and conversions
  • neo_types: Core Neo ecosystem data types.

    • Script hashes
    • Contract parameters
    • Block and transaction types
    • NNS name types
  • neo_wallets: Neo asset and account management.

    • Wallet creation and management
    • NEP-6 wallet standard support
    • Account import/export
    • Wallet backup and recovery

For detailed information, consult the documentation of each module.

Re-exports§

pub use crate::neo_types::deserialize_address_or_script_hash;
pub use crate::neo_types::deserialize_h256;
pub use crate::neo_types::deserialize_h256_option;
pub use crate::neo_types::deserialize_hash_map_h160_account;
pub use crate::neo_types::deserialize_script_hash;
pub use crate::neo_types::deserialize_script_hash_option;
pub use crate::neo_types::deserialize_url_option;
pub use crate::neo_types::serialize_address_or_script_hash;
pub use crate::neo_types::serialize_h256;
pub use crate::neo_types::serialize_h256_option;
pub use crate::neo_types::serialize_hash_map_h160_account;
pub use crate::neo_types::serialize_script_hash;
pub use crate::neo_types::serialize_script_hash_option;
pub use crate::neo_types::serialize_url_option;
pub use crate::neo_types::var_size;
pub use crate::neo_types::vec_to_array32;
pub use crate::neo_types::Address;
pub use crate::neo_types::AddressOrScriptHash;
pub use crate::neo_types::Base64Encode;
pub use crate::neo_types::Bytes;
pub use crate::neo_types::ContractIdentifiers;
pub use crate::neo_types::ContractManifest;
pub use crate::neo_types::ContractParameter;
pub use crate::neo_types::ContractParameterType;
pub use crate::neo_types::ContractState;
pub use crate::neo_types::InvocationResult;
pub use crate::neo_types::NNSName;
pub use crate::neo_types::NefFile;
pub use crate::neo_types::OpCode;
pub use crate::neo_types::OperandSize;
pub use crate::neo_types::ParameterValue;
pub use crate::neo_types::ScriptHash;
pub use crate::neo_types::ScriptHashExtension;
pub use crate::neo_types::ScryptParamsDef;
pub use crate::neo_types::StackItem;
pub use crate::neo_types::StringExt;
pub use crate::neo_types::TryBase64Encode;
pub use crate::neo_types::TryStringExt;
pub use crate::neo_types::TypeError;
pub use crate::neo_types::VMState;
pub use crate::neo_types::serde_with_utils::deserialize_boolean_expression;
pub use crate::neo_types::serde_with_utils::deserialize_bytes;
pub use crate::neo_types::serde_with_utils::deserialize_h160;
pub use crate::neo_types::serde_with_utils::deserialize_hardforks;
pub use crate::neo_types::serde_with_utils::deserialize_hashmap_address_u256;
pub use crate::neo_types::serde_with_utils::deserialize_hashmap_u256_hashset_h256;
pub use crate::neo_types::serde_with_utils::deserialize_hashmap_u256_hashset_u256;
pub use crate::neo_types::serde_with_utils::deserialize_hashmap_u256_vec_u256;
pub use crate::neo_types::serde_with_utils::deserialize_hashset_u256;
pub use crate::neo_types::serde_with_utils::deserialize_map;
pub use crate::neo_types::serde_with_utils::deserialize_private_key;
pub use crate::neo_types::serde_with_utils::deserialize_public_key;
pub use crate::neo_types::serde_with_utils::deserialize_public_key_option;
pub use crate::neo_types::serde_with_utils::deserialize_scopes;
pub use crate::neo_types::serde_with_utils::deserialize_vec_script_hash;
pub use crate::neo_types::serde_with_utils::deserialize_vec_script_hash_option;
pub use crate::neo_types::serde_with_utils::deserialize_wildcard;
pub use crate::neo_types::serde_with_utils::serialize_boolean_expression;
pub use crate::neo_types::serde_with_utils::serialize_bytes;
pub use crate::neo_types::serde_with_utils::serialize_h160;
pub use crate::neo_types::serde_with_utils::serialize_hashmap_address_u256;
pub use crate::neo_types::serde_with_utils::serialize_hashmap_u256_hashset_h256;
pub use crate::neo_types::serde_with_utils::serialize_hashmap_u256_hashset_u256;
pub use crate::neo_types::serde_with_utils::serialize_hashmap_u256_vec_u256;
pub use crate::neo_types::serde_with_utils::serialize_hashset_u256;
pub use crate::neo_types::serde_with_utils::serialize_map;
pub use crate::neo_types::serde_with_utils::serialize_private_key;
pub use crate::neo_types::serde_with_utils::serialize_public_key;
pub use crate::neo_types::serde_with_utils::serialize_public_key_option;
pub use crate::neo_types::serde_with_utils::serialize_scopes;
pub use crate::neo_types::serde_with_utils::serialize_vec_script_hash;
pub use crate::neo_types::serde_with_utils::serialize_vec_script_hash_option;
pub use crate::neo_types::serde_with_utils::serialize_wildcard;
pub use crate::neo_types::contract::ContractMethodToken;
pub use crate::neo_types::contract::ContractNef;
pub use crate::neo_types::contract::NativeContractState;
pub use crate::neo_types::contract::NeoVMStateType;
pub use crate::neo_types::serde_value::ValueExtension;
pub use futures;
pub use coins_ledger;

Modules§

builder
Neo Builder Module
codec
config
constants
Constants used throughout the Neo N3 SDK.
crypto
Neo Crypto
extensionsDeprecated
Trait implementations for serde JSON serialization.
monitoring
Monitoring
neo_builder
Neo Builder Module
neo_clients
Neo Clients
neo_codec
neo_config
neo_contract
Neo Contract Module
neo_crypto
Neo Crypto
neo_error
neo_fs
Neo File Storage (NeoFS)
neo_protocol
Neo Protocol
neo_types
Neo Types (v1.0.9)
neo_utils
Neo Utilities
neo_wallets
Neo Wallets
neo_x
Neo X
prelude
Convenient imports for commonly used types and traits.
protocol
Neo Protocol
providers
Neo Clients
sdk
High-level SDK API for simplified Neo blockchain interaction
wallets
Neo Wallets
x
Neo X

Macros§

counter
Increment a named counter.
ensure
Macro for early return with context
gauge
Set a named gauge value.
histogram
Observe a named histogram value.
neo3_error
Macro for creating context-aware errors
trace_contract
Execute a block in a contract tracing context.
trace_rpc
Execute a block in an RPC tracing context.
trace_transaction
Execute a block in a transaction tracing context.

Constants§

VERSION
Current version of the neo3 crate.