JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 12
  • Score
    100M100P100Q59464F
  • License MIT

> ๐Ÿ› ๏ธ Turn confusing Web3 errors into clear, human-friendly messages for developers and users alike.

Package Exports

  • web3-error-helper
  • web3-error-helper/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (web3-error-helper) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

web3-error-helper

๐Ÿ› ๏ธ Turn confusing Web3 errors into clear, human-friendly messages for developers and users alike.

npm version License Build


โšก Quick Start

Get started in seconds:

import { translateError } from 'web3-error-helper';

try {
  await contract.transfer(to, amount);
} catch (err) {
  const result = translateError(err, {
    chain: 'polygon',
    customMappings: {
      'execution reverted: custom error':
        'Custom error message for your contract',
    },
  });
  console.error(result.message);
  // -> "Custom error message for your contract" or a human-readable default
}

No setup requiredโ€”just wrap your calls, and your errors are instantly readable.

โš ๏ธ Note: Currently, all EVM-compatible chains use shared error mappings. Chain-specific error patterns are planned for future releases.

๐ŸŒ Multi-Language Support

Translate errors into 20+ languages with built-in translations:

import {
  translateError,
  registerLocale,
  setCurrentLanguage,
} from 'web3-error-helper';

// Register Spanish translations
registerLocale('es', {
  errors: {
    network: 'Error de red ocurrido. Por favor verifica tu conexiรณn.',
    wallet: 'Error de billetera ocurrido. Por favor verifica tu conexiรณn.',
    insufficient_funds: 'Saldo insuficiente para la transacciรณn',
  },
});

// Set language and translate
setCurrentLanguage('es');
const result = translateError(error, { language: 'es' });
console.log(result.message); // -> "Error de red ocurrido..."

๐ŸŽฏ Advanced Usage

Custom Chain Support

Register your own blockchain networks with custom error mappings:

โš ๏ธ Note: Custom chains use the same error mappings as built-in chains. Chain-specific error patterns are not yet implemented.

import { registerCustomChain, translateError } from 'web3-error-helper';

// Register a custom chain
registerCustomChain({
  chainId: 'my-custom-chain',
  name: 'My Custom Chain',
  isEVMCompatible: true,
  errorMappings: [
    {
      pattern: 'custom error pattern',
      message: 'Custom error message for your chain',
      priority: 15,
    },
  ],
});

// Use with custom chain
const result = translateError(error, { chain: 'my-custom-chain' });

Error Categories & Advanced Options

import { translateError, SupportedChain } from 'web3-error-helper';

const result = translateError(error, {
  chain: SupportedChain.POLYGON,
  fallbackMessage: 'Custom fallback message',
  includeOriginalError: true,
  customMappings: {
    'specific error': 'Custom translation',
  },
});

console.log(result.message); // Human-readable message
console.log(result.translated); // Whether it was translated
console.log(result.chain); // Chain used
console.log(result.originalError); // Original error (if requested)

Smart Language Management

import {
  configureLanguageSelection,
  detectFromBrowser,
  getAvailableLanguages,
} from 'web3-error-helper';

// Configure language selection with optimization
const result = configureLanguageSelection({
  targetLanguages: ['es', 'pt', 'fr'],
  includeEnglishFallback: true,
  autoSuggest: true,
  loadOnlyTarget: true,
});

// Auto-detect browser language
const browserLang = detectFromBrowser(); // 'en-US' -> 'en'

// Get available languages with metadata
const languages = getAvailableLanguages();
console.log(languages); // [{ code: 'en', info: {...} }, ...]

Supported Languages (20): English (en), Spanish (es), Portuguese (pt), Chinese (zh), Japanese (ja), Korean (ko), German (de), Russian (ru), Hindi (hi), Arabic (ar), Turkish (tr), Vietnamese (vi), Thai (th), Indonesian (id), Polish (pl), Ukrainian (uk), Hebrew (he), French (fr), Italian (it), Dutch (nl)

๐Ÿ“š Complete Examples: Check out the examples/ directory for comprehensive usage examples including custom chains, advanced error handling, i18n usage, and real-world scenarios.


