Catalog npm
Back to packageRELEASE DETAILS

0.1.0-dev

npm

@0xgery/wallet-sdk

TypeScript SDK for integrating with Octra Wallet Extension

blockchaincommunitydappextensionoctrasdkunofficialwalletweb3
Published26 Aug 2025
Direct dependencies11
Transitive dependenciesNot calculated

README

Current package documentation

Octra Wallet SDK

A comprehensive TypeScript/JavaScript SDK that enables seamless integration between decentralized applications (DApps) and the Octra Wallet browser extension. This toolkit provides developers with a secure, type-safe, and user-friendly way to interact with the Octra blockchain network.

What is this SDK?

The Octra Wallet SDK bridges the gap between web applications and blockchain functionality, allowing developers to:

  • Connect to Octra Wallet: Establish secure connections with users' Octra wallet extensions
  • Manage Transactions: Send regular and private transactions with full type safety
  • Handle Balances: Read public and encrypted private balance information
  • Event-Driven Architecture: React to wallet events like balance changes, network switches, and connection status
  • Private Features: Support for Octra's unique private balance encryption and private transfer system
  • Multi-Framework Support: Works with React, Vue, Svelte, and vanilla JavaScript applications

Why use this SDK?

  • Security First: Only authenticated DApps with proper SDK integration can connect
  • TypeScript Native: Full type definitions for better development experience
  • Smart Extension Detection: Built-in extension monitoring with automatic retry logic
  • Event-Driven Architecture: Real-time updates replace polling for better performance
  • Robust Error Handling: Detailed diagnostics with automatic retry and exponential backoff
  • Framework Agnostic: Compatible with any JavaScript framework or vanilla JS
  • Developer Friendly: Advanced debugging tools and development mode logging
  • Production Ready: Clean builds with zero console noise in production

Disclaimer: This is an unofficial, community-built project for the Octra network. It is not affiliated with, endorsed by, or maintained by the official Octra team.

Note: This SDK is developed by NullxGery (0xGery) for the Octra network ecosystem.

What's New in v0.2.0

Major Performance & Reliability Improvements:

  • Built-in Extension Detection: No more manual polling - SDK automatically detects extension availability
  • Automatic Retry Logic: Exponential backoff retry system (3 attempts: 1s → 2s → 4s)
  • Enhanced Error Diagnostics: Detailed failure context with browser/extension state information
  • Event-Based Communication: Real-time extension events replace polling for instant updates
  • Advanced Development Tools: Rich debugging with browser console utilities
  • Production-Safe Logging: Zero console output in production builds

View Full Changelog

Quick Start

Installation

# npm
npm install @0xgery/wallet-sdk

# yarn
yarn add @0xgery/wallet-sdk

# CDN (for quick testing)
<script src="https://unpkg.com/@0xgery/wallet-sdk@0.2.0/dist/index.umd.js"></script>

Basic Usage

import { OctraWallet } from '@0xgery/wallet-sdk';

// Create wallet instance
const wallet = new OctraWallet({
  appName: 'My Awesome DApp',
  appDescription: 'A revolutionary decentralized application',
  requiredPermissions: ['read_balance', 'send_transactions']
});

// Initialize and connect
await wallet.initialize();
const connection = await wallet.connect();

console.log('Connected!', connection.address);

// Get balance
const balance = await wallet.getBalance();
console.log('Balance:', balance.total, 'OCT');

// Send transaction
const result = await wallet.sendTransaction({
  to: 'recipient_address',
  amount: 10.5,
  message: 'Hello from my DApp!'
});

console.log('Transaction sent:', result.txHash);

Simple Setup (Auto-connect)

import { createOctraWallet } from '@0xgery/wallet-sdk';

const wallet = await createOctraWallet({
  appName: 'My DApp',
  autoConnect: true,
  debug: true
});

if (wallet.isConnected()) {
  const balance = await wallet.getBalance();
  console.log('Balance:', balance.total, 'OCT');
}

API Reference

OctraWallet Class

Constructor

new OctraWallet(config: SDKConfig)

SDKConfig:

