npm.io
0.107.1 • Published 10h ago

@debros/root-core

Licence
AGPL-3.0-only
Version
0.107.1
Deps
16
Size
5.3 MB
Vulns
0
Weekly
0

@debros/root-core

Platform-agnostic cryptocurrency wallet core implementing multi-chain support for Solana and EVM chains.

Overview

This package provides the foundational cryptographic primitives, chain adapters, and wallet management services for building cryptocurrency wallet applications. It follows Clean Architecture principles with clear separation between domain, application, and infrastructure layers.

Key Features

  • Multi-chain Support: EVM chains (Ethereum, Polygon, BSC, Arbitrum, Optimism) and Solana
  • Cryptographic Primitives: BIP-39 mnemonic generation, BIP-32/44 HD derivation, ECDSA/EdDSA signing, AES-256-GCM encryption
  • Secure by Design: Constant-time cryptographic operations using audited @noble and @scure libraries
  • Platform Agnostic: No platform-specific dependencies - works in Node.js, React Native, and browser environments
  • Type Safe: Full TypeScript support with comprehensive type definitions

Installation

pnpm add @debros/root-core

Architecture

The package follows Clean Architecture / Hexagonal Architecture:

src/
├── domain/           # Core business logic (no dependencies)
│   ├── entities/     # Wallet, Account, Transaction, Token, NFT
│   ├── interfaces/   # Abstractions (ISecureStorage, IChainAdapter, etc.)
│   ├── types/        # Type definitions
│   └── errors/       # Domain-specific errors
│
├── application/      # Business logic and use cases
│   ├── wallet/       # WalletService, WalletFactory, WalletState
│   ├── account/      # AccountService, HDDerivation, AddressValidator
│   ├── transaction/  # TransactionService, FeeEstimator, TransactionQueue
│   ├── token/        # TokenService, TokenListProvider
│   ├── balance/      # BalanceService
│   └── nft/          # NFTService
│
├── infrastructure/   # External adapters
│   ├── crypto/       # Mnemonic, HD derivation, signing, encryption
│   ├── chains/       # EVM and Solana chain adapters
│   ├── provider/     # RPC providers with caching and failover
│   └── storage/      # Storage implementations
│
└── utils/            # Encoding, formatting, validation utilities
SOLID Principles
  • Single Responsibility: Each class has one reason to change
  • Open/Closed: Open for extension via adapters, closed for modification
  • Liskov Substitution: Chain adapters are substitutable
  • Interface Segregation: Separate interfaces for different capabilities
  • Dependency Inversion: Core depends on abstractions (interfaces)

Basic Usage

Creating a New Wallet
import { WalletService, MemoryStorage, ChainType } from "@debros/root-core";

// Create storage (use platform-specific secure storage in production)
const storage = new MemoryStorage();

// Initialize wallet service
const walletService = new WalletService(storage);

// Create a new wallet with 24-word mnemonic
const { wallet, mnemonic, accounts } = await walletService.createWallet({
  name: "My Wallet",
  password: "secure-password",
  wordCount: 24,
  chains: [ChainType.EVM, ChainType.SOLANA],
});

// IMPORTANT: Securely display mnemonic to user for backup
console.log("Backup phrase:", mnemonic);
Importing an Existing Wallet
import { WalletService, MemoryStorage, ChainType } from "@debros/root-core";

const storage = new MemoryStorage();
const walletService = new WalletService(storage);

// Import from mnemonic
const { wallet, accounts } = await walletService.importWallet({
  name: "Imported Wallet",
  password: "secure-password",
  mnemonic: "your twelve or twenty four word mnemonic phrase here",
  chains: [ChainType.EVM, ChainType.SOLANA],
});
Signing Transactions
import {
  AccountService,
  TransactionService,
  createAccountService,
  createTransactionService,
} from "@debros/root-core";

// Create services
const accountService = createAccountService(walletService);
const transactionService = createTransactionService(accountService);

// Build and sign a transaction
const txResult = await transactionService.sendNative({
  fromAccountId: accounts[0].id,
  to: "0x742d35Cc6634C0532925a3b844Bc9e7595f8fE35",
  amount: BigInt("1000000000000000000"), // 1 ETH in wei
  password: "secure-password",
});
Using Cryptographic Primitives Directly
import {
  generateMnemonicPhrase,
  mnemonicToSeedBytesAsync,
  deriveEVMAccount,
  deriveSolanaAccount,
  encrypt,
  decrypt,
} from "@debros/root-core";

