Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement a way to know which response corresponds to which request in the middleware #7028

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Copy link
Contributor

Choose a reason for hiding this comment

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

Sorry, is this the correct change for this MR?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It was chacngelog sync fix


#### 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
Loading