interface SDKConfig {
  appName: string;                    // Required: Your DApp name
  appDescription?: string;            // App description for user
  appVersion?: string;               // App version (default: '1.0.0')
  appUrl?: string;                   // App URL (auto-detected)
  appIcon?: string;                  // App icon URL
  requiredPermissions?: Permission[]; // Required permissions
  networkId?: string;                // Target network ('mainnet', 'testnet')
  debug?: boolean;                   // Enable debug logging
}

Methods

Initialize
await wallet.initialize(): Promise<boolean>

Initialize the SDK. Must be called before any other methods.

Connection Management
await wallet.connect(options?: ConnectOptions): Promise<ConnectEvent>
await wallet.disconnect(): Promise<void>
wallet.isConnected(): boolean
wallet.getConnectionInfo(): ConnectionInfo
Wallet Information
wallet.getAddress(): string | null
await wallet.getBalance(forceRefresh?: boolean): Promise<Balance>
await wallet.getNetworkInfo(): Promise<NetworkInfo>
Transactions
await wallet.sendTransaction(txData: TransactionData): Promise<TransactionResult>
await wallet.getTransactionHistory(page?: number, limit?: number): Promise<TransactionHistory>
Private Features
await wallet.getPrivateBalanceInfo(): Promise<PrivateBalanceInfo>
await wallet.encryptBalance(amount: number): Promise<boolean>
await wallet.decryptBalance(amount: number): Promise<boolean>
await wallet.sendPrivateTransfer(data: PrivateTransferData): Promise<TransactionResult>
await wallet.getPendingPrivateTransfers(): Promise<PendingPrivateTransfer[]>
await wallet.claimPrivateTransfer(transferId: string): Promise<TransactionResult>
Event Handling
wallet.on(event: WalletEventType, listener: (data) => void): void
wallet.off(event: WalletEventType, listener: Function): void
wallet.once(event: WalletEventType, listener: (data) => void): void

Events:

  • connect - Wallet connected
  • disconnect - Wallet disconnected
  • accountChanged - Account switched
  • balanceChanged - Balance updated
  • networkChanged - Network switched
  • transactionConfirmed - Transaction confirmed
  • error - Error occurred
  • extensionLocked - Extension was locked
  • extensionUnlocked - Extension was unlocked

Utility Functions

The SDK now exports useful utility functions:

import {
  // Validation utilities
  isValidAddress,
  isValidAmount,
  isValidMessage,
  isValidFeeLevel,
  isValidNetworkId,
  
  // Formatting utilities  
  formatOCT,
  formatAddress,
  formatTimestamp,
  formatTxHash,
  
  // Conversion utilities
  toMicroOCT,
  fromMicroOCT,
  
  // Error utilities
  createErrorMessage,
  isErrorType,
  
  // Async utilities
  delay,
  retry,
  withTimeout,
  
  // Browser utilities
  isBrowser,
  checkBrowserSupport,
  
  // Development utilities
  generateMockData,
  createLogger
} from '@0xgery/wallet-sdk';

// Example usage
const isValid = isValidAddress('OCTxyz123...');
const formatted = formatOCT(123.456789, 2); // "123.46"
const shortAddr = formatAddress('OCTxyz123...abc', 6, 4); // "OCTxyz...abc"

Development & Debugging Tools

The SDK includes advanced debugging tools available in development environments:

// Available at window.__OCTRA_SDK_UTILS__ in development
window.__OCTRA_SDK_UTILS__.enableDebugMode();   // Enable detailed logging
window.__OCTRA_SDK_UTILS__.disableDebugMode();  // Disable logging
window.__OCTRA_SDK_UTILS__.getSDKInfo();        // Get SDK version info
window.__OCTRA_SDK_UTILS__.simulateExtensionEvent('balanceChanged', data); // Test events
window.__OCTRA_SDK_UTILS__.showWelcome();       // Show SDK welcome message

Automatic Development Detection:

  • Localhost and development domains automatically enable debug utilities
  • Rich console output with grouped logging and clear indicators
  • Extension state monitoring and diagnostics
  • Event simulation for testing
  • Zero production overhead

Integration Examples

React Integration

import React, { useState, useEffect } from 'react';
import { OctraWallet, createOctraWallet } from '@0xgery/wallet-sdk';