โœจ Features

  • Human-readable errors โ€“ Translate confusing EVM and wallet errors into clear messages.
  • Plug & Play โ€“ Wrap try/catch blocks or RPC calls without extra setup.
  • Extensible โ€“ Add your own custom error mappings per project.
  • Multi-chain support โ€“ Works across EVM-compatible chains (Ethereum, Polygon, Arbitrum, Optimism, etc.) with shared error mappings.
  • Custom chain support โ€“ Register and manage custom blockchain networks with their own error mappings.
  • ๐ŸŒ Internationalization (i18n) โ€“ Multi-language support with smart language detection and bundle optimization.
  • Smart language management โ€“ Auto-detect browser language, suggest alternatives, and optimize bundle size.
  • TypeScript-first โ€“ Fully typed for safety and autocomplete with modern ES2022 features.
  • Modern JavaScript โ€“ Built with latest JS/TS features: nullish coalescing, optional chaining, and strict type checking.

๐Ÿš€ Installation

Requirements: Node.js 18.0.0 or higher

npm install web3-error-helper
# or
yarn add web3-error-helper
# or
pnpm add web3-error-helper

๐Ÿ“‹ Compatibility: See COMPATIBILITY.md for detailed Node.js version support and migration guide.


๐Ÿ”ฎ Roadmap

โœ… Completed Features

Core Error Translation

  • Error translation system โ€“ Core functionality for translating EVM errors
  • Multi-chain support โ€“ Built-in support for Ethereum, Polygon, Arbitrum, Optimism, BSC, Avalanche, Fantom, Base (shared error mappings)
  • Custom chain support โ€“ Register and manage custom blockchain networks with full error mapping support
  • Error categories โ€“ Organized error mappings (ERC20, gas, wallet, network, transaction, contract, EVM)
  • Regex pattern matching โ€“ Advanced error pattern recognition with priority-based matching
  • Configurable fallbacks โ€“ Generic fallback messages with intelligent error type detection
  • Chain management โ€“ Comprehensive chain discovery, validation, and statistics
  • Error type detection โ€“ Automatic categorization of errors (network, wallet, contract, gas, transaction)

Type Safety & Code Quality

  • TypeScript support โ€“ Full type safety and modern ES2024 features
  • Type safety improvements โ€“ Eliminated all any types with proper TypeScript types
  • Enhanced type definitions โ€“ Comprehensive i18n type system with adapter-specific types
  • Non-null assertion fixes โ€“ Replaced with proper fallback handling
  • Type guards โ€“ Improved nested value access with safer object access

Internationalization (i18n)

  • ๐ŸŒ Multi-language support โ€“ 20 blockchain-focused languages (English, Spanish, Portuguese, Chinese, Japanese, Korean, German, Russian, Hindi, Arabic, Turkish, Vietnamese, Thai, Indonesian, Polish, Ukrainian, Hebrew, French, Italian, Dutch)
  • Smart language management โ€“ Bundle optimization with up to 70% size reduction
  • Language detection โ€“ Auto-detect browser language and suggest alternatives
  • Translation key system โ€“ Type-safe translation keys for different blockchain ecosystems
  • Partial override system โ€“ Granular control with developer-provided locales
  • Automatic fallback system โ€“ Developer translation โ†’ English fallback โ†’ Key itself
  • Language bundle optimization โ€“ Smart loading with lazy loading system

Architecture & Infrastructure

  • Modern architecture โ€“ Clean separation of concerns with modular design
  • Adapter system โ€“ Comprehensive blockchain ecosystem adapters (EVM, Solana, Cosmos, Near, Cardano, Polkadot, Algorand, Tezos, Stellar, Ripple)
  • Test infrastructure โ€“ 157/157 tests passing with 73 stable snapshots
  • Timestamp mocking โ€“ Consistent test results with mockable timestamp system
  • ESLint configuration โ€“ Clean codebase with 0 linting errors
  • Production-ready quality โ€“ Comprehensive testing and documentation

๐Ÿ“‹ Planned Features

Framework Components

  • React <ErrorMessage /> component
  • Vue <ErrorMessage /> component
  • Svelte <ErrorMessage /> component
  • Angular <ErrorMessage /> component
  • Web Component <web3-error-message>

Enhanced Error Coverage

  • Expanded error dictionary โ€“ More comprehensive error mappings for edge cases
  • Chain-specific error patterns โ€“ Individual blockchain error formats and patterns
  • Error severity classification โ€“ Automatic severity detection (low, medium, high, critical)

Developer Experience

  • Custom error formatting โ€“ Flexible error message formatting options
  • Error debugging tools โ€“ Enhanced debugging and development utilities

๐Ÿค Contributor Guidelines

We love contributions! ๐ŸŽ‰ To keep the library high-quality and consistent, please follow these simple rules:

  • Code style: Follow existing conventions (ESLint + Prettier). No style-only changes.
  • Error messages: Keep messages clear, concise, and user-friendly.
  • Issue submissions: Only create issues for actual bugs or missing core functionality. Minor suggestions or new error mappings are better suited for PRs.
  • Adding chains or frameworks: Stick to the roadmap. If you want to propose a new chain or component, open a discussion first.
  • Tests required: Always include unit tests when adding or updating error mappings.
  • Documentation: Update README/examples if you add new features.

Here's how to get started:

Setup

Requirements: Node.js 18.0.0 or higher

git clone https://github.com/YOUR_GITHUB_USERNAME/web3-error-helper.git
cd web3-error-helper
pnpm install
git checkout -b feature/my-feature

๐Ÿ’ก Node.js Version: Use nvm use to automatically switch to the correct Node.js version (specified in .nvmrc).

Branch Naming Rules

We enforce consistent branch naming to maintain project organization. All branches must follow this pattern:

Format: ^(feature|fix|hotfix|release)\/[a-z0-9._-]+$

Valid examples:

  • feature/user-authentication
  • fix/login-bug
  • hotfix/security-patch
  • release/v1.2.0

Rules:

  • Must start with: feature/, fix/, hotfix/, or release/
  • Use lowercase letters, numbers, dots, underscores, or hyphens only
  • No spaces or uppercase letters allowed

The project includes automatic validation:

  • Local validation: Pre-push hook prevents invalid branch names
  • Remote validation: GitHub Actions validates PR branch names
  • Manual check: Run npm run validate:branch anytime

Development

# Build the project
pnpm run build

# Watch for changes during development
pnpm run build:watch

# Clean build output
pnpm run clean

Adding or Updating Errors

  • Add mappings inside src/errors/ directory (JSON files for each category).
  • Keep messages clear, concise, and user-friendly.
  • Follow the existing file structure (erc20.json, gas.json, wallet.json, etc.).
  • Use the addCustomMappings function for runtime custom mappings.

Testing

pnpm run test

Ensure all tests pass before committing.

Code Style

  • ESLint + Prettier are enforced.
  • Run the linter: pnpm run lint
  • Modern JavaScript/TypeScript features are used throughout the codebase
  • Follow ES2022 standards and TypeScript strict mode

Commit Messages & Versioning

We use Conventional Commits for automatic versioning. Follow these patterns:

Major Version Bump (Breaking Changes)

git commit -m "feat!: redesign error translation API"
git commit -m "fix: resolve critical bug

BREAKING CHANGE: API interface has changed"

Minor Version Bump (New Features)

git commit -m "feat: add Polygon chain support"
git commit -m "feat: implement custom error mappings"

Patch Version Bump (Bug Fixes & Maintenance)

git commit -m "fix: resolve gas estimation error"
git commit -m "docs: update README examples"
git commit -m "chore: update dependencies"
git commit -m "test: add unit tests for error mapping"

Pull Requests

  • Use conventional commit messages (see above)
  • Open a PR with a description of your changes
  • The workflow will automatically create version tags based on your commit messages
  • Feedback may be requested before merging

Version Management

The project uses automated versioning via GitHub Actions:

  • Major bump: BREAKING CHANGE: or !: in commit messages
  • Minor bump: feat: commits
  • Patch bump: fix:, docs:, chore:, test:, etc.

๐Ÿ“œ License

MIT ยฉ Renato Ferreira