Reference Implementations

Reference Implementations for Roru Labs

This document provides information about reference implementations, example code, and best practices for developers building on Roru Labs.

Official Implementations

Roru Wallet (Reference)

Platform: iOS, Android, Desktop, Web

Architecture:

  • Native implementations for each platform

  • Shared core logic

  • Platform-specific UI

  • Full feature implementation

Key Features:

  • Complete wallet functionality

  • Roru One integration

  • Offline capability

  • Multi-chain support

Code Structure:

roru-wallet/
├── core/           # Shared core logic
├── ios/           # iOS implementation
├── android/       # Android implementation
├── desktop/        # Desktop implementations
└── web/           # Web implementation

SDK Implementations

Rust SDK (Primary):

  • Core implementation

  • Best performance

  • Complete features

  • Reference for other languages

TypeScript SDK:

  • Web and Node.js

  • Type-safe

  • Async/await

  • Full feature set

Python SDK:

  • Server-side use

  • Easy integration

  • Complete API

  • Good for automation

Go SDK:

  • High performance

  • Server applications

  • Concurrent operations

  • Full features

Swift SDK:

  • iOS native

  • SwiftUI support

  • Complete features

  • Native performance

C Bindings:

  • Embedded systems

  • FFI support

  • Core operations

  • Minimal dependencies

Example Applications

Basic Wallet Integration

Rust Example:

use roru_sdk::prelude::*;

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize SDK
    let client = RoruClient::new(
        RoruConfig::default()
            .with_infra_endpoint("https://infra.roru.labs")
    ).await?;

    // Create wallet
    let wallet = client.create_wallet().await?;
    
    // Generate address
    let address = wallet.generate_address().await?;
    println!("Address: {}", address);

    // Send transaction
    let tx = TransactionBuilder::new()
        .to(address)
        .amount(1000000) // 1.0 tokens
        .build()?;
    
    let result = wallet.send(tx).await?;
    println!("Transaction: {:?}", result);
    
    Ok(())
}

TypeScript Example:

import { RoruClient, TransactionBuilder } from '@roru/sdk';

async function main() {
    // Initialize SDK
    const client = new RoruClient({
        infraEndpoint: 'https://infra.roru.labs'
    });

    // Create wallet
    const wallet = await client.createWallet();
    
    // Generate address
    const address = await wallet.generateAddress();
    console.log('Address:', address);

    // Send transaction
    const tx = new TransactionBuilder()
        .to(address)
        .amount(1000000) // 1.0 tokens
        .build();
    
    const result = await wallet.send(tx);
    console.log('Transaction:', result);
}

main().catch(console.error);

Merchant Integration

Checkout Flow:

import { MerchantSDK } from '@roru/merchant';

const merchant = new MerchantSDK({
    apiKey: 'your-api-key',
    endpoint: 'https://merchant.roru.labs'
});

// Create checkout session
const session = await merchant.createCheckout({
    amount: 50000, // 0.05 tokens
    currency: 'USDC',
    description: 'Product purchase'
});

// Get payment URL
const paymentUrl = session.paymentUrl;
// Display to customer

// Check payment status
const status = await merchant.getPaymentStatus(session.id);

Offline Transaction Example

Rust Example:

use roru_sdk::prelude::*;

async fn create_offline_transaction() -> Result<()> {
    // Connect to Roru One
    let device = RoruOne::connect().await?;
    
    // Create transaction offline
    let tx = device.create_transaction(
        recipient_address,
        amount
    ).await?;
    
    // Generate proof bundle
    let bundle = device.create_proof_bundle(tx).await?;
    
    // Transfer via NFC
    device.transfer_nfc(bundle).await?;
    
    Ok(())
}

Integration Patterns

Web Application Integration

React Example:

import { useRoruWallet } from '@roru/react';

function PaymentComponent() {
    const { wallet, connect, send } = useRoruWallet();
    
    const handlePayment = async () => {
        await connect();
        const result = await send({
            to: recipientAddress,
            amount: amount
        });
        console.log('Payment complete:', result);
    };
    
    return (
        <button onClick={handlePayment}>
            Pay with Roru
        </button>
    );
}

Server-Side Integration

Node.js Example:

const { RoruClient } = require('@roru/sdk');

const client = new RoruClient({
    infraEndpoint: process.env.RORU_INFRA_ENDPOINT
});

// Process payment
async function processPayment(paymentData) {
    const wallet = await client.getWallet(paymentData.walletId);
    const tx = await wallet.send({
        to: paymentData.recipient,
        amount: paymentData.amount
    });
    return tx;
}

Best Practices

Error Handling

Robust Error Handling:

match wallet.send(tx).await {
    Ok(result) => {
        // Handle success
    }
    Err(RoruError::InsufficientBalance) => {
        // Handle insufficient balance
    }
    Err(RoruError::NetworkError(e)) => {
        // Handle network error
        // Retry logic
    }
    Err(e) => {
        // Handle other errors
    }
}

State Management

Efficient State Sync:

// Subscribe to state updates
wallet.onStateUpdate((state) => {
    // Update UI
    updateBalance(state.balance);
    updateTransactions(state.transactions);
});

// Manual sync when needed
await wallet.syncState();

Performance Optimization

Batch Operations:

// Batch multiple transactions
let mut batch = TransactionBatch::new();
batch.add(tx1);
batch.add(tx2);
batch.add(tx3);

let results = wallet.send_batch(batch).await?;

Testing

Unit Testing

SDK Testing:

#[cfg(test)]
mod tests {
    use super::*;
    
    #[tokio::test]
    async fn test_transaction_creation() {
        let client = RoruClient::new_test().await.unwrap();
        let wallet = client.create_wallet().await.unwrap();
        // Test transaction creation
    }
}

Integration Testing

End-to-End Testing:

describe('Wallet Integration', () => {
    it('should create and send transaction', async () => {
        const client = new RoruClient({ testMode: true });
        const wallet = await client.createWallet();
        const tx = await wallet.send({
            to: testAddress,
            amount: 1000
        });
        expect(tx.status).toBe('confirmed');
    });
});

Code Examples Repository

GitHub Repository

Location: github.com/roru-labs/examples

Examples Include:

  • Basic wallet operations

  • Merchant integrations

  • Offline transactions

  • Multi-chain operations

  • Custom circuits

  • Chain adapters

Documentation Examples

Inline Examples:

  • All SDK methods have examples

  • API documentation includes code

  • Tutorial guides with code

  • Best practices with examples

Conclusion

Reference implementations provide:

  • Working Examples: Real, functional code

  • Best Practices: Proven patterns

  • Integration Guides: Step-by-step instructions

  • Testing Examples: How to test your code

  • Complete Solutions: Full application examples

Use these references as starting points for your own implementations.

Last updated