@debros/root-core
v0.104.0
Published
Core cryptographic primitives and wallet functionality for Root wallet
Maintainers
Readme
@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-coreArchitecture
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 utilitiesSOLID 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 settingsAccount- Individual blockchain accountTransaction- Transaction representationToken- ERC-20/SPL tokenNFT- NFT asset
Types
ChainType-EVM|SOLANAWalletStatus-LOCKED|UNLOCKED|UNINITIALIZEDTransactionStatus-PENDING|CONFIRMED|FAILEDAccountDerivationType-HD|IMPORTED
Interfaces
ISecureStorage- Platform-specific secure storageIChainAdapter- Chain interaction abstractionITransactionBuilder- Transaction constructionITransactionSigner- Transaction signingITokenHandler- Token operationsINFTHandler- NFT operations
Application Layer
Services
WalletService- Wallet lifecycle managementAccountService- Account operationsTransactionService- Transaction building and sendingTokenService- Token balance and transfersBalanceService- Portfolio trackingNFTService- NFT management
Infrastructure Layer
Crypto
generateMnemonicPhrase- BIP-39 mnemonic generationderiveEVMAccount/deriveSolanaAccount- Account derivationsignHash/signMessage- ECDSA signing (EVM)signEd25519- EdDSA signing (Solana)encrypt/decrypt- AES-256-GCM encryptionderiveKeyScrypt/deriveKeyPBKDF2- Key derivation
Chains
ChainRegistry- Chain adapter managementEVMChainAdapter- Ethereum and EVM-compatible chainsSolanaChainAdapter- Solana blockchainERC20Handler/SPLTokenHandler- Token operationsERC721Handler/MetaplexHandler- NFT operations
Providers
RPCProvider- JSON-RPC communicationCachedProvider- Response cachingProviderManager- 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
- Mnemonic Handling: Always clear mnemonics from memory after use with
clearMnemonic() - Private Keys: Use
clearDerivedAccount()to zero out private keys when done - Secure Storage: Implement
ISecureStorageusing platform-specific secure storage (Keychain, Keystore, etc.) - Password Strength: Enforce strong passwords for wallet encryption
- 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 cleanLicense
AGPL-3.0-only — see the top-level LICENSE for the full text.
