Advanced Features

FractaLedger Advanced Features

FractaLedger provides several advanced features that enhance its functionality and enable more complex use cases.

Internal Wallet Transfers

Internal wallet transfers allow you to move funds between internal wallets that are mapped to the same primary on-chain wallet without requiring on-chain transactions. This feature is particularly useful for:

  • Transferring funds between users within the same system
  • Reallocating funds between different internal wallets
  • Implementing internal payment systems without incurring blockchain transaction fees
Internal Transfers Diagram
┌─────────────────────────────────────────────────────────────┐
│                      Primary Wallet                          │
│                                                             │
│  ┌───────────────┐    ┌───────────────┐    ┌──────────────┐ │
│  │ Internal      │    │ Internal      │    │ Internal     │ │
│  │ Wallet A      │───▶│ Wallet B      │───▶│ Wallet C     │ │
│  │ Balance: 0.5  │    │ Balance: 0.3  │    │ Balance: 0.2 │ │
│  └───────────────┘    └───────────────┘    └──────────────┘ │
│                                                             │
└─────────────────────────────────────────────────────────────┘
      

How It Works

Internal transfers are processed entirely within the Hyperledger Fabric ledger and do not create on-chain transactions. This makes them:

  • Instant: No need to wait for blockchain confirmations
  • Free: No blockchain transaction fees
  • Private: Not visible on the public blockchain

API Endpoint

You can perform internal transfers using the POST /api/transactions/internal-transfer endpoint:

curl -X POST http://localhost:3000/api/transactions/internal-transfer \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "fromInternalWalletId": "internal_wallet_1",
    "toInternalWalletId": "internal_wallet_2",
    "amount": 0.1,
    "memo": "Payment for services"
  }'

Implementation Example

Here's an example of how to perform an internal transfer using the FractaLedger JavaScript SDK:

const fractaledger = require('fractaledger');

async function transferFunds() {
  try {
    const result = await fractaledger.internalTransfer({
      fromInternalWalletId: 'internal_wallet_1',
      toInternalWalletId: 'internal_wallet_2',
      amount: 0.1,
      memo: 'Payment for services'
    });
    
    console.log('Transfer successful:', result);
  } catch (error) {
    console.error('Transfer failed:', error);
  }
}

Base Wallet Protection

Base wallet protection ensures that the primary on-chain wallet always has sufficient funds to cover all internal wallets. This is achieved through:

  1. Base Internal Wallet: A special internal wallet that represents excess funds in the primary wallet
  2. Read-Only Wallet Access: API endpoint that provides aggregate balance information
  3. Enhanced Withdrawal Validation: Checks to prevent withdrawals that would exceed the aggregate internal distributed amount
Base Wallet Protection Diagram
┌─────────────────────────────────────────────────────────────┐
│                      Primary Wallet                          │
│                      Balance: 1.5 BTC                        │
│                                                             │
│  ┌───────────────┐    ┌───────────────┐    ┌──────────────┐ │
│  │ Internal      │    │ Internal      │    │ Base Internal│ │
│  │ Wallet A      │    │ Wallet B      │    │ Wallet       │ │
│  │ Balance: 0.5  │    │ Balance: 0.7  │    │ Balance: 0.3 │ │
│  └───────────────┘    └───────────────┘    └──────────────┘ │
│                                                             │
└─────────────────────────────────────────────────────────────┘
      

Base Internal Wallet

The base internal wallet is a special internal wallet that represents excess funds in the primary on-chain wallet. It follows this naming convention:

{namePrefix}{blockchain}_{primaryWalletName}

For example, for a Bitcoin primary wallet named "btc_wallet_1", the base internal wallet would be named:

base_wallet_bitcoin_btc_wallet_1

Configuration

To enable base internal wallet creation, add the following to your configuration file:

"baseInternalWallet": {
  "namePrefix": "base_wallet_",
  "description": "Represents excess funds in the primary on-chain wallet",
  "createOnInitialization": true
}

Read-Only Wallet Access

You can get information about a primary wallet, including the aggregate balance of all internal wallets, using the GET /api/wallets/:blockchain/:name/read-only endpoint:

curl -X GET http://localhost:3000/api/wallets/bitcoin/btc_wallet_1/read-only \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

Response:

{
  "blockchain": "bitcoin",
  "name": "btc_wallet_1",
  "address": "bc1q...",
  "balance": 1.5,
  "aggregateInternalBalance": 1.2,
  "excessBalance": 0.3,
  "baseInternalWalletId": "base_wallet_bitcoin_btc_wallet_1"
}

Enhanced Withdrawal Validation

When you attempt to withdraw funds from an internal wallet, FractaLedger checks that the withdrawal amount doesn't exceed the available balance in the primary wallet. This prevents situations where multiple internal wallets try to withdraw more funds than are actually available in the primary wallet.

If a withdrawal would cause the aggregate internal balance to exceed the primary wallet balance, the withdrawal is rejected with an error message.

Balance Reconciliation

FractaLedger includes a robust balance reconciliation system that ensures the integrity of your wallet balances. This feature verifies that the sum of all internal wallet balances matches the actual on-chain balance of the primary wallet.

How It Works

The balance reconciliation system periodically checks the on-chain balance of the primary wallet and compares it to the sum of all internal wallet balances. If a discrepancy is detected, it's recorded in the ledger and can trigger alerts or automatic corrective actions.

Balance Reconciliation Diagram
┌─────────────────────────────────────────────────────────────┐
│                      Balance Reconciliation                  │
│                                                             │
│  ┌───────────────┐    ┌───────────────┐    ┌──────────────┐ │
│  │ Primary Wallet│    │ Sum of        │    │ Discrepancy  │ │
│  │ Balance: 1.5  │ == │ Internal      │ => │ Detection    │ │
│  │               │    │ Balances: 1.5 │    │              │ │
│  └───────────────┘    └───────────────┘    └──────────────┘ │
│                                                             │
└─────────────────────────────────────────────────────────────┘
      

Configuration

Configure balance reconciliation in your config.json file:

"balanceReconciliation": {
  "strategy": "afterTransaction", 
  "scheduledFrequency": 3600000,
  "warningThreshold": 0.00001,
  "strictMode": false
}
  • strategy: When to perform reconciliation
    • afterTransaction: Check after each transaction
    • scheduled: Check at regular intervals
    • both: Use both strategies
  • scheduledFrequency: Interval in milliseconds for scheduled reconciliation (default: 1 hour)
  • warningThreshold: Minimum difference to trigger a warning (default: 0.00001)
  • strictMode: If true, transactions will fail when discrepancies are detected

API Endpoints

FractaLedger provides several API endpoints for managing balance reconciliation:

Get Reconciliation Configuration

GET /api/reconciliation/config

Reconcile a Specific Wallet

POST /api/reconciliation/wallet/:blockchain/:name

Reconcile All Wallets

POST /api/reconciliation/all

List Balance Discrepancies

GET /api/reconciliation/discrepancies

Resolve a Discrepancy

POST /api/reconciliation/discrepancies/:id/resolve

Discrepancy Resolution

When a discrepancy is detected, it's recorded in the ledger with details about the difference. Administrators can review and resolve discrepancies through the API, providing a resolution description that explains the cause and action taken.

curl -X POST http://localhost:3000/api/reconciliation/discrepancies/discrepancy_123/resolve \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "resolution": "Manual adjustment to correct for transaction fee not accounted for",
    "adjustmentAmount": 0.0001
  }'

API Messaging System

FractaLedger includes a structured messaging system for API responses that provides clear, consistent, and informative feedback to clients. This system categorizes messages by type and severity, making it easier to handle responses programmatically.

Message Types

  • Info: Informational messages about successful operations
  • Warning: Alerts about potential issues that didn't prevent the operation
  • Error: Messages about failures that prevented the operation

Response Format

API responses include both the requested data and any relevant messages:

{
  "data": {
    "success": true,
    "transfer": {
      "id": "transfer_123",
      "fromWalletId": "internal_wallet_1",
      "toWalletId": "internal_wallet_2",
      "amount": 0.1,
      "timestamp": "2025-03-13T12:00:00Z"
    }
  },
  "messages": [
    {
      "type": "info",
      "code": "INFO_001",
      "message": "Internal transfer processed successfully",
      "data": {
        "fromWalletId": "internal_wallet_1",
        "toWalletId": "internal_wallet_2",
        "amount": 0.1
      },
      "timestamp": "2025-03-13T12:00:00Z"
    },
    {
      "type": "warning",
      "code": "WARN_001",
      "message": "Primary wallet balance is low",
      "data": {
        "blockchain": "bitcoin",
        "primaryWalletName": "btc_wallet_1",
        "primaryWalletBalance": 1.2,
        "aggregateInternalBalance": 1.1
      },
      "timestamp": "2025-03-13T12:00:00Z"
    }
  ]
}

Message Codes

Each message includes a unique code that can be used for programmatic handling:

INFO_001 Transaction processed successfully
INFO_002 Wallet created successfully
WARN_001 Primary wallet balance is low
WARN_002 Balance discrepancy detected
ERROR_001 Insufficient balance
ERROR_002 Wallet not found

This messaging system makes it easier to build robust client applications that can handle both successful operations and various error conditions in a consistent way.

Multi-Blockchain Support

FractaLedger supports multiple UTXO-based blockchains simultaneously, allowing you to manage wallets across different blockchains from a single system.

Supported Blockchains

FractaLedger supports the following UTXO-based blockchains:

Bitcoin

The original and most widely used cryptocurrency.

Litecoin

A cryptocurrency that was created as a fork of Bitcoin, with faster block generation time and a different hashing algorithm.

Dogecoin

A cryptocurrency featuring a Shiba Inu dog from the "Doge" Internet meme as its logo.

Other UTXO-Based Blockchains

FractaLedger can be extended to support other UTXO-based blockchains by implementing custom transceivers.

Configuration

You can configure multiple blockchains in your config.json file:

{
  "bitcoin": [
    {
      "name": "btc_wallet_1",
      "network": "mainnet",
      "walletAddress": "bc1q...",
      "secretEnvVar": "BTC_WALLET_1_SECRET",
      "transceiver": {
        "method": "callback",
        "module": "./transceivers/bitcoin-transceiver.js",
        "config": {
          "apiUrl": "https://blockstream.info/api",
          "monitoringInterval": 60000
        }
      }
    }
  ],
  "litecoin": [
    {
      "name": "ltc_wallet_1",
      "network": "mainnet",
      "walletAddress": "ltc1q...",
      "secretEnvVar": "LTC_WALLET_1_SECRET",
      "transceiver": {
        "method": "callback",
        "module": "./transceivers/litecoin-transceiver.js",
        "config": {
          "apiUrl": "https://ltc.bitaps.com/api/v1/blockchain",
          "monitoringInterval": 60000
        }
      }
    }
  ],
  "dogecoin": [
    {
      "name": "doge_wallet_1",
      "network": "mainnet",
      "walletAddress": "D...",
      "secretEnvVar": "DOGE_WALLET_1_SECRET",
      "transceiver": {
        "method": "callback",
        "module": "./transceivers/dogecoin-transceiver.js",
        "config": {
          "apiUrl": "https://dogechain.info/api/v1",
          "monitoringInterval": 60000
        }
      }
    }
  ]
}

Transaction Broadcasting Flow

FractaLedger uses a transceiver architecture that separates transaction creation/signing from the actual blockchain interaction. This allows you to handle blockchain operations through your preferred method. The complete transaction flow is as follows:

  1. Transaction Creation: When you use endpoints like /api/transactions/withdraw, the system creates a transaction with the specified parameters, signs it with the wallet's private key, generates the raw transaction hex, assigns a transaction ID, and stores this information in the pending transactions map.
  2. Transaction Retrieval: Your application retrieves pending transactions via GET /api/transactions/pending.
  3. External Broadcasting: Your application is responsible for broadcasting these transactions to the blockchain network using your own infrastructure or third-party services.
  4. Result Submission: After broadcasting, your application reports the results back to FractaLedger via POST /api/transactions/results.

This architecture provides several benefits:

  • Flexibility: You can implement your own broadcasting logic.
  • Security: Sensitive operations like broadcasting can be handled in a controlled environment.
  • Customization: Different broadcasting methods can be used for different scenarios.
  • Separation of Concerns: Transaction creation is separate from blockchain interaction.

Custom Transceivers

To support a specific blockchain, you need to implement a custom transceiver for that blockchain. FractaLedger provides a command-line tool for generating transceiver templates:

npx fractaledger-generate-transceiver --type bitcoin --output ./my-transceivers

This generates a custom transceiver implementation for Bitcoin in the ./my-transceivers directory. You can then customize this transceiver to work with your specific blockchain.

API Extensions

FractaLedger allows you to extend the API with custom endpoints that implement your specific business logic. This is done through API extensions, which are JavaScript modules that register new endpoints with the API server.

Creating an API Extension

You can create an API extension using the generate-api-extension tool:

npx fractaledger-generate-api-extension --name my-extension --output ./api-extensions

This generates a new API extension file in the ./api-extensions directory.

Example API Extension

Here's an example API extension that adds endpoints for managing merchant fees:

/**
 * Merchant Fee API Extension
 * 
 * This extension adds endpoints for managing merchant fees and processing merchant transactions.
 */

/**
 * Register the merchant fee extension with the API server
 * @param {Object} app The Express app instance
 * @param {Function} authenticateJWT The authentication middleware
 * @param {Object} dependencies Additional dependencies (walletManager, fabricClient, etc.)
 */
function registerMerchantFeeExtension(app, authenticateJWT, dependencies) {
  const { walletManager, fabricClient } = dependencies;
  
  /**
   * Create fee configuration
   * POST /api/fee-config
   */
  app.post('/api/fee-config', authenticateJWT, async (req, res) => {
    try {
      const { defaultFeePercentage, minFeeAmount, maxFeeAmount, merchantSpecificFees } = req.body;
      
      if (defaultFeePercentage === undefined) {
        return res.status(400).json({ error: 'Missing required parameters' });
      }
      
      // Submit the fee configuration to the Fabric network
      const result = await fabricClient.submitTransaction(
        'updateFeeConfiguration',
        defaultFeePercentage.toString(),
        (minFeeAmount || 0).toString(),
        (maxFeeAmount || 1).toString(),
        JSON.stringify(merchantSpecificFees || {})
      );
      
      const feeConfig = JSON.parse(result.toString());
      
      res.json(feeConfig);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  });
  
  /**
   * Process a merchant transaction
   * POST /api/transactions/merchant
   */
  app.post('/api/transactions/merchant', authenticateJWT, async (req, res) => {
    try {
      const { fromWalletId, toWalletId, feeWalletId, amount } = req.body;
      
      if (!fromWalletId || !toWalletId || !feeWalletId || !amount) {
        return res.status(400).json({ error: 'Missing required parameters' });
      }
      
      // Process the merchant transaction
      const result = await fabricClient.submitTransaction(
        'processMerchantTransaction',
        fromWalletId,
        toWalletId,
        feeWalletId,
        amount.toString()
      );
      
      const transaction = JSON.parse(result.toString());
      
      res.json(transaction);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  });
}

module.exports = registerMerchantFeeExtension;

Registering an API Extension

To register your API extension with the FractaLedger system, you need to add it to the api.extensions array in your config.json file:

"api": {
  "port": 3000,
  "host": "localhost",
  "extensions": [
    {
      "module": "./api-extensions/merchant-fee-extension.js"
    }
  ]
}

This registers your API extension with the FractaLedger API server, making your custom endpoints available for use.

Monitoring and Alerting

FractaLedger includes a monitoring and alerting system that helps you keep track of your wallets and transactions. This system can notify you of important events, such as low wallet balances, failed transactions, or balance discrepancies.

Configuration

Configure monitoring and alerting in your config.json file:

"monitoring": {
  "interval": 60000,
  "healthCheck": {
    "enabled": true,
    "failureThreshold": 3,
    "successThreshold": 1
  },
  "alerting": {
    "enabled": true,
    "email": {
      "enabled": true,
      "recipients": ["admin@example.com"],
      "smtpServer": "smtp.example.com",
      "smtpPort": 587,
      "smtpUser": "alerts@example.com",
      "smtpPasswordEnvVar": "SMTP_PASSWORD"
    },
    "slack": {
      "enabled": true,
      "webhookUrl": "https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
    }
  }
}

Health Checks

FractaLedger performs regular health checks to ensure that all components of the system are functioning properly. If a health check fails, an alert is triggered.

Alerting Channels

FractaLedger supports multiple alerting channels:

Email

Send alerts to one or more email addresses.

Slack

Send alerts to a Slack channel using a webhook URL.

Custom Channels

Implement custom alerting channels by extending the alerting system.

Alert Types

FractaLedger can generate alerts for various events:

  • Low Wallet Balance: When a primary wallet balance falls below a threshold
  • Failed Transaction: When a transaction fails to broadcast or confirm
  • Balance Discrepancy: When a balance reconciliation detects a discrepancy
  • System Error: When a system component encounters an error
  • Health Check Failure: When a health check fails