Skip to content

Commit

Permalink
Implement a way to know which response corresponds to which request i…
Browse files Browse the repository at this point in the history
…n the middleware (#7028)

* move request middleware to _sendRequest

* lint

* change log
  • Loading branch information
avkos authored May 6, 2024
1 parent c62ef79 commit 5d2f2aa
Show file tree
Hide file tree
Showing 9 changed files with 301 additions and 218 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2448,6 +2448,10 @@ If there are any bugs, improvements, optimizations or any new feature proposal f

### Added

#### web3

- Updated type `Web3EthInterface.accounts` to includes `privateKeyToAccount`,`privateKeyToAddress`,and `privateKeyToPublicKey` (#6762)

#### web3-core

- `defaultReturnFormat` was added to the configuration options. (#6947)
Expand Down Expand Up @@ -2487,6 +2491,10 @@ If there are any bugs, improvements, optimizations or any new feature proposal f

### Changed

#### web3-core

- Interface `RequestManagerMiddleware` was changed (#7003)

#### web3-eth

- Added parameter `customTransactionReceiptSchema` into methods `emitConfirmation`, `waitForTransactionReceipt`, `watchTransactionByPolling`, `watchTransactionBySubscription`, `watchTransactionForConfirmations` (#7000)
Expand Down
6 changes: 6 additions & 0 deletions packages/web3-core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,4 +210,10 @@ Documentation:
## [Unreleased]

### Added

- `defaultReturnFormat` was added to the configuration options. (#6947)

### Changed

- Interface `RequestManagerMiddleware` was changed (#7003)

33 changes: 19 additions & 14 deletions packages/web3-core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,16 @@ You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/

import { HexString, JsonRpcResponse, Transaction, Web3APIMethod, Web3APIRequest, Web3APIReturnType } from 'web3-types';
import {
HexString,
JsonRpcPayload,
JsonRpcResponse,
Transaction,
Web3APIMethod,
Web3APIReturnType,
} from 'web3-types';

export type TransactionTypeParser = (
transaction: Transaction,
) => HexString | undefined;
export type TransactionTypeParser = (transaction: Transaction) => HexString | undefined;

export interface Method {
name: string;
Expand All @@ -32,16 +37,16 @@ export interface ExtensionObject {
}

export interface RequestManagerMiddleware<API> {
processRequest<
AnotherMethod extends Web3APIMethod<API>
>(
request: Web3APIRequest<API, AnotherMethod>,
options?: { [key: string]: unknown }): Promise<Web3APIRequest<API, AnotherMethod>>;
processRequest<ParamType = unknown[]>(
request: JsonRpcPayload<ParamType>,
options?: { [key: string]: unknown },
): Promise<JsonRpcPayload<ParamType>>;

processResponse<
AnotherMethod extends Web3APIMethod<API>,
ResponseType = Web3APIReturnType<API, AnotherMethod>>
(
response: JsonRpcResponse<ResponseType>,
options?: { [key: string]: unknown }): Promise<JsonRpcResponse<ResponseType>>;
}
ResponseType = Web3APIReturnType<API, AnotherMethod>,
>(
response: JsonRpcResponse<ResponseType>,
options?: { [key: string]: unknown },
): Promise<JsonRpcResponse<ResponseType>>;
}
34 changes: 16 additions & 18 deletions packages/web3-core/src/web3_request_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export class Web3RequestManager<
public constructor(
provider?: SupportedProviders<API> | string,
useRpcCallSpecification?: boolean,
requestManagerMiddleware?: RequestManagerMiddleware<API>
requestManagerMiddleware?: RequestManagerMiddleware<API>,
) {
super();

Expand All @@ -88,11 +88,9 @@ export class Web3RequestManager<
}
this.useRpcCallSpecification = useRpcCallSpecification;

if (!isNullish(requestManagerMiddleware))
this.middleware = requestManagerMiddleware;

if (!isNullish(requestManagerMiddleware)) this.middleware = requestManagerMiddleware;
}

/**
* Will return all available providers
*/
Expand Down Expand Up @@ -150,7 +148,7 @@ export class Web3RequestManager<
return true;
}

public setMiddleware(requestManagerMiddleware: RequestManagerMiddleware<API>){
public setMiddleware(requestManagerMiddleware: RequestManagerMiddleware<API>) {
this.middleware = requestManagerMiddleware;
}

Expand All @@ -167,16 +165,11 @@ export class Web3RequestManager<
Method extends Web3APIMethod<API>,
ResponseType = Web3APIReturnType<API, Method>,
>(request: Web3APIRequest<API, Method>): Promise<ResponseType> {

let requestObj = {...request};

if (!isNullish(this.middleware))
requestObj = await this.middleware.processRequest(requestObj);
const requestObj = { ...request };

let response = await this._sendRequest<Method, ResponseType>(requestObj);

if (!isNullish(this.middleware))
response = await this.middleware.processResponse(response);
if (!isNullish(this.middleware)) response = await this.middleware.processResponse(response);

if (jsonRpc.isResponseWithResult(response)) {
return response.result;
Expand Down Expand Up @@ -210,10 +203,15 @@ export class Web3RequestManager<
);
}

const payload = jsonRpc.isBatchRequest(request)
? jsonRpc.toBatchPayload(request)
: jsonRpc.toPayload(request);
let payload = (
jsonRpc.isBatchRequest(request)
? jsonRpc.toBatchPayload(request)
: jsonRpc.toPayload(request)
) as JsonRpcPayload;

if (!isNullish(this.middleware)) {
payload = (await this.middleware.processRequest(payload));
}
if (isWeb3Provider(provider)) {
let response;

Expand Down Expand Up @@ -447,10 +445,10 @@ export class Web3RequestManager<
} else if ((response as unknown) instanceof Error) {
error = response as unknown as JsonRpcError;
}

// This message means that there was an error while executing the code of the smart contract
// However, more processing will happen at a higher level to decode the error data,
// according to the Error ABI, if it was available as of EIP-838.
// according to the Error ABI, if it was available as of EIP-838.
if (error?.message.includes('revert')) throw new ContractExecutionError(error);

return false;
Expand Down
30 changes: 23 additions & 7 deletions packages/web3-core/test/unit/web3_context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
// eslint-disable-next-line max-classes-per-file
import { ExistingPluginNamespaceError } from 'web3-errors';
import HttpProvider from 'web3-providers-http';
import { EthExecutionAPI, JsonRpcResponse, Web3APIMethod, Web3APIRequest, Web3APIReturnType } from 'web3-types';
import {
EthExecutionAPI,
JsonRpcPayload,
JsonRpcResponse,
Web3APIMethod,
Web3APIReturnType,
} from 'web3-types';
import { Web3Context, Web3PluginBase } from '../../src/web3_context';
import { Web3RequestManager } from '../../src/web3_request_manager';
import { RequestManagerMiddleware } from '../../src/types';
Expand Down Expand Up @@ -69,11 +75,19 @@ describe('Web3Context', () => {
it('should set middleware for the request manager', () => {
const context = new Web3Context('http://test.com');

const middleware: RequestManagerMiddleware<EthExecutionAPI>
= {
processRequest: jest.fn(async <Method extends Web3APIMethod<EthExecutionAPI>>(request: Web3APIRequest<EthExecutionAPI, Method>) => request),
processResponse: jest.fn(async <Method extends Web3APIMethod<EthExecutionAPI>, ResponseType = Web3APIReturnType<EthExecutionAPI, Method>>(response: JsonRpcResponse<ResponseType>) => response),
};
const middleware: RequestManagerMiddleware<EthExecutionAPI> = {
processRequest: jest.fn(
async <Param = unknown[]>(request: JsonRpcPayload<Param>) => request,
),
processResponse: jest.fn(
async <
Method extends Web3APIMethod<EthExecutionAPI>,
ResponseType = Web3APIReturnType<EthExecutionAPI, Method>,
>(
response: JsonRpcResponse<ResponseType>,
) => response,
),
};

context.setRequestManagerMiddleware(middleware);
expect(context.requestManager.middleware).toEqual(middleware);
Expand All @@ -95,7 +109,9 @@ describe('Web3Context', () => {
).find(s => s.description === 'shapeMode');
if (symbolForShapeMode) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
delete (context.getContextObject().requestManager as any)._emitter[symbolForShapeMode];
delete (context.getContextObject().requestManager as any)._emitter[
symbolForShapeMode
];
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(context.getContextObject().requestManager as any)._emitter = {
Expand Down
Loading

1 comment on commit 5d2f2aa

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Benchmark

Benchmark suite Current: 5d2f2aa Previous: c62ef79 Ratio
processingTx 8767 ops/sec (±5.12%) 9041 ops/sec (±3.62%) 1.03
processingContractDeploy 40540 ops/sec (±7.05%) 37458 ops/sec (±6.70%) 0.92
processingContractMethodSend 20282 ops/sec (±6.31%) 18860 ops/sec (±6.48%) 0.93
processingContractMethodCall 41478 ops/sec (±5.04%) 37636 ops/sec (±6.11%) 0.91
abiEncode 46501 ops/sec (±6.65%) 43512 ops/sec (±7.01%) 0.94
abiDecode 31621 ops/sec (±7.28%) 29213 ops/sec (±8.82%) 0.92
sign 1640 ops/sec (±0.75%) 1556 ops/sec (±3.28%) 0.95
verify 379 ops/sec (±2.77%) 375 ops/sec (±0.46%) 0.99

This comment was automatically generated by workflow using github-action-benchmark.

Please sign in to comment.