### Start local development server with yarn start
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Starts the local development server with hot reloading, providing real-time preview of documentation changes.
```bash
yarn start
```
--------------------------------
### Install dependencies with yarn
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Installs all required dependencies for the documentation project. Run this command first in the documentation directory.
```bash
yarn
```
--------------------------------
### Clone and install web3.js
Source: https://deepwiki.com/web3/web3.js/5-development-and-contribution
Commands to clone the web3.js repository and install dependencies with Yarn. The postinstall script automatically runs the build process after installation.
```bash
git clone https://github.com/web3/web3.js.git
cd web3.js
yarn install
```
--------------------------------
### Prerequisites flowchart
Source: https://deepwiki.com/web3/web3.js/5-development-and-contribution
Mermaid flowchart showing the prerequisites and setup flow for web3.js development: installing Node.js ≥ 14, npm ≥ 6.12.0, Git, cloning the repository, and running yarn install.
```mermaid
flowchart LR
dev[Developer] -->|installs| node["Node.js ≥ 14"]
dev -->|installs| npm["npm ≥ 6.12.0"]
dev -->|installs| git["Git"]
dev -->|clones| repo["web3.js repository"]
repo -->|yarn install| deps["Dependencies"]
```
--------------------------------
### Test Setup and Teardown Pattern
Source: https://deepwiki.com/web3/web3.js/5.2-testing-infrastructure
Jest setup/teardown pattern: creates a Web3 instance in beforeAll and closes the connection in afterAll using closeOpenConnection().
```javascript
// Typical test setup/teardown pattern
beforeAll(() => {
web3 = new Web3(provider);
});
afterAll(async () => {
await closeOpenConnection(web3);
});
```
--------------------------------
### Basic Ethereum Interactions
Source: https://deepwiki.com/web3/web3.js/2.1-main-web3-class
Examples for common Ethereum operations including fetching account balances, sending transactions, and retrieving the network ID.
```javascript
// Get account balance
const balance = await web3.eth.getBalance('0x1234...');
// Send transaction
const receipt = await web3.eth.sendTransaction({
from: '0x1234...',
to: '0x5678...',
value: web3.utils.toWei('1', 'ether')
});
// Get network ID
const networkId = await web3.eth.net.getId();
```
--------------------------------
### Basic ENS name resolution with web3.eth.ens.getAddress
Source: https://deepwiki.com/web3/web3.js/3.4-ethereum-name-service-%28ens%29
Initializes web3 with a provider and resolves an ENS name to an address using getAddress. The example logs the resolved address.
```javascript
// Initialize web3 with a provider
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR-PROJECT-ID');
// Resolve ENS name to an address
const address = await web3.eth.ens.getAddress('vitalik.eth');
console.log(address); // 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045
```
--------------------------------
### Tab system for JavaScript and TypeScript examples
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Defines a tab group that toggles between JavaScript and TypeScript code examples. The JavaScript tab uses `require('web3')` and the TypeScript tab uses `import { Web3 } from 'web3'`. The `default` attribute on the TypeScript tab makes it the initially selected tab.
```markup
```javascript
const { Web3 } = require('web3');
// ...
```
```typescript
import { Web3 } from 'web3';
// ...
```
```
--------------------------------
### Using ENS names in web3.js methods
Source: https://deepwiki.com/web3/web3.js/3.4-ethereum-name-service-%28ens%29
Shows how ENS names can be used in place of addresses in web3.js methods, which are automatically resolved. Includes getBalance, sendTransaction, and contract creation examples.
```javascript
// Using an ENS name where an address is expected
await web3.eth.getBalance('vitalik.eth');
// Sending a transaction to an ENS name
await web3.eth.sendTransaction({
from: myAccount,
to: 'registrar.eth',
value: web3.utils.toWei('0.1', 'ether')
});
// Creating a contract instance with an ENS name
const contract = new web3.eth.Contract(abi, 'token.eth');
```
--------------------------------
### Plugin class diagram
Source: https://deepwiki.com/web3/web3.js/5.3-plugin-system
Mermaid class diagram showing the relationship between Web3PluginBase, Web3EthPluginBase, and example custom plugins.
```mermaid
classDiagram
class Web3PluginBase {
+pluginNamespace: string
+link(parentContext: Web3Context)
}
class Web3EthPluginBase {
+pluginNamespace: string
+link(parentContext: Web3Context)
}
Web3PluginBase <|-- CustomPlugin
Web3EthPluginBase <|-- EthereumPlugin
class CustomPlugin {
+pluginNamespace: string
+customMethod()
}
class EthereumPlugin {
+pluginNamespace: string
+ethereumMethod()
}
```
--------------------------------
### Setting and getting ENS content hash with web3.eth.ens.setContenthash and getContenthash
Source: https://deepwiki.com/web3/web3.js/3.4-ethereum-name-service-%28ens%29
Sets an IPFS content hash for a domain and retrieves it. The set operation requires a transaction from the owner account with gas specified.
```javascript
// Set IPFS content hash for a domain
await web3.eth.ens.setContenthash(
'mydomain.eth',
'0xe3010170122029f2d17be6139079dc48696d1f582a8530eb9805b561eda517e22a892c7e3f1f',
{
from: ownerAccount,
gas: 5000000
}
);
// Retrieve the content hash
const contentHash = await web3.eth.ens.getContenthash('mydomain.eth');
```
--------------------------------
### Sidebar configuration in sidebars.js
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
JavaScript object defining the sidebar navigation for guides, documentation, glossary, and API sections using autogenerated directories.
```javascript
const sidebars = {
guidesSidebar: [{ type: 'autogenerated', dirName: 'guides' }],
docSidebar: [{ type: 'autogenerated', dirName: 'libdocs' }],
glossarySidebar: [{ type: 'autogenerated', dirName: 'glossary' }],
apiSidebar: [
{
type: 'autogenerated',
dirName: 'api',
},
],
};
```
--------------------------------
### Resolve ENS name to address
Source: https://deepwiki.com/web3/web3.js/3.4-ethereum-name-service-%28ens%29
Resolves a human-readable ENS name to an Ethereum address using web3.eth.ens.getAddress. The example shows the expected return value for 'vitalik.eth'.
```javascript
// Resolve an ENS name to an address
const address = await web3.eth.ens.getAddress('vitalik.eth');
// Returns: 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045
```
--------------------------------
### Decision flowchart for provider selection
Source: https://deepwiki.com/web3/web3.js/2.4-provider-architecture
Mermaid flowchart guiding the choice of provider type based on execution environment (browser vs Node.js), need for user wallet, local node availability, and real-time events.
```mermaid
flowchart TD
Start["Choose Provider Type"]
Start --> Environment{"Execution Environment?"}
Environment -->|"Browser"| BrowserNeeds{"Need User Wallet?"}
Environment -->|"Node.js"| NodeNeeds{"Local Node Available?"}
BrowserNeeds -->|"Yes"| UseEIP1193["Use EIP1193Provider\n(Browser wallet)"]
BrowserNeeds -->|"No"| BrowserEvents{"Need Real-time Events?"}
BrowserEvents -->|"Yes"| UseWS1["Use WebSocketProvider"]
BrowserEvents -->|"No"| UseHTTP1["Use HttpProvider"]
NodeNeeds -->|"Yes"| NodePerformance{"Need Max Performance?"}
NodeNeeds -->|"No"| NodeEvents{"Need Real-time Events?"}
NodePerformance -->|"Yes"| UseIPC["Use IpcProvider"]
NodePerformance -->|"No"| NodeEvents
NodeEvents -->|"Yes"| UseWS2["Use WebSocketProvider"]
NodeEvents -->|"No"| UseHTTP2["Use HttpProvider"]
```
--------------------------------
### Reverse resolution of ENS name
Source: https://deepwiki.com/web3/web3.js/3.4-ethereum-name-service-%28ens%29
Looks up the ENS name associated with a given Ethereum address using web3.eth.ens.reverseResolution. The example shows the expected return value for the address.
```javascript
// Get the ENS name for an address (if set)
const name = await web3.eth.ens.reverseResolution('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045');
// Returns: vitalik.eth
```
--------------------------------
### Initializing Web3
Source: https://deepwiki.com/web3/web3.js/2.1-main-web3-class
Demonstrates various ways to initialize the Web3 instance using HTTP, WebSocket, browser providers, or custom configuration options.
```javascript
// With HTTP provider
const web3 = new Web3('http://localhost:8545');
// With WebSocket provider
const web3 = new Web3('ws://localhost:8546');
// With existing provider (e.g., from browser)
const web3 = new Web3(window.ethereum);
// With custom options
const web3 = new Web3({
provider: 'http://localhost:8545',
defaultAccount: '0x1234...',
defaultBlock: 'latest'
});
```
--------------------------------
### Serve built documentation locally with yarn serve
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Serves the built documentation locally to preview the production build.
```bash
yarn serve
```
--------------------------------
### Setting and switching providers in Web3.js
Source: https://deepwiki.com/web3/web3.js/2.4-provider-architecture
Shows how to initialize a Web3 instance with an HTTP provider, switch to a WebSocket provider using setProvider, and use a WebSocketProvider instance. Setting a provider on the main Web3 instance updates all modules.
```javascript
// Initialize with one provider
const web3 = new Web3('http://localhost:8545');
// Switch to a different provider
web3.setProvider('ws://localhost:8546');
// Or use a provider instance
web3.setProvider(new WebSocketProvider('ws://localhost:8546'));
```
--------------------------------
### Plugin System Implementation
Source: https://deepwiki.com/web3/web3.js/2.1-main-web3-class
Shows how to extend the Web3 class by creating a custom plugin class, registering it, and invoking its methods.
```javascript
// Create a plugin
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'myPlugin';
// Custom methods
async customMethod() {
// Implementation
}
}
// Register plugin
web3.registerPlugin(new MyPlugin());
// Use plugin
await web3.myPlugin.customMethod();
```
--------------------------------
### Build documentation for production with yarn build
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Builds the documentation for production, generating a static website in the build/ directory.
```bash
yarn build
```
--------------------------------
### Deploy documentation using SSH (USE_SSH=true yarn deploy)
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Deploys the documentation to the configured hosting provider (typically GitHub Pages) using SSH authentication.
```bash
# Deploy using SSH
USE_SSH=true yarn deploy
```
--------------------------------
### Contract instantiation with web3.eth.Contract
Source: https://deepwiki.com/web3/web3.js/2.1-main-web3-class
Shows three ways to instantiate a contract using the ContractBuilder class assigned to eth.Contract: with only the ABI, with ABI and address, and with ABI, address, and options.
```javascript
// Simple instantiation with ABI
const contract = new web3.eth.Contract(abi);
// With ABI and address
const contract = new web3.eth.Contract(abi, address);
// With ABI, address, and options
const contract = new web3.eth.Contract(abi, address, options);
```
--------------------------------
### Deploy documentation using GitHub token (GIT_USER= yarn deploy)
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Deploys the documentation to the configured hosting provider (typically GitHub Pages) using a GitHub token for authentication. Replace with your actual GitHub username.
```bash
# Or deploy using GitHub token
GIT_USER= yarn deploy
```
--------------------------------
### Documentation Deployment Workflow
Source: https://deepwiki.com/web3/web3.js/5-development-and-contribution
Visual representation of the automated documentation build and deployment process to Cloudflare Pages.
```mermaid
flowchart LR
push["Push to 4.x"] --> generate["Generate API Docs"]
generate --> build["Build Documentation Site"]
build --> deploy["Deploy to Cloudflare Pages"]
```
--------------------------------
### Documentation Build Process Flowchart
Source: https://deepwiki.com/web3/web3.js/5-development-and-contribution
Visual representation of the documentation generation pipeline from TypeScript source and Markdown files to the final deployment on Cloudflare Pages.
```mermaid
flowchart TD
source["TypeScript Source"] --> typedoc["TypeDoc"]
markdown["Markdown Files"] --> docSite["Documentation Site"]
typedoc --> apiDocs["API Documentation"]
apiDocs --> docSite
docSite --> cloudflare["Cloudflare Pages"]
```
--------------------------------
### Build Process Flowchart (Mermaid)
Source: https://deepwiki.com/web3/web3.js/1.2-repository-structure
Mermaid diagram illustrating the build steps: clean, parallel builds for CJS/ESM/types, and adding package.json files. Use to understand the build pipeline.
```mermaid
flowchart TD
Start["Build Start"] --> Clean["Clean (rimraf dist & lib)"]
Clean --> Parallel["Parallel Builds"]
Parallel --> BuildCJS["Build CommonJS"]
Parallel --> BuildESM["Build ESM"]
Parallel --> BuildTypes["Build TypeScript Declarations"]
BuildCJS --> TSC_CJS["tsc --build tsconfig.cjs.json"]
BuildESM --> TSC_ESM["tsc --build tsconfig.esm.json"]
BuildTypes --> TSC_Types["tsc --build tsconfig.types.json"]
TSC_CJS --> PackageJSON_CJS["Add package.json with type:commonjs"]
TSC_ESM --> PackageJSON_ESM["Add package.json with type:module"]
PackageJSON_CJS --> BuildComplete["Build Complete"]
PackageJSON_ESM --> BuildComplete
TSC_Types --> BuildComplete
```
--------------------------------
### Default Provider (mainnet)
Source: https://deepwiki.com/web3/web3.js/2.4-provider-architecture
Creates a Web3 instance using the default mainnet provider when no provider is specified.
```javascript
// Using default provider (mainnet)
const web3 = new Web3();
```
--------------------------------
### Backend Conditional Testing with describeIf
Source: https://deepwiki.com/web3/web3.js/5.2-testing-infrastructure
Conditional test suite using describeIf to run tests only when the backend is not 'hardhat', based on getSystemTestBackend().
```javascript
describeIf(getSystemTestBackend() !== 'hardhat')(
`${getSystemTestBackend()} tests - methodName`,
() => {
// Test suite
}
);
```
--------------------------------
### Request EIP-6963 Providers and Listen for New Providers
Source: https://deepwiki.com/web3/web3.js/2.4-provider-architecture
Use Web3.requestEIP6963Providers() to request all available EIP-6963 providers and Web3.onNewProviderDiscovered() to listen for new providers. The callback receives providerInfo and can connect to the provider by creating a new Web3 instance.
```javascript
// Request all available EIP-6963 providers
Web3.requestEIP6963Providers();
// Listen for new providers
Web3.onNewProviderDiscovered((providerInfo) => {
console.log('New provider discovered:', providerInfo.info.name);
// Connect to the provider
const web3 = new Web3(providerInfo.provider);
});
```
--------------------------------
### Set ENS address and resolver
Source: https://deepwiki.com/web3/web3.js/3.4-ethereum-name-service-%28ens%29
Shows how to set the address and resolver for an ENS domain using web3.eth.ens.setAddress and setResolver. Both require ownership and specify gas limits.
```javascript
// Set the address for a name (requires ownership)
await web3.eth.ens.setAddress(
'mydomain.eth',
'0x8c1eD7e19abAa9f23c476dA86Dc1577F1Ef401f5',
{
from: ownerAccount,
gas: 5000000
}
);
```
```javascript
// Set the resolver for a domain
await web3.eth.ens.setResolver(
'mydomain.eth',
'0x4976fb03C32e5B8cfe2b6cCB31c09Ba78EBaBa41',
{
from: ownerAccount,
gas: 5000000
}
);
```
--------------------------------
### Smart Contract Interactions
Source: https://deepwiki.com/web3/web3.js/2.1-main-web3-class
Covers creating contract instances, calling constant methods, sending transactions to contracts, and deploying new contracts.
```javascript
// Create contract instance
const contract = new web3.eth.Contract(abi, contractAddress);
// Call constant function
const result = await contract.methods.myMethod().call();
// Send transaction to contract
const receipt = await contract.methods.myMethod(param).send({
from: '0x1234...'
});
// Deploy new contract
const newContract = await contract.deploy({
data: '0x...',
arguments: [arg1, arg2]
}).send({
from: '0x1234...'
});
```
--------------------------------
### Web3 constructor signature
Source: https://deepwiki.com/web3/web3.js/2.1-main-web3-class
The constructor accepts a provider string, a supported provider instance, a Web3ContextInitOptions object, or no parameters (defaulting to mainnet).
```typescript
constructor(
providerOrContext:
| string
| SupportedProviders
| Web3ContextInitOptions = mainnet,
)
```
--------------------------------
### Mermaid flowchart of documentation build and deployment
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Flowchart showing the input, build, output, and deployment stages. Markdown, TypeScript source, and config files are processed by yarn build and docusaurus build, which invokes TypeDoc. The build directory is deployed to static hosting.
```mermaid
flowchart TD
subgraph "Input"
MDFiles["Markdown Files"]
TSSource["TypeScript Source"]
ConfigFiles["Configuration Files"]
end
subgraph "Build Process"
YarnBuild["yarn build"]
DocusaurusBuild["docusaurus build"]
TypeDocAPI["TypeDoc API Generator"]
YarnBuild --> DocusaurusBuild
DocusaurusBuild -- "Process markdown" --> MDFiles
DocusaurusBuild -- "Use configuration" --> ConfigFiles
DocusaurusBuild -- "Invoke TypeDoc" --> TypeDocAPI
TypeDocAPI -- "Analyze source" --> TSSource
end
subgraph "Output"
BuildDir["build/ directory"]
StaticFiles["Static Files (HTML/CSS/JS)"]
DocusaurusBuild --> BuildDir
BuildDir --> StaticFiles
end
subgraph "Deployment"
YarnDeploy["yarn deploy"]
StaticHosting["Static Web Hosting"]
BuildDir --> YarnDeploy
YarnDeploy --> StaticHosting
StaticHosting --> LiveSite["docs.web3js.org"]
end
```
--------------------------------
### Listen to Provider Connection Events
Source: https://deepwiki.com/web3/web3.js/2.4-provider-architecture
All providers emit events for connection status changes. Listen for 'connect', 'error', and 'disconnect' events to handle connection state changes.
```javascript
provider.on('connect', () => console.log('Connected to the network'));
provider.on('error', (error) => console.error('Provider error:', error));
provider.on('disconnect', () => console.log('Disconnected from the network'));
```
--------------------------------
### Setting up reverse ENS resolution with web3.eth.ens.setName and reverseResolution
Source: https://deepwiki.com/web3/web3.js/3.4-ethereum-name-service-%28ens%29
Sets a reverse resolution name for an address and then looks it up. Requires a transaction from the owner account and specifies gas.
```javascript
// Set reverse resolution for your address
await web3.eth.ens.setName(
'my-custom-name.eth',
{
from: myAccount,
gas: 5000000
}
);
// Now others can look up your address by name
const name = await web3.eth.ens.reverseResolution(myAccount);
console.log(name); // my-custom-name.eth
```
--------------------------------
### Documentation directory structure (Mermaid diagram)
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Mermaid diagram showing the hierarchy of the documentation system, including configuration files, source directories, and content directories.
```mermaid
graph TD
DocsRoot["docs/"] --> PackageJSON["package.json"]
DocsRoot --> DocusaurusConfig["docusaurus.config.js"]
DocsRoot --> SidebarsJS["sidebars.js"]
DocsRoot --> SourceDir["src/"]
DocsRoot --> ContentDir["docs/"]
SourceDir --> CSSDir["css/"]
SourceDir --> ThemeDir["theme/"]
CSSDir --> CustomCSS["custom.css"]
ThemeDir --> SearchBarDir["SearchBar/"]
SearchBarDir --> SearchBarIndex["index.js"]
ContentDir --> GuidesDir["guides/"]
ContentDir --> LibDocsDir["libdocs/"]
ContentDir --> GlossaryDir["glossary/"]
ContentDir --> PlaygroundMD["web3_playground.md"]
```
--------------------------------
### Build Process Flow Sequence Diagram
Source: https://deepwiki.com/web3/web3.js/5.1-build-system
Mermaid sequence diagram illustrating the build process flow from developer invocation through Yarn, Lerna, TypeScript compilation, and optional Webpack bundling. Shows the loop over packages and the alternative web build path.
```mermaid
sequenceDiagram
participant Dev as "Developer"
participant Yarn as "Yarn/NPM"
participant Lerna as "Lerna"
participant TS as "TypeScript Compiler"
participant Webpack as "Webpack"
Dev->>Yarn: yarn build
Yarn->>Yarn: yarn clean
Yarn->>Yarn: ts-node scripts/init.ts
Yarn->>Lerna: lerna run build
loop For each package
Lerna->>TS: Compile TypeScript
TS->>TS: Generate .d.ts files
TS->>TS: Compile to JavaScript
alt Web Build
Lerna->>Webpack: Bundle for browsers
Webpack->>Webpack: Apply plugins & optimizations
Webpack->>Webpack: Generate browser bundles
end
end
Lerna->>Yarn: Build complete
Yarn->>Dev: Return build status
```
--------------------------------
### AI search integration in SearchBarWrapper
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Implements the AI-powered search by wrapping the default SearchBar and adding the AskCookbook component. It uses a public API key constant `ASK_COOKBOOK_PUBLIC_KEY` and the `@cookbookdev/docsbot/react` package. The component returns a fragment containing both the original search bar and the AI assistant.
```javascript
import React from 'react';
import SearchBar from '@theme-original/SearchBar';
import AskCookbook from '@cookbookdev/docsbot/react';
// Public API key for the Web3.js documentation
const ASK_COOKBOOK_PUBLIC_KEY =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2NjdjNzc3YzNmOGY3Mzk2MGYzZGNiOGYiLCJpYXQiOjE3MTk0MzMwODQsImV4cCI6MjAzNTAwOTA4NH0.OXWVNJMxMuEGG1oWetW_a9005r8hmQ6RbF19wbrpTlk';
export default function SearchBarWrapper(props) {
return (
<>
>
);
}
```
--------------------------------
### IPC Provider Configuration
Source: https://deepwiki.com/web3/web3.js/2.4-provider-architecture
Shows IPC provider paths for different operating systems: Mac OS, Windows (commented), and Linux (commented).
```javascript
// Different paths based on operating system
// Mac OS path
const ipcProvider = new IpcProvider('/Users/myuser/Library/Ethereum/geth.ipc');
// Windows path
// const ipcProvider = new IpcProvider('\\.\\pipe\\geth.ipc');
// Linux path
// const ipcProvider = new IpcProvider('/users/myuser/.ethereum/geth.ipc');
```
--------------------------------
### Build process flowchart
Source: https://deepwiki.com/web3/web3.js/5-development-and-contribution
Mermaid flowchart illustrating the web3.js build process: TypeScript source files are initialized via ts-node scripts/init.ts, then built into CommonJS, ESM, TypeScript declarations, and browser bundles. Browser bundles can be minified with webpack or analyzed with webpack-bundle-analyzer.
```mermaid
flowchart TD
source["TypeScript Source Files"] -->|ts-node scripts/init.ts| initialized["Initialized Source"]
initialized -->|build:cjs| cjs["CommonJS Output"]
initialized -->|build:esm| esm["ESM Output"]
initialized -->|build:types| types["TypeScript Declarations"]
initialized -->|build:web| web["Browser Bundles"]
web -->|webpack| minified["Minified Bundles"]
web -->|webpack-bundle-analyzer| analyzed["Bundle Analysis"]
subgraph "Build Process"
cjs
esm
types
web
end
```
--------------------------------
### WebSocket Provider Configuration
Source: https://deepwiki.com/web3/web3.js/2.4-provider-architecture
Shows basic and advanced configuration of the WebSocket provider, including client options and reconnection settings.
```javascript
// Basic configuration
const wsProvider = new WebSocketProvider('ws://localhost:8546');
// With client options and reconnection settings
const wsProviderWithOptions = new WebSocketProvider(
'ws://localhost:8546',
{
headers: {
authorization: "Basic username:password",
},
maxPayload: 100000000,
},
{
autoReconnect: true,
delay: 5000, // ms
maxAttempts: 5,
}
);
```
--------------------------------
### Documentation System Architecture Diagram
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Mermaid diagram showing the components of the documentation system: Docusaurus core, plugins, content sources, and build output.
```mermaid
graph TD
subgraph "Documentation System"
DocusaurusCore["docusaurus/core"]
DocusaurusPreset["docusaurus/preset-classic"]
TypeDocPlugin["docusaurus-plugin-typedoc-api"]
LunrSearchPlugin["docusaurus-lunr-search"]
LiveCodeBlock["docusaurus/theme-live-codeblock"]
CookbookBot["cookbookdev/docsbot"]
DocusaurusCore --> DocusaurusPreset
DocusaurusCore --> TypeDocPlugin
DocusaurusCore --> LunrSearchPlugin
DocusaurusCore --> LiveCodeBlock
DocusaurusCore --> CookbookBot
end
subgraph "Content Sources"
MarkdownDocs["Markdown Files"]
TypeScriptSource["TypeScript Source Files"]
DocsConfig["docusaurus.config.js"]
SidebarsConfig["sidebars.js"]
CustomCSS["src/css/custom.css"]
SearchBarCustom["src/theme/SearchBar/index.js"]
MarkdownDocs --> DocusaurusPreset
TypeScriptSource --> TypeDocPlugin
DocsConfig --> DocusaurusCore
SidebarsConfig --> DocusaurusPreset
CustomCSS --> DocusaurusPreset
SearchBarCustom --> DocusaurusPreset
end
subgraph "Build Output"
StaticHTML["Static HTML"]
StaticCSS["Static CSS"]
StaticJS["Static JavaScript"]
DocusaurusCore --> StaticHTML
DocusaurusCore --> StaticCSS
DocusaurusCore --> StaticJS
end
```
--------------------------------
### Canary Release Workflow
Source: https://deepwiki.com/web3/web3.js/5-development-and-contribution
Visual representation of the canary release process triggered by pushes to the 4.x branch.
```mermaid
flowchart LR
push["Push to 4.x"] --> build["Build Packages"]
build --> canary["Generate Canary Version"]
canary --> npm["Publish to npm with dev tag"]
```
--------------------------------
### Web3.js Core Architecture Diagram
Source: https://deepwiki.com/web3/web3.js/1-overview
Architecture diagram of web3.js core system showing how the main Web3 class extends Web3Context, includes core modules, and provides utilities. It illustrates the relationships between Web3RequestManager, providers, and the Ethereum network, as well as the specialized packages like web3-eth, web3-eth-contract, web3-eth-accounts, and web3-eth-ens.
```mermaid
graph TD
client["Client Application"] -->|uses| web3["web3.js"]
subgraph "web3.js Core System"
web3 -->|extends| context["Web3Context"]
web3 -->|includes| modules["Core Modules"]
web3 -->|provides| utils["Utilities"]
context -->|manages| requestManager["Web3RequestManager"]
context -->|supports| plugins["Plugin System"]
context -->|manages| config["Web3Config"]
requestManager -->|uses| providers["Providers"]
providers -->|connects to| ethereum["Ethereum Network"]
modules -->|includes| eth["web3-eth"]
modules -->|includes| contract["web3-eth-contract"]
modules -->|includes| accounts["web3-eth-accounts"]
modules -->|includes| ens["web3-eth-ens"]
modules -->|includes| other["Other Modules..."]
end
```
--------------------------------
### HTTP Provider Configuration
Source: https://deepwiki.com/web3/web3.js/2.4-provider-architecture
Shows basic and advanced configuration of the HTTP provider, including options for keepalive, credentials, and headers.
```javascript
// Basic configuration
const httpProvider = new HttpProvider('http://localhost:8545');
// With options
const httpProviderWithOptions = new HttpProvider('http://localhost:8545', {
providerOptions: {
keepalive: true,
credentials: "omit",
headers: {
"Access-Control-Allow-Origin": "*",
},
},
});
```
--------------------------------
### Network testing infrastructure flowchart
Source: https://deepwiki.com/web3/web3.js/5.2-testing-infrastructure
Mermaid flowchart illustrating the network testing infrastructure for web3.js. Shows how tests connect to local nodes (Hardhat, Geth) and remote nodes (Sepolia, Infura) over HTTP, WebSocket, and IPC.
```mermaid
flowchart TD
subgraph "Network Testing Environments"
direction TB
Web3Tests["Web3.js Tests"] --> Providers["Test Providers"]
Providers --> LocalNodes["Local Nodes"]
Providers --> RemoteNodes["Remote Nodes"]
LocalNodes --> HardhatNode["Hardhat Node"]
LocalNodes --> GethNode["Local Geth Node"]
RemoteNodes --> Testnets["Public Testnets"]
RemoteNodes --> PublicNodes["Public Node Providers"]
Testnets --> Sepolia["Sepolia Testnet"]
PublicNodes --> Infura["Infura Provider"]
subgraph "Connection Protocols"
HttpConnection["HTTP"]
WsConnection["WebSocket"]
IpcConnection["IPC"]
end
LocalNodes --> HttpConnection
LocalNodes --> WsConnection
LocalNodes --> IpcConnection
RemoteNodes --> HttpConnection
RemoteNodes --> WsConnection
end
```
--------------------------------
### web3.eth property structure diagram
Source: https://deepwiki.com/web3/web3.js/2.1-main-web3-class
Mermaid diagram showing the structure of the web3.eth property and its attached modules, including core ETH methods, ENS, Iban, net, personal, Contract, abi, and accounts.
```mermaid
graph TD
Web3["Web3"] --> Eth["web3.eth"]
Eth --> EthCore["Core ETH Methods"]
Eth --> ENS["eth.ens"]
Eth --> Iban["eth.Iban"]
Eth --> Net["eth.net"]
Eth --> Personal["eth.personal"]
Eth --> Contract["eth.Contract"]
Eth --> Abi["eth.abi"]
Eth --> Accounts["eth.accounts"]
Contract --> Methods["contract.methods"]
Contract --> Events["contract.events"]
Contract --> Deploy["contract.deploy()"]
```
--------------------------------
### Configure WebSocket Provider Auto-Reconnection
Source: https://deepwiki.com/web3/web3.js/2.4-provider-architecture
Create a WebSocketProvider with auto-reconnection options to handle unexpected disconnections. The options include autoReconnect, delay, and maxAttempts.
```javascript
const wsProvider = new WebSocketProvider('ws://localhost:8546', {}, {
autoReconnect: true,
delay: 5000,
maxAttempts: 5,
});
```
--------------------------------
### Request Flow Sequence Diagram
Source: https://deepwiki.com/web3/web3.js/1-overview
Sequence diagram illustrating the request flow through web3.js, from the client application to the Ethereum node and back, including middleware and error handling steps.
```mermaid
sequenceDiagram
participant App as Client Application
participant Web3 as web3.js
participant Context as Web3Context
participant RequestManager as Web3RequestManager
participant Provider as Provider (HTTP/WS/IPC)
participant Node as Ethereum Node
App->>Web3: Make request (e.g., getBalance)
Web3->>Context: Forward request
Context->>RequestManager: send(method, params)
alt Has middleware
RequestManager->>RequestManager: Apply request middleware
end
RequestManager->>Provider: request({method, params})
Provider->>Node: JSON-RPC request
Node->>Provider: JSON-RPC response
Provider->>RequestManager: Response data
alt Has middleware
RequestManager->>RequestManager: Apply response middleware
end
alt Error response
RequestManager->>RequestManager: Create appropriate error object
end
RequestManager->>Context: Formatted response/error
Context->>Web3: Pass response/error
Web3->>App: Return result
```
--------------------------------
### GitHub Actions test workflow flowchart
Source: https://deepwiki.com/web3/web3.js/5.2-testing-infrastructure
Mermaid flowchart describing the GitHub Actions test workflow: a build job produces artifacts that feed parallel test jobs (unit, lint, ESM build, types build, web build, integration, E2E browser, benchmark). Integration tests split into Hardhat and Geth tests; unit tests feed code coverage and a Codecov report.
```mermaid
flowchart TD
subgraph "GitHub Actions Test Workflow"
direction TB
Trigger["Push/PR to 4.x Branch"] --> BuildJob["Build Job"]
BuildJob --> Artifacts["Build Artifacts"]
Artifacts --> ParallelJobs["Parallel Test Jobs"]
ParallelJobs --> UnitTests["Unit Tests"]
ParallelJobs --> Lint["Lint"]
ParallelJobs --> BuildESM["Build ESM"]
ParallelJobs --> BuildTypes["Build Types"]
ParallelJobs --> BuildWeb["Build Web"]
ParallelJobs --> IntegrationTests["Integration Tests"]
IntegrationTests --> HardhatTests["Hardhat Tests"]
IntegrationTests --> GethTests["Geth Tests"]
ParallelJobs --> E2ETests["E2E Browser Tests"]
ParallelJobs --> Benchmark["Benchmark Tests"]
UnitTests --> Coverage["Code Coverage"]
Coverage --> Codecov["Codecov Report"]
end
```
--------------------------------
### Yarn Workspaces Configuration
Source: https://deepwiki.com/web3/web3.js/1.2-repository-structure
Defines the workspace packages for the monorepo, enabling dependency hoisting and symlinking between local packages.
```json
"workspaces": {
"packages": [
"packages/*",
"tools/*"
]
}
```
--------------------------------
### Interactive playground iframe
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Embeds the Web3.js StackBlitz playground in an iframe. The `src` URL includes parameters for embedding, specifying the file to show, and hiding navigation. The iframe is set to a height of 700px and a width of 80%.
```html
```
--------------------------------
### Test Utilities Flowchart
Source: https://deepwiki.com/web3/web3.js/5.2-testing-infrastructure
Mermaid flowchart showing the hierarchy of web3.js test utilities, including test fixtures, helpers, and specific functions like getSystemE2ETestProvider() and toAllVariants().
```mermaid
flowchart LR
subgraph "Test Utilities"
direction TB
Utilities["Test Utilities"] --> Fixtures["Test Fixtures"]
Utilities --> Utils["Test Helpers"]
Fixtures --> BlockData["Block Data Fixtures"]
Fixtures --> NetworkData["Network Fixtures"]
Utils --> E2EUtils["E2E Test Utilities"]
Utils --> SharedUtils["Shared Test Utilities"]
E2EUtils --> GetProvider["getSystemE2ETestProvider()"]
E2EUtils --> GetAccount["getE2ETestAccountAddress()"]
SharedUtils --> VariantGenerator["toAllVariants()"]
SharedUtils --> ConnectionManager["closeOpenConnection()"]
end
```
--------------------------------
### Lerna Configuration for Independent Versioning
Source: https://deepwiki.com/web3/web3.js/1.2-repository-structure
Configures Lerna 4.0.0 with Yarn workspaces and independent versioning. Enables per-package versioning while supporting coordinated releases.
```json
{
"lerna": "4.0.0",
"npmClient": "yarn",
"useWorkspaces": true,
"version": "independent",
"packages": ["packages/*", "tools/*"]
}
```
--------------------------------
### Unit Test Structure
Source: https://deepwiki.com/web3/web3.js/5-development-and-contribution
Basic structure for unit tests located in the test/unit directory of each package.
```javascript
// Basic unit test structure
describe('MyClass', () => {
it('should perform a specific operation', () => {
const result = myFunction();
expect(result).toBe(expectedValue);
});
});
```
--------------------------------
### Mermaid diagram of repository structure
Source: https://deepwiki.com/web3/web3.js/1.2-repository-structure
A Mermaid graph showing the monorepo organization, including core infrastructure, Ethereum functionality, provider packages, and the main web3 package.
```mermaid
graph TD
Root["web3.js Repository"] --> Packages["packages/"]
Root --> Tools["tools/"]
Root --> Scripts["scripts/"]
Packages --> CorePackages["Core Infrastructure"]
Packages --> EthPackages["Ethereum Functionality"]
Packages --> ProviderPackages["Connection Layer"]
CorePackages --> web3core["web3-core"]
CorePackages --> web3types["web3-types"]
CorePackages --> web3errors["web3-errors"]
CorePackages --> web3utils["web3-utils"]
CorePackages --> web3validator["web3-validator"]
EthPackages --> web3eth["web3-eth"]
EthPackages --> web3ethContract["web3-eth-contract"]
EthPackages --> web3ethAccounts["web3-eth-accounts"]
EthPackages --> web3ethAbi["web3-eth-abi"]
EthPackages --> web3ethIban["web3-eth-iban"]
EthPackages --> web3ethEns["web3-eth-ens"]
EthPackages --> web3ethPersonal["web3-eth-personal"]
EthPackages --> web3net["web3-net"]
ProviderPackages --> web3providersHttp["web3-providers-http"]
ProviderPackages --> web3providersWs["web3-providers-ws"]
ProviderPackages --> web3providersIpc["web3-providers-ipc"]
Root --> MainPackage["web3 (Main Package)"]
```
--------------------------------
### Parametrized Testing with it.each
Source: https://deepwiki.com/web3/web3.js/5.2-testing-infrastructure
Parametrized testing using Jest's it.each with toAllVariants() to generate test cases for multiple input combinations.
```javascript
it.each(
toAllVariants<{ block: 'latest' | 'pending' | ... }>({
block: ['latest', 'pending', ...],
})
)('methodName', async ({ block }) => {
// Test implementation
});
```
--------------------------------
### Web3 Class Diagram (Mermaid)
Source: https://deepwiki.com/web3/web3.js/2.1-main-web3-class
Mermaid class diagram showing the inheritance and composition relationships of the Web3 class, including Web3Context, Web3Eth, and associated modules.
```mermaid
classDiagram
Web3Context <|-- Web3
Web3 *-- Web3Eth
Web3 *-- Utils
Web3Eth *-- Contract
Web3Eth *-- ENS
Web3Eth *-- Personal
Web3Eth *-- Net
class Web3Context {
+provider
+requestManager
+config
+setProvider()
+use()
+registerPlugin()
}
class Web3 {
+static version
+static utils
+static modules
+static requestEIP6963Providers()
+static onNewProviderDiscovered()
+utils
+eth
+constructor(providerOrContext)
}
class Web3Eth {
+getBalance()
+sendTransaction()
+Contract
+ens
+net
+personal
+abi
+accounts
}
class Contract {
+methods
+events
+deploy()
}
```
--------------------------------
### Package Exports Configuration (package.json)
Source: https://deepwiki.com/web3/web3.js/1.2-repository-structure
Defines the exports field for a package, providing type, import, and require entry points. Enables CommonJS, ESM, and TypeScript usage.
```json
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"import": "./lib/esm/index.js",
"require": "./lib/commonjs/index.js"
}
}
```
--------------------------------
### Custom CSS for playground iframe
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Styles the playground iframe by its ID `#playground-iframe`, setting its width to 92vw, height to 700px, and removing default margins and padding.
```css
#playground-iframe {
width: 92vw;
height: 700px;
margin: 0;
padding: 0;
}
```
--------------------------------
### Build Toolchain Flowchart (Mermaid)
Source: https://deepwiki.com/web3/web3.js/5.1-build-system
Mermaid flowchart illustrating the build toolchain: TypeScript source is compiled by tsc into JavaScript for Node.js, declaration files, and modern JavaScript, which is then bundled by Webpack and analyzed by Webpack Bundle Analyzer.
```mermaid
flowchart TD
subgraph "Build Toolchain"
source["TypeScript Source"]
source --> tsc["TypeScript Compiler (tsc)"]
tsc --> jsNode["JavaScript for Node.js"]
tsc --> dts["Declaration Files (.d.ts)"]
tsc --> jsModern["JavaScript for Modern Environments"]
jsModern --> webpack["Webpack"]
webpack --> bundle["Browser Bundles"]
bundle --> analyzer["Webpack Bundle Analyzer"]
end
```
--------------------------------
### Web3 Class Inheritance Diagram
Source: https://deepwiki.com/web3/web3.js/2-core-architecture
Mermaid class diagram showing the inheritance hierarchy of the Web3 class and related modules. It illustrates that Web3, Web3Eth, Web3Net, and Web3Personal all inherit from Web3Context, and that CustomPlugin inherits from Web3PluginBase. The diagram also lists key members of Web3Context, Web3, and Web3PluginBase.
```mermaid
classDiagram
Web3Context <|-- Web3
Web3Context <|-- Web3Eth
Web3Context <|-- Web3Net
Web3Context <|-- Web3Personal
Web3PluginBase <|-- CustomPlugin
class Web3Context {
+requestManager: Web3RequestManager
+config: Web3Config
+providers: Object
+use(module): T
+registerPlugin(plugin)
+setProvider(provider)
+getContextObject()
}
class Web3 {
+utils: Utils
+eth: Web3EthInterface
+version: string
+modules: Object
+Contract: ContractBuilder
}
class Web3PluginBase {
+pluginNamespace: string
+linkToContext(context)
}
```
--------------------------------
### Web3 class type definition with generics
Source: https://deepwiki.com/web3/web3.js/2.1-main-web3-class
Defines the Web3 class with a generic parameter for custom registered subscriptions, extending Web3Context with the standard Ethereum subscription types.
```typescript
class Web3<
CustomRegisteredSubscription extends {
[key: string]: Web3SubscriptionConstructor;
} = RegisteredSubscription,
> extends Web3Context
```
--------------------------------
### TypeDoc plugin configuration in docusaurus.config.js
Source: https://deepwiki.com/web3/web3.js/5.4-documentation-system
Configuration for docusaurus-plugin-typedoc-api. Specifies project root, packages, and TypeDoc options including plugins for monorepo link types, extras, and MDN links. Used to generate API docs from TypeScript source.
```javascript
[
'docusaurus-plugin-typedoc-api',
{
projectRoot: join(__dirname, '..'),
packages: packages.map(p => `packages/${p}`),
minimal: false,
debug: true,
changelogs: true,
readmes: false,
tsconfigName: 'docs/tsconfig.docs.json',
typedocOptions: {
plugin: [
'typedoc-monorepo-link-types',
'typedoc-plugin-extras',
'typedoc-plugin-mdn-links',
],
},
},
]
```
--------------------------------
### Jest configuration for web3.js tests
Source: https://deepwiki.com/web3/web3.js/5.2-testing-infrastructure
Jest configuration for web3.js unit tests. Sets test file matching, TypeScript transformation via ts-jest, JSON coverage output, mock/reset isolation, and a 600000 ms timeout for long-running tests.
```javascript
// Key Jest configuration (simplified from templates/jest.config.js.tmpl)
module.exports = {
// Match test files using pattern
testMatch: ['/test/**/?(*.)+(spec|test).+(ts|tsx|js)'],
// TypeScript configuration
transform: {
'^.+\.(ts|tsx)$': ['ts-jest', { tsconfig: './test/tsconfig.json' }]
},
// Coverage reporting
coverageReporters: ['json'],
coverageDirectory: '.coverage',
// Test isolation
restoreMocks: true,
resetModules: true,
// Long-running tests setting
testTimeout: 600000,
};
```
--------------------------------
### TypeScript module declaration for plugin
Source: https://deepwiki.com/web3/web3.js/5.3-plugin-system
Declares the 'web3' module to add the custom plugin type to the Web3 interface for TypeScript type safety.
```typescript
declare module 'web3' {
interface Web3 {
myPlugin: MyCustomPlugin;
}
}
```