Skip to main content

Installation

[dependencies]
nexus-sdk = "0.1"
tokio = { version = "1", features = ["full"] }

NexusClient

The main client for interacting with NEXUS nodes.

Constructor

use nexus_sdk::{NexusClient, ClientConfig};

let config = ClientConfig {
    rpc_url: "http://localhost:8545".to_string(),
    rpc_urls: vec!["http://backup:8545".to_string()], // fallbacks
    network: "regtest".to_string(),
    default_gas_limit: 2_000_000,
    timeout_ms: 30000,
    max_requests_per_second: 100,
};

let client = NexusClient::new(config);

Configuration

pub struct ClientConfig {
    /// Primary RPC endpoint
    pub rpc_url: String,
    
    /// Fallback RPC endpoints for failover
    pub rpc_urls: Vec<String>,
    
    /// Network (mainnet, testnet, regtest)
    pub network: String,
    
    /// Default gas limit
    pub default_gas_limit: u64,
    
    /// Request timeout in milliseconds
    pub timeout_ms: u64,
    
    /// Max requests per second (rate limiting)
    pub max_requests_per_second: u32,
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            rpc_url: "http://localhost:8545".to_string(),
            rpc_urls: Vec::new(),
            network: "regtest".to_string(),
            default_gas_limit: 2_000_000,
            timeout_ms: 30000,
            max_requests_per_second: 100,
        }
    }
}

Methods

get_block_height()

Get the current block height.
let height = client.get_block_height().await?;
// Returns: u64

get_balance(address)

Get account balance.
let balance = client.get_balance("bcrt1p...").await?;
// Returns: u128

get_transaction_count(address)

Get account nonce.
let nonce = client.get_transaction_count(&address_bytes).await?;
// Returns: u64

deploy_contract(contract, deployer, signer, value)

Deploy a WASM smart contract.
use nexus_sdk::ContractBuilder;

let contract = ContractBuilder::new("my_contract")
    .wasm_file("./contract.wasm")
    .init_args_raw(init_args)
    .build()?;

let contract_id = client.deploy_contract(
    contract,
    &deployer_pubkey,
    Some(&secret_key),
    0  // value in sats
).await?;
// Returns: Vec<u8> (32-byte contract ID)

call_contract(contract_id, function, args, caller, value)

Call a contract function with typed return.
let result: u64 = client.call_contract(
    &contract_id,
    "get_balance",
    &args,
    &caller,
    0
).await?;

call_contract_raw(contract_id, function, args, caller, value)

Call a contract function with raw bytes return.
let result_bytes = client.call_contract_raw(
    &contract_id,
    "get_data",
    &args,
    &caller,
    0
).await?;
// Returns: Vec<u8>

send_contract_call_raw(contract_id, function, args, sender, signer, value)

Send a state-changing transaction.
let tx_id = client.send_contract_call_raw(
    &contract_id,
    "transfer",
    &args,
    &sender,
    Some(&secret_key),
    0
).await?;
// Returns: Vec<u8> (32-byte tx ID)

get_state(contract_id, key)

Read contract storage directly.
let value = client.get_state(&contract_id, b"my_key").await?;
// Returns: Option<Vec<u8>>

query_events(contract_id, event_name, from_block, to_block)

Query contract events.
let events = client.query_events(
    Some(&contract_id),
    Some("Transfer"),
    Some(100),
    Some(200)
).await?;
// Returns: Vec<ContractEvent>

wait_for_receipt(tx_hash)

Wait for transaction receipt.
let receipt = client.wait_for_receipt("0x1234...").await?;
// Returns: serde_json::Value

get_node_info()

Get node information including protocol key.
let info = client.get_node_info().await?;
// Returns: serde_json::Value

get_token_balance(token_contract, address)

Get NEP-20 token balance.
let balance = client.get_token_balance(&token_contract, "bcrt1p...").await?;
// Returns: TokenBalance { balance: String, balance_decimal: u64 }

ContractBuilder

Build contracts for deployment.
use nexus_sdk::ContractBuilder;

