Skip to content

nymos-xyz/nym-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Nym SDK

Software Development Kit for building applications on the Nym privacy blockchain.

Features

🔗 Blockchain Integration

  • Client Library: Connect to Nym networks and submit transactions
  • Account Management: Create wallets, manage keys, check balances
  • Transaction Handling: Send payments with configurable privacy levels
  • Block Explorer: Query blockchain data and transaction history

📜 Smart Contracts

  • Contract Deployment: Deploy NymScript contracts with privacy configurations
  • Contract Interaction: Call functions and query state with privacy options
  • ABI Support: Type-safe contract interfaces with privacy annotations
  • Event Monitoring: Listen for contract events with privacy filtering

🔒 Privacy Features

  • Zero-Knowledge Proofs: Generate and verify zk-SNARKs, zk-STARKs, and Bulletproofs
  • Anonymous Transactions: Mix network routing for transaction privacy
  • Stealth Addresses: Generate anonymous receiving addresses
  • Encrypted Data: End-to-end encryption for sensitive information

🆔 Identity Integration

  • QuID Support: Seamless integration with QuID universal identity
  • Domain Management: Register and manage .quid and .axon domains
  • Authentication: Generate proofs for service authentication
  • Multi-Identity: Support for multiple identity contexts

Installation

Add to your Cargo.toml:

[dependencies]
nym-sdk = "0.1.0"

# Optional features
nym-sdk = { version = "0.1.0", features = ["privacy", "contracts"] }

Quick Start

Basic Client Usage

use nym_sdk::{NymClient, PrivacyLevel};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to Nym testnet
    let client = NymClient::connect("https://testnet.nym.network").await?;
    
    // Check network status
    let info = client.get_network_info().await?;
    println!("Connected to: {}", info.name);
    
    // Check balance
    let balance = client.get_balance("0x...").await?;
    println!("Balance: {} NYM", balance);
    
    // Send private transaction
    let tx_hash = client.transfer(
        "0x...", // to address
        "10.0",  // amount
        PrivacyLevel::Anonymous
    ).await?;
    
    println!("Transaction sent: {}", tx_hash);
    
    // Wait for confirmation
    let tx = client.wait_for_confirmation(&tx_hash).await?;
    println!("Transaction confirmed in block {}", tx.block_number);
    
    Ok(())
}

Smart Contract Interaction

use nym_sdk::{NymClient, Contract, CallConfig, PrivacyLevel};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = NymClient::connect("https://testnet.nym.network").await?;
    
    // Load contract
    let contract = Contract::at("0x...", &client).await?;
    
    // Call contract function privately
    let result = contract.call(
        "transfer",
        &["0x...", "100"],
        CallConfig {
            privacy_level: PrivacyLevel::Private,
            ..Default::default()
        }
    ).await?;
    
    println!("Transaction hash: {}", result.transaction_hash);
    
    // Query contract state
    let balance = contract.query("balanceOf", &["0x..."]).await?;
    println!("Balance: {}", balance);
    
    Ok(())
}

Deploy Contract

use nym_sdk::{NymClient, Contract, DeploymentConfig, PrivacyLevel};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = NymClient::connect("https://testnet.nym.network").await?;
    
    // Read compiled contract
    let bytecode = std::fs::read("contract.wasm")?;
    let abi = std::fs::read_to_string("contract.abi.json")?;
    
    // Deploy with privacy features
    let contract = Contract::deploy(
        &client,
        &bytecode,
        &abi,
        DeploymentConfig {
            privacy_level: PrivacyLevel::Private,
            constructor_args: vec!["1000000".to_string()], // initial supply
            ..Default::default()
        }
    ).await?;
    
    println!("Contract deployed at: {}", contract.address());
    
    Ok(())
}

Privacy Features