// Generate a 24-word mnemonic
const { phrase, words } = generateMnemonicPhrase(256);

// Derive seed from mnemonic
const seed = await mnemonicToSeedBytesAsync(phrase);

// Derive EVM account
const evmAccount = deriveEVMAccount(seed, 0);
console.log("EVM Address:", evmAccount.address);

// Derive Solana account
const solanaAccount = deriveSolanaAccount(seed, 0);
console.log("Solana Address:", solanaAccount.address);

// Encrypt sensitive data
const key = new Uint8Array(32); // Use proper key derivation in production
crypto.getRandomValues(key);
const encrypted = encrypt(new TextEncoder().encode("secret"), key);

// Decrypt data
const decrypted = decrypt(encrypted, key);
Multi-Chain Balance Queries
import {
  BalanceService,
  createBalanceService,
  ChainRegistry,
  createEVMAdapter,
} from "@debros/root-core";

// Set up chain registry
const registry = new ChainRegistry();
registry.register(createEVMAdapter(1)); // Ethereum mainnet

// Create balance service
const balanceService = createBalanceService(registry);

// Get account balances
const balance = await balanceService.getNativeBalance(
  accounts[0].address,
  ChainType.EVM,
  1, // Ethereum chain ID
);

API Reference

Domain Layer
Entities
  • Wallet - Main wallet entity with accounts and settings
  • Account - Individual blockchain account
  • Transaction - Transaction representation
  • Token - ERC-20/SPL token
  • NFT - NFT asset
Types
  • ChainType - EVM | SOLANA
  • WalletStatus - LOCKED | UNLOCKED | UNINITIALIZED
  • TransactionStatus - PENDING | CONFIRMED | FAILED
  • AccountDerivationType - HD | IMPORTED
Interfaces
  • ISecureStorage - Platform-specific secure storage
  • IChainAdapter - Chain interaction abstraction
  • ITransactionBuilder - Transaction construction
  • ITransactionSigner - Transaction signing
  • ITokenHandler - Token operations
  • INFTHandler - NFT operations
Application Layer
Services
  • WalletService - Wallet lifecycle management
  • AccountService - Account operations
  • TransactionService - Transaction building and sending
  • TokenService - Token balance and transfers
  • BalanceService - Portfolio tracking
  • NFTService - NFT management
Infrastructure Layer
Crypto
  • generateMnemonicPhrase - BIP-39 mnemonic generation
  • deriveEVMAccount / deriveSolanaAccount - Account derivation
  • signHash / signMessage - ECDSA signing (EVM)
  • signEd25519 - EdDSA signing (Solana)
  • encrypt / decrypt - AES-256-GCM encryption
  • deriveKeyScrypt / deriveKeyPBKDF2 - Key derivation
Chains
  • ChainRegistry - Chain adapter management
  • EVMChainAdapter - Ethereum and EVM-compatible chains
  • SolanaChainAdapter - Solana blockchain
  • ERC20Handler / SPLTokenHandler - Token operations
  • ERC721Handler / MetaplexHandler - NFT operations
Providers
  • RPCProvider - JSON-RPC communication
  • CachedProvider - Response caching
  • ProviderManager - Multi-provider orchestration
Storage
  • MemoryStorage - In-memory storage (testing)
  • EncryptedStorageWrapper - Encryption wrapper
Utilities
  • Encoding: bytesToHex, hexToBytes, bytesToBase58, base58ToBytes
  • Formatting: formatTokenAmount, formatAddress, formatUSD
  • Validation: isValidEthereumAddress, isValidSolanaAddress, isValidMnemonic

Security Considerations

  1. Mnemonic Handling: Always clear mnemonics from memory after use with clearMnemonic()
  2. Private Keys: Use clearDerivedAccount() to zero out private keys when done
  3. Secure Storage: Implement ISecureStorage using platform-specific secure storage (Keychain, Keystore, etc.)
  4. Password Strength: Enforce strong passwords for wallet encryption
  5. Memory Safety: All cryptographic operations use constant-time implementations

Development

# Install dependencies
pnpm install

# Type check
pnpm type-check

# Build
pnpm build

# Run tests
pnpm test

# Clean build artifacts
pnpm clean

License

AGPL-3.0-only — see the top-level LICENSE for the full text.

Keywords