let contract = ContractBuilder::new("my_contract")
    .wasm_file("./contract.wasm")
    .init_args_raw(vec![1, 2, 3])
    .build()?;

// Or with typed init args
let contract = ContractBuilder::new("token")
    .wasm_file("./token.wasm")
    .init_args(&("MyToken", "MTK", 18u32, 1000000u64))?
    .build()?;

Methods

new(name)

Create a new contract builder.
let builder = ContractBuilder::new("contract_name");

wasm_file(path)

Load WASM from file.
builder.wasm_file("./contract.wasm")

wasm_bytes(bytes)

Set WASM bytes directly.
builder.wasm_bytes(wasm_bytes)

init_args(args)

Set typed initialization arguments.
builder.init_args(&("arg1", 100u64))?

init_args_raw(bytes)

Set raw initialization argument bytes.
builder.init_args_raw(vec![1, 2, 3])

build()

Build the contract.
let contract = builder.build()?;

Transaction Signing

Sign transactions with secp256k1 keys.
use nexus_sdk::NexusClient;
use secp256k1::SecretKey;

let secret_key = SecretKey::from_slice(&key_bytes)?;

// Sign is handled internally by deploy_contract and send_contract_call_raw
// when you provide a signer key

// For manual signing:
let mut tx = Transaction { /* ... */ };
client.sign_transaction(&mut tx, &secret_key)?;

Challenge System

Interact with BitVM2 fraud proof challenges.

list_challenge_games()

List all active challenge games.
let games = client.list_challenge_games().await?;
// Returns: Vec<BisectionGameInfo>

get_challenge_game(game_id)

Get challenge game details.
let game = client.get_challenge_game(&game_id).await?;
// Returns: Option<BisectionGameInfo>

initiate_challenge(bond_txid, claimed_hash)

Initiate a fraud proof challenge.
let game_id = client.initiate_challenge(&bond_txid, &claimed_hash).await?;
// Returns: [u8; 32]

submit_bisection_midpoint(game_id, midpoint_hash)

Submit midpoint in bisection game (prover).
client.submit_bisection_midpoint(&game_id, &midpoint_hash).await?;

select_bisection_half(game_id, select_upper, our_hash)

Select half in bisection game (challenger).
let resolved = client.select_bisection_half(&game_id, true, &our_hash).await?;
// Returns: bool

verify_and_resolve(game_id)

Verify disputed step and resolve game.
let prover_wins = client.verify_and_resolve(&game_id).await?;
// Returns: bool

Types

ContractEvent

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContractEvent {
    pub contract_id: Vec<u8>,
    pub event_name: String,
    pub data: Vec<u8>,
    pub block_height: u64,
    pub timestamp: u64,
}

TokenBalance

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenBalance {
    pub balance: String,
    pub balance_decimal: u64,
}

BisectionGameInfo

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BisectionGameInfo {
    pub game_id: [u8; 32],
    pub total_steps: u64,
    pub range_low: u64,
    pub range_high: u64,
    pub prover_hash_low: [u8; 32],
    pub prover_hash_high: [u8; 32],
    pub round: u32,
    pub max_rounds: u32,
    pub state: BisectionStateInfo,
    pub created_at: u64,
    pub deadline: u64,
}

SdkError

pub enum SdkError {
    NetworkError(String),
    SerializationError(String),
    ExecutionFailed(String),
    InvalidInput(String),
    ContractNotFound,
    InsufficientBalance,
    InvalidNonce,
}

Error Handling

use nexus_sdk::SdkError;

match client.deploy_contract(contract, &deployer, Some(&signer), 0).await {
    Ok(contract_id) => {
        println!("Deployed: {}", hex::encode(&contract_id));
    }
    Err(SdkError::NetworkError(msg)) => {
        eprintln!("Network error: {}", msg);
    }
    Err(SdkError::ExecutionFailed(msg)) => {
        eprintln!("Execution failed: {}", msg);
    }
    Err(e) => {
        eprintln!("Error: {:?}", e);
    }
}