NeoRust v0.1.4

NeoRust is a comprehensive Rust SDK for interacting with the Neo N3 blockchain. It provides a complete set of tools and utilities for building applications on the Neo ecosystem, including wallet management, transaction creation, smart contract interaction, and more.
Features
- Complete Neo N3 Support: Full compatibility with the Neo N3 blockchain protocol
- Wallet Management: Create, manage, and secure Neo wallets with support for NEP-6 standard
- Transaction Building: Construct and sign various transaction types
- Smart Contract Interaction: Deploy and interact with smart contracts
- RPC Client: Connect to Neo nodes via JSON-RPC
- NEP-17 Token Support: Interact with NEP-17 compatible tokens
- Neo Name Service (NNS): Resolve and manage domain names on the Neo blockchain
- Cryptographic Operations: Secure key management and cryptographic functions
- NeoFS Support: Interact with the NeoFS distributed storage system
- SGX Integration: Support for Intel SGX secure enclaves
- Modular Architecture: Well-organized codebase with clear separation of concerns
- Famous Neo N3 Contracts: Direct support for popular Neo N3 contracts like Flamingo Finance, NeoburgerNeo, GrandShare, and NeoCompound
- Neo X Support: EVM compatibility layer and bridge functionality for Neo X, an EVM-compatible chain maintained by Neo
Quick Start
Import all essential types and traits using the prelude:
use neo::prelude::*;
Connect to a Neo N3 Node
use neo::prelude::*;
async fn example() -> Result<(), Box<dyn std::error::Error>> {
let provider = neo_providers::JsonRpcClient::new("https://testnet1.neo.coz.io:443");
let block_count = provider.get_block_count().await?;
println!("Current block height: {}", block_count);
let latest_block = provider.get_block_by_index(block_count - 1, 1).await?;
println!("Latest block hash: {}", latest_block.hash);
Ok(())
}
Installation
Add neo3 to your Cargo.toml:
[dependencies]
neo3 = "0.1.4"
Note: The crate is published as neo3 but is imported as neo in code:
use neo::prelude::*;
For the latest development version, you can use the Git repository:
[dependencies]
neo3 = { git = "https://github.com/R3E-Network/NeoRust.git" }
Documentation
Comprehensive documentation is available at:
Usage Examples
Connecting to Neo Nodes
use neo::{
neo_clients::{HttpProvider, JsonRpcProvider},
prelude::RpcClient,
};
async fn connect_to_nodes() -> Result<(), Box<dyn std::error::Error>> {
let mainnet_provider = HttpProvider::new("https://mainnet1.neo.org:443")?;
let mainnet_client = RpcClient::new(mainnet_provider);
let testnet_provider = HttpProvider::new("https://testnet1.neo.org:443")?;
let testnet_client = RpcClient::new(testnet_provider);
let block_count = testnet_client.get_block_count().await?;
let latest_block_hash = testnet_client.get_best_block_hash().await?;
Ok(())
}
Wallet Management
use neo::{
neo_protocol::account::Account,
neo_wallets::{Wallet, WalletBackup, WalletTrait},
prelude::{NeoNetwork, ScryptParamsDef},
};
async fn manage_wallets() -> Result<(), Box<dyn std::error::Error>> {
let mut wallet = Wallet::new();
wallet.set_name("MyNeoWallet".to_string());
let wallet = wallet.with_network(NeoNetwork::TestNet.to_magic());
let new_account = Account::create()?;
let mut wallet = wallet;
wallet.add_account(new_account.clone());
wallet.encrypt_accounts("password123");
let backup_path = std::path::PathBuf::from("wallet_backup.json");
WalletBackup::backup(&wallet, backup_path.clone())?;
let recovered_wallet = WalletBackup::recover(backup_path)?;
Ok(())
}
Creating and Sending Transactions
use neo::{
neo_clients::{HttpProvider, JsonRpcProvider},
neo_builder::transaction::{Transaction, TransactionBuilder},
neo_protocol::account::Account,
prelude::{RpcClient, Signer, WalletTrait},
};
async fn create_transaction() -> Result<(), Box<dyn std::error::Error>> {
let provider = HttpProvider::new("https://testnet1.neo.org:443")?;
let client = RpcClient::new(provider);
let sender = Account::create()?;
let receiver = Account::create()?;
let tx = TransactionBuilder::new()
.version(0)
.nonce(1234)
.valid_until_block(client.get_block_count().await? + 100)
.sender(sender.get_script_hash())
.receiver(receiver.get_script_hash())
.system_fee(1000000)
.network_fee(1000000)
.build();
let signed_tx = tx.sign(&sender).await?;
let tx_hash = client.send_raw_transaction(signed_tx).await?;
Ok(())
}
Interacting with Smart Contracts
use neo::{
neo_clients::{HttpProvider, JsonRpcProvider},
neo_contract::{ContractManagement, SmartContract},
neo_types::contract::{ContractParameter, ContractParameterType},
prelude::{RpcClient, Signer},
};
async fn interact_with_contract() -> Result<(), Box<dyn std::error::Error>> {
let provider = HttpProvider::new("https://testnet1.neo.org:443")?;
let client = RpcClient::new(provider);
let contract_hash = "0xef4073a0f2b305a38ec4050e4d3d28bc40ea63f5".parse()?;
let contract = SmartContract::new(contract_hash, client.clone());
let result = contract.call_function("balanceOf", vec![
ContractParameter::new_hash160("NZNos2WqTbu5oCgyfss9kUJgBXJqhuYAaj".parse()?)
]).await?;
let account = Account::create()?;
let invoke_result = contract.invoke(
"transfer",
vec![
ContractParameter::new_hash160(account.get_script_hash()),
ContractParameter::new_hash160("NZNos2WqTbu5oCgyfss9kUJgBXJqhuYAaj".parse()?),
ContractParameter::new_integer(1000),
ContractParameter::new_any(None),
],
account,
).await?;
Ok(())
}
Working with NEP-17 Tokens
use neo::{
neo_clients::{HttpProvider, JsonRpcProvider},
neo_contract::Nep17Contract,
neo_protocol::account::Account,
prelude::{RpcClient, Signer},
};
async fn work_with_nep17_tokens() -> Result<(), Box<dyn std::error::Error>> {
let provider = HttpProvider::new("https://testnet1.neo.org:443")?;
let client = RpcClient::new(provider);
let account = Account::create()?;
let neo_token_hash = "0xef4073a0f2b305a38ec4050e4d3d28bc40ea63f5".parse()?;
let neo_token = Nep17Contract::new(neo_token_hash, client.clone());
let symbol = neo_token.symbol().await?;
let decimals = neo_token.decimals().await?;
let total_supply = neo_token.total_supply().await?;
let balance = neo_token.balance_of(account.get_script_hash()).await?;
let recipient = "NZNos2WqTbu5oCgyfss9kUJgBXJqhuYAaj".parse()?;
let transfer_result = neo_token.transfer(
account.clone(),
recipient,
1000,
None,
).await?;
Ok(())
}
Using Neo Name Service (NNS)
use neo::{
neo_clients::{HttpProvider, JsonRpcProvider},
neo_contract::NameService,
prelude::{RpcClient, Signer},
};
async fn use_neo_name_service() -> Result<(), Box<dyn std::error::Error>> {
let provider = HttpProvider::new("https://testnet1.neo.org:443")?;
let client = RpcClient::new(provider);
let nns = NameService::new(client);
let domain = "example.neo";
let script_hash = nns.resolve(domain).await?;
println!("Domain {} resolves to: {}", domain, script_hash);
let owner = nns.get_owner(domain).await?;
println!("Domain {} is owned by: {}", domain, owner);
let is_available = nns.is_available("newdomain.neo").await?;
println!("Domain is available: {}", is_available);
Ok(())
}
Working with Famous Neo N3 Contracts
use neo::{
neo_clients::{HttpProvider, JsonRpcProvider},
neo_contract::famous::{FlamingoContract, NeoburgerContract, GrandShareContract, NeoCompoundContract},
neo_protocol::account::Account,
prelude::{RpcClient, Signer},
};
use std::str::FromStr;
async fn interact_with_famous_contracts() -> Result<(), Box<dyn std::error::Error>> {
let provider = HttpProvider::new("https://mainnet1.neo.org:443")?;
let client = RpcClient::new(provider);
let account = Account::create()?;
let flamingo = FlamingoContract::new(Some(&client));
let token_a = ScriptHash::from_str("d2a4cff31913016155e38e474a2c06d08be276cf")?; let token_b = ScriptHash::from_str("ef4073a0f2b305a38ec4050e4d3d28bc40ea63f5")?; let swap_rate = flamingo.get_swap_rate(&token_a, &token_b, 1_0000_0000).await?;
println!("Swap rate: {} NEO per GAS", swap_rate as f64 / 100_000_000.0);
let neoburger = NeoburgerContract::new(Some(&client));
let rate = neoburger.get_rate().await?;
println!("bNEO exchange rate: {} bNEO per NEO", rate);
let wrap_tx = neoburger.wrap(1, &account).await?;
let grandshare = GrandShareContract::new(Some(&client));
let proposal_tx = grandshare.submit_proposal(
"My Proposal",
"This is a proposal description",
1000_0000_0000, &account,
).await?;
let neocompound = NeoCompoundContract::new(Some(&client));
let gas_token = ScriptHash::from_str("d2a4cff31913016155e38e474a2c06d08be276cf")?;
let apy = neocompound.get_apy(&gas_token).await?;
println!("Current APY for GAS: {}%", apy);
Ok(())
}
Using Neo X EVM Compatibility and Bridge
use neo::{
neo_clients::{HttpProvider, JsonRpcProvider},
neo_x::{NeoXProvider, NeoXTransaction, NeoXBridgeContract},
neo_protocol::account::Account,
prelude::{RpcClient, Signer, ScriptHash},
};
use primitive_types::H160;
use std::str::FromStr;
async fn use_neo_x() -> Result<(), Box<dyn std::error::Error>> {
let neo_provider = HttpProvider::new("https://mainnet1.neo.org:443")?;
let neo_client = RpcClient::new(neo_provider);
let neo_x_provider = NeoXProvider::new("https://rpc.neo-x.org", Some(&neo_client));
let chain_id = neo_x_provider.chain_id().await?;
println!("Neo X Chain ID: {}", chain_id);
let destination = H160::from_str("0x1234567890123456789012345678901234567890")?;
let data = vec![];
let transaction = NeoXTransaction::new(
Some(destination),
data,
0, 21000, 20_000_000_000, );
let bridge = NeoXBridgeContract::new(Some(&neo_client));
let gas_token = ScriptHash::from_str("d2a4cff31913016155e38e474a2c06d08be276cf")?;
let fee = bridge.get_fee(&gas_token).await?;
let cap = bridge.get_cap(&gas_token).await?;
println!("Bridge fee: {} GAS", fee as f64 / 100_000_000.0);
println!("Bridge cap: {} GAS", cap as f64 / 100_000_000.0);
let account = Account::create()?;
let neo_x_address = "0x1234567890123456789012345678901234567890";
let amount = 1_0000_0000;
let deposit_tx = bridge.deposit(
&gas_token,
amount,
neo_x_address,
&account,
).await?;
let neo_n3_address = "NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc";
let withdraw_tx = bridge.withdraw(
&gas_token,
amount,
neo_n3_address,
&account,
).await?;
Ok(())
}
Configuration
NeoRust provides configuration options for different network environments and blockchain parameters:
use neo::{
neo_config::{NeoConfig, NeoConstants, NEOCONFIG},
prelude::NeoNetwork,
};
fn configure_neo() {
let mut config = NEOCONFIG.lock().unwrap();
config.set_network(NeoNetwork::MainNet.to_magic()).unwrap();
config.allows_transmission_on_fault = true;
let max_tx_size = NeoConstants::MAX_TRANSACTION_SIZE;
let mainnet_magic = NeoConstants::MAGIC_NUMBER_MAINNET;
let testnet_magic = NeoConstants::MAGIC_NUMBER_TESTNET;
let mainnet_config = NeoConfig::mainnet();
}
Available Features
NeoRust provides several optional features that can be enabled in your Cargo.toml:
- ledger: Support for hardware wallets via Ledger devices
- aws: AWS KMS integration for key management
- futures: Support for asynchronous Futures
- sgx: Intel SGX support for secure enclaves (requires additional setup)
Example of enabling multiple features:
[dependencies]
neo3 = "0.1.4"
Build and Test Scripts
NeoRust includes convenient scripts for building and testing with different feature configurations:
Unix/Linux/MacOS:
./scripts/build.sh
./scripts/build.sh --features ledger,aws,futures
./scripts/test.sh
./scripts/test.sh --nocapture
Windows:
# Build with default configuration
.\scripts\build.bat
# Build with specific features
.\scripts\build.bat --features ledger,aws,futures
# Run tests with default features (ledger,aws,futures)
.\scripts\test.bat
For more details on available script options, see the scripts README.
Project Structure
NeoRust is organized into several modules:
- neo_builder: Transaction and script building utilities
- neo_clients: Neo node interaction clients (RPC and WebSocket)
- neo_codec: Encoding/decoding for Neo-specific data structures
- neo_config: Network and client configuration
- neo_contract: Smart contract interaction
- 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
Contributing
Contributions are welcome! Here's how you can contribute to the NeoRust SDK:
-
Report Issues: If you find a bug or have a feature request, please create an issue on the GitHub repository.
-
Submit Pull Requests: If you'd like to contribute code:
- Fork the repository
- Create a new branch (
git checkout -b feature/your-feature-name)
- Make your changes
- Run the tests (
./scripts/test.sh)
- Commit your changes (
git commit -m 'Add some feature')
- Push to the branch (
git push origin feature/your-feature-name)
- Open a Pull Request
-
Coding Standards: Please follow the Rust coding standards and include appropriate tests for your changes.
-
Documentation: Update the documentation to reflect your changes if necessary.
Package Status
NeoRust is now available on crates.io as the neo3 crate. The latest version is 0.1.4.
This means you can now easily add it to your Rust projects without having to reference the GitHub repository directly.
License
This project is licensed under either of
at your option.
Acknowledgments
Supported by R3E Network and GrantShares. Additional support is welcome.
The NeoRust team would like to thank everyone who contributed to reaching the milestone of publishing the neo3 crate to crates.io.