@explorins/web3-ts
v0.3.86
Published
Enterprise TypeScript library for blockchain operations with Ethers.js and Web3.js support, transaction management, and smart contract interactions across multiple networks including Ethereum, Polygon, and PERS Besu private blockchains.
Readme
@explorins/web3-ts
A comprehensive TypeScript library for enterprise-grade Web3 and blockchain operations. Provides seamless wallet interactions, transaction management, smart contract operations, and advanced provider management across multiple blockchain networks including private chains.
🌟 Key Highlights
- 🔒 Enterprise Ready: Production-tested with 86%+ test coverage and comprehensive error handling
- 🔐 Private Chain Support: Advanced JWT authentication for private blockchain networks (PERS Besu)
- ⚡ Intelligent Providers: Adaptive retry logic, connection pooling, and health monitoring
- 🎯 Type Safety: Full TypeScript support with strict type definitions
- 🚀 Optimized Bundle: Selective imports reducing bundle size by 15-30%
- 🔧 Multi-Chain: Ethereum, Polygon, and custom private networks
📦 Installation
npm install @explorins/web3-tsRequirements
- Node.js 16+
- TypeScript 4.8+
- Ethers.js v6+ (peer dependency)
ESM & Tree-Shaking: Fully compatible with native Node.js ESM, bundlers (Webpack, Vite, Rollup), and modern runtimes (Deno, Bun). The library is marked sideEffects: false for optimal tree-shaking.
🏗️ Library Architecture
Core Modules
🔗 Connection Management
- Provider Setup: Intelligent Web3 providers with retry logic
- Chain Configuration: Multi-chain support with automatic switching
- Authentication: JWT-based authentication for private chains
💸 Transaction Operations
- EIP-1559 Support: Fee market transactions with gas optimization
- Legacy Transactions: Backward compatibility for older networks
- Transaction Parsing: Automatic type detection and validation
- Gas Management: Intelligent gas estimation and optimization
📝 Smart Contracts
- Contract Interactions: Type-safe contract method calls
- ABI Management: Pre-built ABIs for common standards (ERC20, ERC721, ERC1155)
- Validation: Parameter validation against contract ABIs
- PERS Contracts: Specialized private blockchain contract utilities
🛠️ Utilities & Helpers
- Address Utilities: Validation, normalization, and comparison
- Transaction Utilities: Parsing, validation, and analysis
- Crypto Utilities: EIP-712 signature validation
- Format Utilities: Data formatting and conversion
- Validation Suite: Comprehensive parameter and transaction validation
� Import Strategies
Convenient Imports (Recommended for Most Users)
For quick development and prototyping, import from the main entry point:
import {
getPublicWeb3ConnectionFromChainId,
parseTransactionBuffer,
validateEthereumAddress,
formatEther,
CHAIN_IDS
} from '@explorins/web3-ts';Pros: Simple, easy to use, great DX
Tree-shaking: Modern bundlers (Webpack 5+, Vite, Rollup) with our sideEffects: false configuration handle this efficiently.
Optimized Imports (For Bundle-Size Sensitive Applications)
For maximum bundle optimization, import directly from specific modules:
// Direct module imports
import { getPublicWeb3ConnectionFromChainId } from '@explorins/web3-ts/functions/connection';
import { validateEthereumAddress } from '@explorins/web3-ts/utils/address-utilities';
import { formatEther } from '@explorins/web3-ts/utils/format-utilities';
import { CHAIN_IDS } from '@explorins/web3-ts/helpers/chains';Pros: Absolute best tree-shaking, smallest possible bundle
Use when: Every kilobyte matters (mobile apps, edge functions, serverless)
Subpath Exports
The library provides convenient subpath exports for common modules:
// Ethers.js-only functionality
import { createContractReadOnly } from '@explorins/web3-ts/ethers';
// Type definitions only
import type { ChainData, TransactionParams } from '@explorins/web3-ts/types';
// Specific utilities
import { formatEther } from '@explorins/web3-ts/utils/transaction';
import { getChainById } from '@explorins/web3-ts/helpers/chains';Available subpaths:
@explorins/web3-ts- Full library (Web3.js + Ethers.js)@explorins/web3-ts/ethers- Ethers.js-only functionality@explorins/web3-ts/types- TypeScript type definitions@explorins/web3-ts/utils/transaction- Transaction utilities@explorins/web3-ts/functions/connection- Connection functions@explorins/web3-ts/helpers/chains- Chain configuration
�🚀 Quick Start Guide
Basic Setup
import {
getPublicWeb3ConnectionFromChainId,
parseTransactionBuffer,
validateEthereumAddress
} from '@explorins/web3-ts';
// Connect to Polygon
const provider = getPublicWeb3ConnectionFromChainId(137);
// Validate an address
const isValid = validateEthereumAddress('0x742d35Cc6634C0532925a3b8D91EB21C4c65c26E');
// Parse a transaction
const txBuffer = Buffer.from('02f86c...', 'hex');
const parsed = parseTransactionBuffer(txBuffer, 137, true);Smart Contract Interaction
import {
createContractReadOnly,
validateContractMethod,
safeContractCall,
ERC20_ABI
} from '@explorins/web3-ts';
// Create a read-only contract instance
const contract = createContractReadOnly(
'0xA0b86a33E6B2e5C3c1e78C9E7d8F8F1234567890',
ERC20_ABI,
provider
);
// Validate method exists before calling
validateContractMethod(contract, 'balanceOf', 'ERC20 token');
// Safe contract call with automatic validation
const balance = await safeContractCall(
contract,
'balanceOf',
['0x742d35Cc6634C0532925a3b8D91EB21C4c65c26E'],
{ validate: true, dryRun: true }
);Transaction Construction
import {
createFeeMarketTransaction,
createLegacyTransaction,
estimateContractGas
} from '@explorins/web3-ts';
// Create an EIP-1559 transaction
const feeMarketTx = await createFeeMarketTransaction({
to: '0x742d35Cc6634C0532925a3b8D91EB21C4c65c26E',
value: '1000000000000000000', // 1 ETH
chainId: 1,
maxFeePerGas: '20000000000',
maxPriorityFeePerGas: '2000000000'
});
// Estimate gas for contract interaction
const gasEstimate = await estimateContractGas(
contract,
'transfer',
['0x742d35Cc6634C0532925a3b8D91EB21C4c65c26E', '1000000000000000000']
);🔧 Advanced Configuration
Private Blockchain with JWT Authentication
import {
IntelligentWeb3Provider,
getWeb3ProviderFromChainData
} from '@explorins/web3-ts';
// Private chain configuration
const privateChainData = {
chainId: 39123,
rpcUrl: 'https://private-blockchain.company.com/rpc',
chainType: 'private' as const,
authHeader: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
};
// Token refresh function for automatic authentication
const tokenRefresher = async (): Promise<string> => {
const response = await fetch('/api/auth/refresh', {
method: 'POST',
headers: { 'Authorization': `Bearer ${refreshToken}` }
});
const data = await response.json();
return `Bearer ${data.accessToken}`;
};
// Create intelligent provider with JWT authentication
const provider = new IntelligentWeb3Provider(
privateChainData,
30000, // 30s timeout
'MyApp/1.0', // User agent
tokenRefresher, // Automatic token refresh
3 // Max retries
);Intelligent Provider Features
// Health monitoring
const isHealthy = await provider.healthCheck();
console.log('Provider healthy:', isHealthy);
// Status inspection
const status = provider.getStatus();
console.log('Provider status:', {
chainId: status.chainId,
isPrivateChain: status.isPrivateChain,
hasTokenRefresher: status.hasTokenRefresher,
ongoingRefreshes: status.ongoingRefreshes
});
// Proper cleanup
provider.disconnect();Multi-Chain Support
import {
getPublicChainById,
POLYGON_MAINNET,
ETHEREUM_MAINNET
} from '@explorins/web3-ts';
// Supported networks
const supportedChains = [
{ ...ETHEREUM_MAINNET, name: 'Ethereum' },
{ ...POLYGON_MAINNET, name: 'Polygon' },
{ chainId: 39123, name: 'PERS Besu', type: 'private' }
];
// Dynamic chain switching
const switchToChain = (chainId: number) => {
const chainData = getPublicChainById(chainId);
return getPublicWeb3ConnectionFromChainId(chainId);
};🔍 Validation & Error Handling
Comprehensive Validation
import {
validateTransactionParams,
validateContractMethodWithParams,
validateParameterType,
validateNetwork
} from '@explorins/web3-ts';
// Validate transaction parameters
validateTransactionParams({
to: '0x742d35Cc6634C0532925a3b8D91EB21C4c65c26E',
value: '1000000000000000000',
gasLimit: '21000'
}, {
requireValidAddress: true,
requireNonZeroValue: true,
maxGasLimit: '500000'
});
// Validate contract method with parameters
validateContractMethodWithParams(
contract,
'transfer',
['0x742d35Cc6634C0532925a3b8D91EB21C4c65c26E', '1000000000000000000']
);
// Validate parameter types against Solidity types
validateParameterType('1000000000000000000', 'uint256', 'amount');
validateParameterType('0x742d35Cc6634C0532925a3b8D91EB21C4c65c26E', 'address', 'recipient');Error Handling Patterns
import { validateEthereumAddress } from '@explorins/web3-ts';
try {
// Transaction with comprehensive error handling
const result = await safeContractCall(
contract,
'transfer',
['0x742d35Cc6634C0532925a3b8D91EB21C4c65c26E', '1000000000000000000'],
{ validate: true, dryRun: true }
);
console.log('Transfer successful:', result);
} catch (error: any) {
if (error.message.includes('authentication')) {
// Handle authentication errors
console.error('Authentication failed, refreshing token...');
} else if (error.message.includes('gas')) {
// Handle gas estimation errors
console.error('Gas estimation failed:', error.message);
} else {
// Generic error handling
console.error('Transaction failed:', error.message);
}
}📊 Supported Networks
| Network | Chain ID | Type | Features | Provider Support | |---------|----------|------|----------|------------------| | Ethereum Mainnet | 1 | Public | Full | ✅ Web3, Ethers, Infura | | Ethereum Sepolia | 11155111 | Testnet | Full | ✅ Web3, Ethers, Infura | | Polygon Mainnet | 137 | Public | Full | ✅ Web3, Ethers, Alchemy | | Polygon Amoy | 80002 | Testnet | Full | ✅ Web3, Ethers | | PERS Besu | 39123 | Private | Enhanced | ✅ JWT Auth, Custom | | Custom Private | Any | Private | Configurable | ✅ JWT Auth, Custom |
🛠️ Utility Functions
Transaction Analysis
import {
detectTransactionType,
getTransactionTypeName,
decodeTransactionData,
analyzeTransaction
} from '@explorins/web3-ts';
// Analyze any transaction
const txHash = '0x1234...';
const analysis = await analyzeTransaction(txHash, provider);
// Detect transaction type
const txType = detectTransactionType('02f86c...');
const typeName = getTransactionTypeName(txType); // "EIP-1559 (Fee Market)"
// Decode transaction data
const decoded = decodeTransactionData('0x02f86c...');
console.log('Transaction details:', decoded);Address Operations
import {
normalizeAddress,
compareAddresses,
extractAddressString,
validateEthereumAddress
} from '@explorins/web3-ts';
// Normalize addresses for comparison
const normalized = normalizeAddress('0xabc123...');
// Safe address comparison
const isSame = compareAddresses(address1, address2);
// Extract address from various formats
const address = extractAddressString('ethereum:0x742d35Cc...');
// Comprehensive validation
const isValid = validateEthereumAddress(address);Formatting Utilities
import {
formatEther,
formatTokenAmount,
formatGas,
formatDuration,
formatPercentage
} from '@explorins/web3-ts';
// Format Wei to Ether
const ethAmount = formatEther('1000000000000000000'); // "1.0 ETH"
// Format token amounts with decimals
const tokenAmount = formatTokenAmount('1000000', 6, 'USDC'); // "1.0 USDC"
// Format gas values
const gasFormatted = formatGas('21000'); // "21,000 gas"
// Format time durations
const duration = formatDuration(3665); // "1h 1m 5s"
// Format percentages
const percentage = formatPercentage(0.1584); // "15.84%"🔐 Security Features
EIP-712 Signature Validation
import { validateEIP712Signature } from '@explorins/web3-ts';
const domain = {
name: 'MyDApp',
version: '1',
chainId: 1,
verifyingContract: '0x742d35Cc6634C0532925a3b8D91EB21C4c65c26E'
};
const types = {
Transfer: [
{ name: 'to', type: 'address' },
{ name: 'amount', type: 'uint256' }
]
};
const message = {
to: '0x742d35Cc6634C0532925a3b8D91EB21C4c65c26E',
amount: '1000000000000000000'
};
const result = await validateEIP712Signature(
domain,
types,
message,
signature,
expectedSigner
);
console.log('Signature valid:', result.isValid);
console.log('Recovered address:', result.recoveredAddress);Private Key Management
import {
createSignerWithProvider,
convertPrivateKeyToAddress,
validateProviderHealth
} from '@explorins/web3-ts';
// Create signer from private key
const signer = createSignerWithProvider(privateKey, provider);
// Derive address from private key
const address = convertPrivateKeyToAddress(privateKey);
// Validate provider health before operations
const health = await validateProviderHealth(provider, expectedChainId);
console.log('Provider health:', health);📈 Performance Optimization
Bundle Size Optimization
// Import only what you need for smaller bundles
import { isAddress } from '@explorins/web3-ts/helpers/chains';
import { formatEther } from '@explorins/web3-ts/utils/format';
import { IntelligentWeb3Provider } from '@explorins/web3-ts/providers';
// Selective imports reduce bundle size by 15-30%Connection Pooling
// Use singleton pattern for provider management
class ProviderManager {
private static providers = new Map<string, IntelligentWeb3Provider>();
static getProvider(chainId: number): IntelligentWeb3Provider {
const key = `chain-${chainId}`;
if (!this.providers.has(key)) {
const provider = new IntelligentWeb3Provider(/* config */);
this.providers.set(key, provider);
}
return this.providers.get(key)!;
}
static cleanup(): void {
this.providers.forEach(provider => provider.disconnect());
this.providers.clear();
}
}📚 API Reference
Core Classes
IntelligentWeb3Provider
Advanced Web3 provider with retry logic and JWT authentication.
class IntelligentWeb3Provider {
constructor(
chainData: ChainData,
timeout?: number,
customUserAgent?: string,
tokenRefresher?: () => Promise<string>,
maxRetries?: number
);
send(payload: JsonRpcPayload, callback: Callback): void;
healthCheck(): Promise<boolean>;
getStatus(): ProviderStatus;
disconnect(): void;
}Core Functions
Connection Management
getPublicWeb3ConnectionFromChainId(chainId: number): Web3BaseProvidergetWeb3ProviderFromChainData(chainData: ChainData): Web3BaseProvidergetInfuraProvider(chainId: number, projectId: string): InfuraProvider
Transaction Operations
createFeeMarketTransaction(params: FeeMarketParams): Promise<Transaction>createLegacyTransaction(params: LegacyParams): Promise<Transaction>parseTransactionBuffer(buffer: Buffer, chainId: number): TransactionResult
Smart Contract Utilities
createContractReadOnly(address: string, abi: any[], provider: Provider): ContractcreateContractWithSigner(address: string, abi: any[], signer: Signer): ContractvalidateContractMethod(contract: Contract, methodName: string): void
Type Definitions
interface ChainData {
chainId?: number;
rpcUrl: string;
chainType: 'mainnet' | 'testnet' | 'private';
authHeader?: string;
}
interface TransactionParams {
to?: string;
value?: string | bigint;
gasLimit?: string | bigint;
gasPrice?: string | bigint;
maxFeePerGas?: string | bigint;
maxPriorityFeePerGas?: string | bigint;
data?: string;
nonce?: number;
}
interface ValidationConfig {
requireValidAddress?: boolean;
requireNonZeroValue?: boolean;
maxGasLimit?: string;
validateChainId?: number;
strictTypeValidation?: boolean;
}🧪 Testing
The library includes comprehensive test coverage (86%+) with Jest:
# Run all tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watchTest Categories
- ✅ Unit Tests: Individual function validation
- ✅ Integration Tests: Provider and contract interactions
- ✅ Validation Tests: Parameter and transaction validation
- ✅ Error Handling: Edge cases and error scenarios
🔧 Development
Building
# Build for both CommonJS and ESM
npm run build
# Build with cleanup
npm run build:clean
# Watch mode for development
npm run devContributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Add comprehensive tests for new functionality
- Ensure all tests pass (
npm test) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Code Standards
- TypeScript strict mode enabled
- 86%+ test coverage requirement
- ESLint configuration for code quality
- Comprehensive JSDoc documentation
📄 License
This project is licensed under a Private License - see the LICENSE file for details.
🏢 About eXplorins
Built by eXplorins for enterprise blockchain applications requiring high availability, security, and comprehensive blockchain connectivity across public and private networks.
Enterprise Features
- Production Ready: Deployed in production environments
- Enterprise Support: Commercial support available
- Private Chain Expertise: Specialized in PERS Besu integration
- Custom Development: Tailored solutions for enterprise needs
Need Help?
- � Issues & Bug Reports
- � Feature Requests
- � Enterprise Support: Contact eXplorins for custom blockchain solutions
For enterprise inquiries and custom blockchain solutions, contact eXplorins.