use nym_sdk::{ZKProofGenerator, ProofType, AnonymousTransfer};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = NymClient::connect("https://testnet.nym.network").await?;
    
    // Generate zero-knowledge proof
    let proof_gen = ZKProofGenerator::new(ProofType::STARK);
    let proof = proof_gen.generate_balance_proof(
        1000, // secret balance
        "0x...", // commitment
    ).await?;
    
    // Send anonymous transaction
    let anon_transfer = AnonymousTransfer::new(&client);
    let tx_hash = anon_transfer.send(
        "0x...", // to address
        "50.0",  // amount
        AnonymousConfig {
            mix_rounds: 5,
            stealth_address: true,
            ..Default::default()
        }
    ).await?;
    
    println!("Anonymous transaction: {}", tx_hash);
    
    Ok(())
}

Identity Management

use nym_sdk::{QuIDClient, IdentityManager};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to QuID identity system
    let quid = QuIDClient::connect().await?;
    
    // Create new identity
    let identity = quid.create_identity("alice-personal").await?;
    println!("Created identity: {}", identity.id());
    
    // Register domain
    let domain = identity.register_domain("alice.quid").await?;
    println!("Registered domain: {}", domain);
    
    // Authenticate with service
    let challenge = "auth-challenge-123";
    let proof = identity.generate_auth_proof(challenge).await?;
    println!("Authentication proof: {}", proof);
    
    Ok(())
}

API Reference

Client

impl NymClient {
    // Connection
    async fn connect(endpoint: &str) -> Result<Self>;
    async fn connect_with_config(endpoint: &str, config: ClientConfig) -> Result<Self>;
    
    // Network queries
    async fn get_network_info(&self) -> Result<NetworkInfo>;
    async fn get_block_number(&self) -> Result<u64>;
    async fn get_block(&self, block_number: u64) -> Result<BlockInfo>;
    
    // Account operations
    async fn get_balance(&self, address: &Address) -> Result<Amount>;
    async fn transfer(&self, to: &Address, amount: &Amount, privacy: PrivacyLevel) -> Result<TransactionHash>;
    
    // Transaction queries
    async fn get_transaction(&self, hash: &TransactionHash) -> Result<TransactionInfo>;
    async fn wait_for_confirmation(&self, hash: &TransactionHash) -> Result<TransactionInfo>;
}

Contracts

impl Contract {
    // Loading contracts
    async fn at(address: &Address, client: &NymClient) -> Result<Self>;
    async fn deploy(client: &NymClient, bytecode: &[u8], abi: &str, config: DeploymentConfig) -> Result<Self>;
    
    // Contract interaction
    async fn call(&self, function: &str, args: &[&str], config: CallConfig) -> Result<CallResult>;
    async fn query(&self, function: &str, args: &[&str]) -> Result<String>;
    
    // Event monitoring
    async fn get_events(&self, filter: EventFilter) -> Result<Vec<EventLog>>;
    fn subscribe_events(&self, filter: EventFilter) -> EventStream;
    
    // Contract info
    fn address(&self) -> &Address;
    fn abi(&self) -> &ContractABI;
}

Privacy

impl ZKProofGenerator {
    fn new(proof_type: ProofType) -> Self;
    async fn generate_proof(&self, circuit: &str, witness: &[u8]) -> Result<ZKProof>;
    async fn verify_proof(&self, proof: &ZKProof, public_inputs: &[String]) -> Result<bool>;
}

impl AnonymousTransfer {
    fn new(client: &NymClient) -> Self;
    async fn send(&self, to: &Address, amount: &Amount, config: AnonymousConfig) -> Result<TransactionHash>;
    async fn generate_stealth_address(&self, public_key: &[u8]) -> Result<Address>;
}

Identity

impl QuIDClient {
    async fn connect() -> Result<Self>;
    async fn create_identity(&self, name: &str) -> Result<Identity>;
    async fn import_identity(&self, backup: &[u8]) -> Result<Identity>;
    async fn list_identities(&self) -> Result<Vec<Identity>>;
}

