Skip to content

Commit

Permalink
Merge branch '4.x' into junaid/4xtestsfix
Browse files Browse the repository at this point in the history
  • Loading branch information
jdevcs committed Aug 2, 2024
2 parents 52e6850 + 61e9e06 commit 32e0431
Show file tree
Hide file tree
Showing 39 changed files with 4,377 additions and 2,265 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/black_box_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ jobs:
needs: build
runs-on: ubuntu-latest
env:
INFURA_HTTP: ${{ secrets.INFURA_HTTP }}
INFURA_WSS: ${{ secrets.INFURA_WSS }}
INFURA_GOERLI_WS: ${{ secrets.INFURA_GOERLI_WS }}
INFURA_MAINNET_HTTP: ${{ secrets.INFURA_MAINNET_HTTP }}
INFURA_MAINNET_WS: ${{ secrets.INFURA_MAINNET_WS }}
INFURA_SEPOLIA_WS: ${{ secrets.INFURA_SEPOLIA_WS }}
MODE: ${{ matrix.mode }}
strategy:
fail-fast: false
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ jobs:
needs: build
runs-on: ubuntu-latest
env:
INFURA_GOERLI_HTTP: ${{ secrets.INFURA_GOERLI_HTTP }}
INFURA_GOERLI_WS: ${{ secrets.INFURA_GOERLI_WS }}
INFURA_SEPOLIA_HTTP: ${{ secrets.INFURA_SEPOLIA_HTTP }}
INFURA_SEPOLIA_WS: ${{ secrets.INFURA_SEPOLIA_WS }}
strategy:
fail-fast: false
matrix:
Expand Down
1 change: 0 additions & 1 deletion .github/workflows/e2e_network_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ on:
- release/**
tags:
- v4.*

jobs:
build:
name: Build Packages
Expand Down
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2631,4 +2631,21 @@ If there are any bugs, improvements, optimizations or any new feature proposal f

- `web3.eth.Contract` will get transaction middleware and use it, if `web3.eth` has transaction middleware. (#7138)

## [4.11.1]

### Fixed

#### web3-errors

- Fixed the undefined data in `Eip838ExecutionError` constructor (#6905)

#### web3-eth

- Adds transaction property to be an empty list rather than undefined when no transactions are included in the block (#7151)
- Change method `getTransactionReceipt` to not be casted as `TransactionReceipt` to give proper return type (#7159)

#### web3

- Remove redundant constructor of contractBuilder (#7150)

## [Unreleased]
83 changes: 83 additions & 0 deletions docs/docs/glossary/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,86 @@ contract Test {
}
]
```

## Proxy

A `proxy` in Web3.js serves as an intermediary between your application and an Ethereum node, **facilitating communication** by **forwarding requests and responses**. Configuring a proxy can help overcome network restrictions, enhance security, and improve load balancing. You can set up a proxy using either HttpProvider or WebSocketProvider in Web3.js.

## HttpProvider

[HttpProvider](https://docs.web3js.org/guides/web3_providers_guide/#http-provider) in Web3.js connects an application to an Ethereum node over HTTP. It allows for sending transactions, reading blockchain data, and interacting with smart contracts. You create a Web3 instance with the node’s URL to establish the connection. It’s essential for DApps needing blockchain interaction but can block the event loop, so alternatives like `WebSocketProvider` might be used for better performance when real-time communication is needed.

```typescript
import { Web3 } from 'web3';
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
```

## WebSocketProvider
[WebSocketProvider](https://docs.web3js.org/guides/web3_providers_guide/#websocket-provider) in Web3.js connects your application to an Ethereum node via WebSocket, enabling real-time and asynchronous communication. This provider is ideal for applications needing real-time updates, such as new blocks or smart contract events. It offers better performance for high-throughput applications compared to `HttpProvider`. Ensure secure connections with `wss://` for exposed endpoints. Handle reconnections gracefully for reliable operation.

```javascript title='WebSocketProvider example'
import { Web3 } from 'web3';
const web3 = new Web3(new Web3.providers.WebsocketProvider('ws://localhost:8546'));
```

## Events

The `Events` class in Web3.js is a crucial part of the library that enables developers to interact with and listen for events emitted by smart contracts on the Ethereum network. Events in **smart contracts** are similar to `logs` or `messages` that the **contract emits to notify** external applications about specific actions or state changes. Web3.js provides a comprehensive set of tools to handle these events, making it possible to build responsive and interactive decentralized applications (dApps).

#### Example

```solidity title='Event in solidity'
contract MyContract {
event Transfer(address indexed from, address indexed to, uint value);
function transfer(address recipient, uint amount) public {
// ... transfer logic ...
emit Transfer(msg.sender, recipient, amount);
}
}
```

```javascript title='Event in web3.js'
import { Web3 } from 'web3';
const MyContract = require('./MyContract.json'); // Assuming ABI is loaded

const web3 = new Web3('wss://mainnet.infura.io/v3/YOUR_INFURA_ID'); // Replace with your provider URL
const contractAddress = '0x...'; // Replace with your contract address

const myContract = new web3.eth.Contract(MyContract.abi, contractAddress);

const transferEvent = myContract.events.Transfer(); // Access the Transfer event

transferEvent.on('data', (event) => {
console.log('Transfer Event:', event);
// Process the event data (from, to, value)
});
```

## Event logs

`Logs` in Web3.js are a part of **Ethereum transactions** that contain **information about events triggered** within smart contracts. They provide a way to record and retrieve significant occurrences within the blockchain. `Event logs` are particularly useful for tracking changes, and debugging.

#### Example

```typescript
import { Web3 } from 'web3';
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

const options = {
fromBlock: 0,
toBlock: 'latest',
address: '0xYourContractAddress',
topics: [
web3.utils.sha3('Transfer(address,address,uint256)')
]
};

web3.eth.getPastLogs(options)
.then((logs) => {
console.log(logs);
})
.catch((error) => {
console.error('Error retrieving logs:', error);
});
`
2 changes: 1 addition & 1 deletion docs/docs/guides/web3_eth/methods.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ The [sendTransaction](/api/web3-eth/function/sendTransaction) method is used to
:::important
Please be cautious when sending transactions, especially when dealing with smart contracts, as they may execute specific functions that can have irreversible effects. Always ensure that the details in your transaction object are accurate and intended.

[Here](guides/wallet/transactions) you can find more examples how to send transaction.
[Here](/guides/wallet/transactions) you can find more examples how to send transaction.
:::

## sign
Expand Down
67 changes: 67 additions & 0 deletions docs/docs/guides/web3_plugin_guide/plugin_authors.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,73 @@ public link(parentContext: Web3Context) {
}
```

## Plugin Middleware

Middleware allows plugins to intercept network interactions and inject custom logic. There are two types of plugin middleware: [request middleware](#request-middleware) and [transaction middleware](#transaction-middleware). In both cases, the middleware is implemented as a new class and registered with the plugin in the plugin's `link` method. Keep reading to learn how to add middleware to a plugin.

### Request Middleware

Request middleware allows plugins to modify RPC requests before they are sent to the network and modify RPC responses before they are returned to Web3.js for further internal processing. Request middleware must implement the [`RequestManagerMiddleware`](/api/web3-core/interface/RequestManagerMiddleware) interface, which specifies two functions: [`processRequest`](/api/web3-core/interface/RequestManagerMiddleware#processRequest) and [`processResponse`](/api/web3-core/interface/RequestManagerMiddleware#processResponse). Here is a simple example of request middleware that prints RPC requests and responses to the console:

```ts
export class RequestMiddleware<API> implements RequestManagerMiddleware<API> {
public async processRequest<ParamType = unknown[]>(
request: JsonRpcPayload<ParamType>
): Promise<JsonRpcPayload<ParamType>> {
const reqObj = { ...request } as JsonRpcPayload;
console.log("Request:", reqObj);
return Promise.resolve(reqObj as JsonRpcPayload<ParamType>);
}

public async processResponse<
Method extends Web3APIMethod<API>,
ResponseType = Web3APIReturnType<API, Method>
>(
response: JsonRpcResponse<ResponseType>
): Promise<JsonRpcResponse<ResponseType>> {
const resObj = { ...response };
console.log("Response:", resObj);
return Promise.resolve(resObj);
}
}
```

To add request middleware to a plugin, use the [`Web3RequestManager.setMiddleware`](/api/web3-core/class/Web3RequestManager#setMiddleware) method in the plugin's `link` method as demonstrated below:

```ts
public link(parentContext: Web3Context): void {
parentContext.requestManager.setMiddleware(new RequestMiddleware());
super.link(parentContext);
}
```

### Transaction Middleware

Transaction middleware allows plugins to modify transaction data before it is sent to the network. Transaction middleware must implement the [`TransactionMiddleware`](/api/web3-eth/interface/TransactionMiddleware) interface, which specifies one function: [`processTransaction`](/api/web3-eth/interface/TransactionMiddleware#processTransaction). Here is a simple example of transaction middleware that prints transaction data to the console:

```ts
export class TxnMiddleware implements TransactionMiddleware {
public async processTransaction(
transaction: TransactionMiddlewareData
): Promise<TransactionMiddlewareData> {
const txObj = { ...transaction };
console.log("Transaction data:", txObj);
return Promise.resolve(txObj);
}
}
```

To add transaction middleware to a plugin, use the [`Web3Eth.setTransactionMiddleware`](/api/web3-eth/class/Web3Eth#setTransactionMiddleware) method in the plugin's `link` method as demonstrated below:

```ts
public link(parentContext: Web3Context): void {
(parentContext as any).Web3Eth.setTransactionMiddleware(
new TxnMiddleware()
);
super.link(parentContext);
}
```

## Setting Up Module Augmentation

In order to provide type safety and IntelliSense for your plugin when it's registered by the user, you must [augment](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation) the `Web3Context` module. In simpler terms, you will be making TypeScript aware that you are modifying the interface of the class `Web3Context`, and any class that extends it, to include the interface of your plugin (i.e. your plugin's added methods, properties, etc.). As a result, your plugin object will be accessible within a namespace of your choice, which will be available within any `Web3Context` object.
Expand Down
1 change: 1 addition & 0 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"typecheck": "tsc"
},
"dependencies": {
"@cookbookdev/docsbot": "^4.21.1",
"@docusaurus/core": "^3.0.1",
"@docusaurus/preset-classic": "^3.0.1",
"@docusaurus/theme-live-codeblock": "^3.0.1",
Expand Down
17 changes: 17 additions & 0 deletions docs/src/theme/SearchBar/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React from 'react';
import SearchBar from '@theme-original/SearchBar';
import AskCookbook from '@cookbookdev/docsbot/react';

// This is a public key, so it's safe to hardcode it.
// To get a new one or request access to the internal portal (If you work for the Web3JS), contact the cookbook.dev team at [email protected].
const ASK_COOKBOOK_PUBLIC_KEY =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI2NjdjNzc3YzNmOGY3Mzk2MGYzZGNiOGYiLCJpYXQiOjE3MTk0MzMwODQsImV4cCI6MjAzNTAwOTA4NH0.OXWVNJMxMuEGG1oWetW_a9005r8hmQ6RbF19wbrpTlk';

export default function SearchBarWrapper(props) {
return (
<>
<SearchBar {...props} />
<AskCookbook apiKey={ASK_COOKBOOK_PUBLIC_KEY} />
</>
);
}
Loading

0 comments on commit 32e0431

Please sign in to comment.