function WalletConnector() {
  const [wallet, setWallet] = useState(null);
  const [connected, setConnected] = useState(false);
  const [address, setAddress] = useState('');
  const [balance, setBalance] = useState(0);

  useEffect(() => {
    async function initWallet() {
      try {
        const walletInstance = await createOctraWallet({
          appName: 'My React DApp',
          debug: process.env.NODE_ENV === 'development'
        });

        // Setup event listeners
        walletInstance.on('connect', (event) => {
          setConnected(true);
          setAddress(event.address);
          setBalance(event.balance.total);
        });

        walletInstance.on('disconnect', () => {
          setConnected(false);
          setAddress('');
          setBalance(0);
        });

        walletInstance.on('balanceChanged', (event) => {
          setBalance(event.newBalance.total);
        });

        setWallet(walletInstance);
      } catch (error) {
        console.error('Failed to initialize wallet:', error);
      }
    }

    initWallet();
  }, []);

  const connect = async () => {
    try {
      await wallet.connect();
    } catch (error) {
      alert('Connection failed: ' + error.message);
    }
  };

  const sendTransaction = async () => {
    try {
      const result = await wallet.sendTransaction({
        to: 'recipient_address',
        amount: 1,
        message: 'Test from React DApp'
      });
      alert('Transaction sent: ' + result.txHash);
    } catch (error) {
      alert('Transaction failed: ' + error.message);
    }
  };

  return (
    <div>
      <h2>Octra Wallet Integration</h2>
      
      {!connected ? (
        <button onClick={connect} disabled={!wallet}>
          {wallet ? 'Connect Wallet' : 'Loading...'}
        </button>
      ) : (
        <div>
          <p>Connected: {address}</p>
          <p>Balance: {balance} OCT</p>
          <button onClick={() => wallet.disconnect()}>Disconnect</button>
          <button onClick={sendTransaction}>Send Test Transaction</button>
        </div>
      )}
    </div>
  );
}

export default WalletConnector;

Vue.js Integration

<template>
  <div>
    <h2>Octra Wallet Integration</h2>
    
    <div v-if="!connected">
      <button @click="connect" :disabled="!wallet">
        {{ wallet ? 'Connect Wallet' : 'Loading...' }}
      </button>
    </div>
    
    <div v-else>
      <p>Connected: {{ address }}</p>
      <p>Balance: {{ balance }} OCT</p>
      <button @click="disconnect">Disconnect</button>
      <button @click="sendTransaction">Send Test Transaction</button>
    </div>
  </div>
</template>

<script>
import { createOctraWallet } from '@0xgery/wallet-sdk';

export default {
  data() {
    return {
      wallet: null,
      connected: false,
      address: '',
      balance: 0
    };
  },
  
  async mounted() {
    try {
      this.wallet = await createOctraWallet({
        appName: 'My Vue DApp',
        debug: process.env.NODE_ENV === 'development'
      });

      // Setup event listeners
      this.wallet.on('connect', (event) => {
        this.connected = true;
        this.address = event.address;
        this.balance = event.balance.total;
      });

      this.wallet.on('disconnect', () => {
        this.connected = false;
        this.address = '';
        this.balance = 0;
      });
    } catch (error) {
      console.error('Failed to initialize wallet:', error);
    }
  },
  
  methods: {
    async connect() {
      try {
        await this.wallet.connect();
      } catch (error) {
        alert('Connection failed: ' + error.message);
      }
    },
    
    async disconnect() {
      await this.wallet.disconnect();
    },
    
    async sendTransaction() {
      try {
        const result = await this.wallet.sendTransaction({
          to: 'recipient_address',
          amount: 1,
          message: 'Test from Vue DApp'
        });
        alert('Transaction sent: ' + result.txHash);
      } catch (error) {
        alert('Transaction failed: ' + error.message);
      }
    }
  }
};
</script>

Vanilla JavaScript Integration

<!DOCTYPE html>
<html>
<head>
    <title>Octra Wallet Integration</title>
    <script src="https://unpkg.com/@0xgery/wallet-sdk/dist/index.umd.js"></script>
</head>
<body>
    <div id="app">
        <h2>Octra Wallet Integration</h2>
        <div id="connection-status">Loading...</div>
        <button id="connect-btn" style="display: none;">Connect Wallet</button>
        <button id="disconnect-btn" style="display: none;">Disconnect</button>
        <button id="send-btn" style="display: none;">Send Transaction</button>
    </div>

    <script>
        let wallet;
        
        async function initWallet() {
            try {
                wallet = await OctraWalletSDK.createOctraWallet({
                    appName: 'My Vanilla JS DApp',
                    debug: true
                });

                // Setup event listeners
                wallet.on('connect', (event) => {
                    document.getElementById('connection-status').textContent = 
                        `Connected: ${event.address} (${event.balance.total} OCT)`;
                    document.getElementById('connect-btn').style.display = 'none';
                    document.getElementById('disconnect-btn').style.display = 'inline';
                    document.getElementById('send-btn').style.display = 'inline';
                });

                wallet.on('disconnect', () => {
                    document.getElementById('connection-status').textContent = 'Disconnected';
                    document.getElementById('connect-btn').style.display = 'inline';
                    document.getElementById('disconnect-btn').style.display = 'none';
                    document.getElementById('send-btn').style.display = 'none';
                });

                // Show connect button
                document.getElementById('connection-status').textContent = 'Ready to connect';
                document.getElementById('connect-btn').style.display = 'inline';
                
            } catch (error) {
                document.getElementById('connection-status').textContent = 'Error: ' + error.message;
                console.error('Failed to initialize wallet:', error);
            }
        }

        // Event handlers
        document.getElementById('connect-btn').addEventListener('click', async () => {
            try {
                await wallet.connect();
            } catch (error) {
                alert('Connection failed: ' + error.message);
            }
        });

        document.getElementById('disconnect-btn').addEventListener('click', async () => {
            await wallet.disconnect();
        });

        document.getElementById('send-btn').addEventListener('click', async () => {
            try {
                const result = await wallet.sendTransaction({
                    to: 'recipient_address',
                    amount: 1,
                    message: 'Test from Vanilla JS DApp'
                });
                alert('Transaction sent: ' + result.txHash);
            } catch (error) {
                alert('Transaction failed: ' + error.message);
            }
        });

        // Initialize on page load
        initWallet();
    </script>
</body>
</html>

Security Best Practices

1. Input Validation

import { isValidAddress, isValidAmount } from '@0xgery/wallet-sdk';

// Always validate user inputs
const recipientAddress = userInput.trim();
if (!isValidAddress(recipientAddress)) {
  throw new Error('Invalid recipient address');
}

const amount = parseFloat(userAmountInput);
if (!isValidAmount(amount)) {
  throw new Error('Invalid transaction amount');
}

2. Enhanced Error Handling

import { OctraWalletError, ErrorCode, isErrorType } from '@0xgery/wallet-sdk';

try {
  await wallet.sendTransaction(txData);
} catch (error) {
  if (isErrorType(error, ErrorCode.INSUFFICIENT_BALANCE)) {
    alert('Not enough balance for this transaction');
  } else if (isErrorType(error, ErrorCode.USER_REJECTED)) {
    console.log('User cancelled the transaction');
  } else if (isErrorType(error, ErrorCode.EXTENSION_NOT_FOUND)) {
    // Enhanced diagnostics available
    console.error('Extension not found. Details:', error.details);
    alert('Please install Octra Wallet extension');
  } else {
    // All errors now include detailed context
    console.error('Transaction failed:', {
      message: error.message,
      code: error.code,
      details: error.details // Browser/extension state info
    });
    alert('Transaction failed: ' + error.message);
  }
}

3. Network Validation

const networkInfo = await wallet.getNetworkInfo();
if (networkInfo.id !== 'mainnet') {
  console.warn('Not connected to mainnet!');
  // Show warning to user or switch network
}

Development

Prerequisites

  • Node.js 16+
  • TypeScript 4.5+
  • Modern browser with extension support

Building from Source

git clone https://github.com/0xGery/Octra.git
cd Octra/wallet-sdk
npm install
npm run build

Testing

npm run test
npm run typecheck
npm run lint

Type Definitions

The SDK is fully typed with TypeScript. Import types as needed:

import {
  Balance,
  TransactionData,
  TransactionResult,
  WalletEventType,
  ConnectEvent,
  ErrorCode
} from '@0xgery/wallet-sdk';

Error Codes

CodeDescription
EXTENSION_NOT_FOUNDOctra Wallet extension not installed
CONNECTION_REFUSEDUser denied connection request
USER_REJECTEDUser rejected transaction/action
INSUFFICIENT_BALANCENot enough balance for transaction
INVALID_ADDRESSInvalid wallet address format
INVALID_AMOUNTInvalid transaction amount
NETWORK_ERRORNetwork communication failure
TRANSACTION_FAILEDTransaction processing failed
PERMISSION_DENIEDMissing required permissions
WALLET_LOCKEDWallet needs to be unlocked

Support

License

MIT License - see LICENSE for details.


Built by NullxGery (0xGery) for the Octra network

Downloads & popularity

Awaiting observations

No metric observations yet

Download counts and popularity will appear here as the collector receives them.

Declared dependencies 11

Native requirements
11 direct targetsNot calculated transitive count
Package / targetRequirementRelationship
jest
Environment
{
  "local_name": "jest",
  "alias": false,
  "peer_metadata": null
}
^29.7.0development
tslib
Environment
{
  "local_name": "tslib",
  "alias": false,
  "peer_metadata": null
}
^2.6.2development
eslint
Environment
{
  "local_name": "eslint",
  "alias": false,
  "peer_metadata": null
}
^8.57.0development
rollup
Environment
{
  "local_name": "rollup",
  "alias": false,
  "peer_metadata": null
}
^4.12.0development
typescript
Environment
{
  "local_name": "typescript",
  "alias": false,
  "peer_metadata": null
}
^5.3.3development
@types/jest
Environment
{
  "local_name": "@types/jest",
  "alias": false,
  "peer_metadata": null
}
^29.5.12development
rollup-plugin-dts
Environment
{
  "local_name": "rollup-plugin-dts",
  "alias": false,
  "peer_metadata": null
}
^6.1.0development
@rollup/plugin-replace
Environment
{
  "local_name": "@rollup/plugin-replace",
  "alias": false,
  "peer_metadata": null
}
^6.0.2development
@rollup/plugin-typescript
Environment
{
  "local_name": "@rollup/plugin-typescript",
  "alias": false,
  "peer_metadata": null
}
^11.1.6development
@typescript-eslint/parser
Environment
{
  "local_name": "@typescript-eslint/parser",
  "alias": false,
  "peer_metadata": null
}
^6.21.0development
@typescript-eslint/eslint-plugin
Environment
{
  "local_name": "@typescript-eslint/eslint-plugin",
  "alias": false,
  "peer_metadata": null
}
^6.21.0development

Distribution files

1 collected
Distribution 1

Source distribution

Source file
Checksums from source
{
  "shasum": "4363d2e7f217ba05920f8887f706f6ed68e873da",
  "tarball": "https://registry.npmjs.org/@0xgery/wallet-sdk/-/wallet-sdk-0.1.0-dev.tgz",
  "fileCount": 9,
  "integrity": "sha512-Pefo1IepK185EddiRueU/mvmW+XOAhzLWGxNXMPrUR7u7aOnGnPzxg61WU9y5653wvCQhkhwcWweI7rhhXUsxg==",
  "signatures": [
    {
      "sig": "MEQCIDxAbJtbb7bOIKFXTqoLLBi8PJIobKFps1poZKtghYVVAiAYTFgSaOLPhbLvZlAtqBwABWoC7U/kdO7z0g3jr/Kh4g==",
      "keyid": "SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"
    }
  ],
  "unpackedSize": 195008
}

Repository

PENDING
0xgery/octra

Shared repository data · GitHub

License detected in repository
Not collected

Metadata history

Meaningful changes
Current collected state Current

Observed since 21 Oct, 08:55 UTC

No superseded metadata states collected. Unchanged observations do not create new revisions.

Record identity

package_version:e5e5fdd4f2274edcb7063584f80f967da6932be4a204e13eee65cabffde767eb

Other collected versions

0.2.19 Sept0.2.09 Sept0.1.2-dev5 Sept0.1.1-dev26 AugView all collected versions →