impl Identity {
    fn id(&self) -> &str;
    async fn register_domain(&self, domain: &str) -> Result<String>;
    async fn generate_auth_proof(&self, challenge: &str) -> Result<String>;
    async fn sign_transaction(&self, tx_data: &[u8]) -> Result<Vec<u8>>;
}

Configuration

Client Configuration

use nym_sdk::{ClientConfig, PrivacyLevel};

let config = ClientConfig {
    timeout: 60,
    default_gas_limit: 2_000_000,
    default_gas_price: 25,
    privacy_level: PrivacyLevel::Private,
};

let client = NymClient::connect_with_config("https://mainnet.nym.network", config).await?;

Privacy Configuration

use nym_sdk::{AnonymousConfig, CommitmentScheme};

let config = AnonymousConfig {
    mix_rounds: 5,
    stealth_address: true,
    commitment_scheme: CommitmentScheme::Pedersen,
};

Examples

DeFi Application

// Swap tokens privately using a DEX contract
let dex = Contract::at("0x...", &client).await?;

let swap_result = dex.call(
    "swapExactTokensForTokens",
    &["1000", "950", "[\"0x...\", \"0x...\"]", "0x...", "1234567890"],
    CallConfig {
        privacy_level: PrivacyLevel::Anonymous,
        value: Some("0.1".to_string()), // ETH for gas
        ..Default::default()
    }
).await?;

Privacy-Preserving Voting

// Vote anonymously in a governance contract
let governance = Contract::at("0x...", &client).await?;

// Generate proof of eligibility without revealing identity
let proof_gen = ZKProofGenerator::new(ProofType::SNARK);
let eligibility_proof = proof_gen.generate_membership_proof(&voter_credentials).await?;

let vote_result = governance.call(
    "vote",
    &["1", "true"], // proposal_id, vote
    CallConfig {
        privacy_level: PrivacyLevel::Secret,
        ..Default::default()
    }
).await?;

Domain Registration

// Register domain through identity
let identity = quid.get_identity("alice-personal").await?;
let domain = identity.register_domain("alice.quid").await?;

// Set up domain content
let content_hash = "QmXoYpizjW3WknFiJnKLwHCnL72vedxjQkDDP1mXWo6uco";
let registry = Contract::at("0x...", &client).await?;

registry.call(
    "setContent",
    &[&domain, content_hash],
    CallConfig {
        privacy_level: PrivacyLevel::Public,
        ..Default::default()
    }
).await?;

Testing

Unit Tests

#[cfg(test)]
mod tests {
    use super::*;
    use nym_sdk::testing::*;

    #[tokio::test]
    async fn test_contract_call() {
        let client = MockNymClient::new();
        let contract = Contract::at("0x123", &client).await.unwrap();
        
        let result = contract.call("balanceOf", &["0x456"], CallConfig::default()).await;
        assert!(result.is_ok());
    }
}

Integration Tests

# Run tests against local testnet
cargo test --features integration-tests

# Run privacy tests
cargo test privacy --features privacy

# Run contract tests  
cargo test contracts --features contracts

Features

Enable specific features based on your needs:

[dependencies]
nym-sdk = { version = "0.1.0", features = ["client", "contracts", "privacy"] }

Available features:

  • client: Basic blockchain client functionality
  • contracts: Smart contract deployment and interaction
  • privacy: Zero-knowledge proofs and anonymous transactions
  • wasm: WebAssembly support for browser applications

WebAssembly Support

use nym_sdk::wasm::*;

// Initialize in browser
let client = WasmNymClient::connect("https://testnet.nym.network").await?;

// Use same API as native client
let balance = client.get_balance("0x...").await?;

Contributing

We welcome contributions! Please see our contributing guidelines.

License

This project is licensed under the MIT License.

Support


Build Privacy-First Applications with Nym SDK 🔒✨

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages