How n42blockchain/erc20sdk works
Project Type and Purpose
• This is a TypeScript SDK (a client‐side library) for interacting with ERC-20 tokens on the N42 blockchain. It exposes high‐level abstractions (ERC20 token instance, Wallet, SDK bootstrap, event subscriptions), while under the hood driving HTTP RPC calls, WebSocket subscriptions, encoding/decoding of transactions, and error/retry logic.
High-Level Architecture Overview
1. Consumer/Application (top layer)
– Your user’s code (mobile app, web front end, script) that calls N42SDK APIs.
2. SDK Facade
– src/index.ts / src/sdk.ts ⇒ Initializes RPCClient & WSClient, provides erc20(address), waitForReceipt().
– src/types.ts ⇒ Shared TypeScript types and interfaces.
3. Core Modules
– ERC20 Module (src/erc20/erc20.ts)
– Wallet (src/wallet/wallet.ts)
– Events/WS (src/ws/client.ts)
– RPC Client (src/rpc/client.ts)
– Utils (src/utils/*.ts) – gas estimation, retry policy, token‐amount conversions
– Error Definitions (src/errors.ts)
4. External Systems (bottom layer)
– N42 HTTP RPC endpoint
– N42 WebSocket endpoint
Component Details & Interactions
a. N42SDK (Facade)
– Initialization: ties together RPCClient and WSClient with user‐provided config (N42Config).
– Exposes erc20(), waitForReceipt().
– Relies on types.ts for proper interfaces.
b. ERC20 Module
– Uses RPCClient to call on-chain read methods (name, symbol, totalSupply, balanceOf, allowance).
– Builds and signs transactions via Wallet, then sends via RPCClient.
– Emits or subscribes to events via WSClient.
c. Wallet
– Cryptographic key management (mnemonic, private key import).
– Signs transactions (used by ERC20 transfer/approve).
d. RPCClient
– HTTP calls to the RPC endpoint.
– Wrapped by retry logic (utils/retry.ts) and gas utilities (utils/gas.ts).
– Throws typed errors (errors.ts) on network, nonce, revert, insufficient funds.
e. WSClient
– Maintains WebSocket connection to subscribe to ERC20 events.
– Provides subscription handles to cancel, using back-off (utils/retry.ts).
f. Utils & Types
– token-amount.ts: convert between min-units and human decimal.
– retry.ts: exponential back-off wrapper.
– gas.ts: estimates and formats gas fees.
– types.ts: common type definitions for config, transfer/approve DTOs, event callbacks.
Architectural Patterns & Design Principles
• Facade Pattern: The N42SDK class hides complexity of RPC/WS/client instantiation.
• Modularization: Each concern (RPC, WS, ERC20 logic, wallet, utils) in its own directory.
• Typed Interfaces: Strong TypeScript types/interfaces separate implementation from API.
• Retry & Resilience: Centralized retry logic module for RPC and WS.
• Event-Driven: WebSocket module for real-time event subscription.
Essential Elements to Capture
• Public API layer vs. Internal modules vs. External network
• Data flow: method invocation, network requests, event streaming
• Error propagation from RPC → typed errors → public API
• Retry back-off integration with both RPC and WS modules