Crate neo3

Source
Expand description

Neo Logo

§NeoRust SDK v0.4.1

A comprehensive Rust library for building applications on the Neo N3 blockchain ecosystem.

Crates.io Documentation

§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 hardware wallet support via Ledger devices. When enabled, you can use Ledger hardware wallets for transaction signing and key management. This feature provides an additional security layer by keeping private keys on dedicated hardware.

  • aws: ⚠️ DISABLED in v0.4.1 due to security vulnerabilities in rusoto dependencies. Will be re-enabled in a future version with modern AWS SDK. For AWS KMS integration, please use v0.3.0 or wait for the next major release with updated AWS dependencies.

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

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

You can disable default features with:

neo3 = { version = "0.4.1", 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.

§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
    let sender = Account::from_wif("YOUR_SENDER_WIF_HERE")?;
    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 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 basic blockchain information
    let block_count = client.get_block_count().await?;
    println!("Block count: {}", block_count);
     
    // Get version information
    let version = client.get_version().await?;
    println!("Node version: {}", version.user_agent);
     
    Ok(())
}

§Working with NEP-17 tokens

use neo3::neo_clients::{HttpProvider, RpcClient, APITrait};
use neo3::neo_protocol::{Account, AccountTrait};
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
    let account = Account::from_wif("YOUR_PRIVATE_KEY_WIF_HERE")?;
     
    // Get account information
    println!("Account address: {}", account.get_address());
    println!("Account script hash: {}", account.get_script_hash());
     
    Ok(())
}

§Using the Neo Name Service (NNS)

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

#[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 blockchain information
    let block_count = client.get_block_count().await?;
    println!("Current block count: {}", block_count);
     
    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_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::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;futures
pub use coins_ledger;ledger

Modules§

builder
Neo Builder Module (v0.1.8)
codec
config
crypto
Neo Crypto (v0.1.8)
extensions
neo_builder
Neo Builder Module (v0.1.8)
neo_clients
Neo Clients
neo_codec
neo_config
neo_contract
Neo Contract Module (v0.1.8)
neo_crypto
Neo Crypto (v0.1.8)
neo_error
neo_fs
Neo File Storage (NeoFS) Module (v0.4.1)
neo_protocol
Neo Protocol
neo_types
Neo Types (v0.4.1)
neo_utils
Neo Utilities (v0.1.8)
neo_wallets
Neo Wallets
neo_x
Neo X
prelude
Convenient imports for commonly used types and traits.
protocol
Neo Protocol
providers
Neo Clients
wallets
Neo Wallets
x
Neo X

Macros§

ensure
Macro for early return with context
neo3_error
Macro for creating context-aware errors