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

deps: Bump and align json-rpc packages #245

Merged
merged 8 commits into from
Sep 25, 2023
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
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ module.exports = {
files: ['*.ts'],
extends: ['@metamask/eslint-config-typescript'],
rules: {
'@typescript-eslint/prefer-nullish-coalescing': 'off',
// TODO: resolve warnings and remove to make into errors
'@typescript-eslint/consistent-type-definitions': 'off',
'@typescript-eslint/naming-convention': 'off',
Expand Down
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@
"test:watch": "jest --watch"
},
"dependencies": {
"@metamask/eth-json-rpc-provider": "^1.0.0",
"@metamask/eth-json-rpc-provider": "^2.1.0",
"@metamask/eth-sig-util": "^7.0.0",
"@metamask/json-rpc-engine": "^7.1.1",
"@metamask/rpc-errors": "^6.0.0",
"@metamask/utils": "^8.1.0",
"clone": "^2.1.1",
"eth-block-tracker": "^7.0.1",
"eth-rpc-errors": "^4.0.3",
"json-rpc-engine": "^6.1.0",
"eth-block-tracker": "^8.0.0",
"pify": "^3.0.0",
"safe-stable-stringify": "^2.3.2"
},
Expand Down
2 changes: 1 addition & 1 deletion src/block-cache.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { providerFromEngine } from '@metamask/eth-json-rpc-provider';
import { JsonRpcEngine } from '@metamask/json-rpc-engine';
import { PollingBlockTracker } from 'eth-block-tracker';
import { JsonRpcEngine } from 'json-rpc-engine';
import pify from 'pify';

import { createBlockCacheMiddleware } from '.';
Expand Down
19 changes: 11 additions & 8 deletions src/block-cache.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';
import type { PollingBlockTracker } from 'eth-block-tracker';
import type { JsonRpcRequest } from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';

import { projectLogger, createModuleLogger } from './logging-utils';
import type {
Expand Down Expand Up @@ -32,7 +32,7 @@
//

class BlockCacheStrategy {
private cache: Cache;

Check warning on line 35 in src/block-cache.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (16.x)

Use a hash name instead

Check warning on line 35 in src/block-cache.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (18.x)

Use a hash name instead

Check warning on line 35 in src/block-cache.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (20.x)

Use a hash name instead

constructor() {
this.cache = {};
Expand All @@ -51,7 +51,7 @@
}

async get(
request: JsonRpcRequest<unknown>,
request: JsonRpcRequest,
requestedBlockNumber: string,
): Promise<Block | undefined> {
// lookup block cache
Expand All @@ -62,7 +62,7 @@
}

async set(
request: JsonRpcRequest<unknown>,
request: JsonRpcRequest,
requestedBlockNumber: string,
result: Block,
): Promise<void> {
Expand All @@ -81,7 +81,7 @@
blockCache[identifier] = result;
}

canCacheRequest(request: JsonRpcRequest<unknown>): boolean {
canCacheRequest(request: JsonRpcRequest): boolean {
// check request method
if (!canCache(request.method)) {
return false;
Expand All @@ -96,7 +96,7 @@
return true;
}

canCacheResult(request: JsonRpcRequest<unknown>, result: Block): boolean {
canCacheResult(request: JsonRpcRequest, result: Block): boolean {
// never cache empty values (e.g. undefined)
if (emptyValues.includes(result as any)) {
return false;
Expand All @@ -110,7 +110,7 @@
)
) {
if (
!result ||

Check warning on line 113 in src/block-cache.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (16.x)

Prefer using an optional chain expression instead, as it's more concise and easier to read

Check warning on line 113 in src/block-cache.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (18.x)

Prefer using an optional chain expression instead, as it's more concise and easier to read

Check warning on line 113 in src/block-cache.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (20.x)

Prefer using an optional chain expression instead, as it's more concise and easier to read
!result.blockHash ||
result.blockHash ===
'0x0000000000000000000000000000000000000000000000000000000000000000'
Expand All @@ -135,7 +135,10 @@

export function createBlockCacheMiddleware({
blockTracker,
}: BlockCacheMiddlewareOptions = {}): JsonRpcCacheMiddleware<unknown, unknown> {
}: BlockCacheMiddlewareOptions = {}): JsonRpcCacheMiddleware<
JsonRpcParams,
Json
> {
// validate options
if (!blockTracker) {
throw new Error(
Expand All @@ -153,7 +156,7 @@
};

return createAsyncMiddleware(
async (req: JsonRpcRequestToCache<unknown>, res, next) => {
async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {
// allow cach to be skipped if so specified
if (req.skipCache) {
return next();
Expand Down
22 changes: 12 additions & 10 deletions src/block-ref-rewrite.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type { Json, JsonRpcParams } from '@metamask/utils';
import type { PollingBlockTracker } from 'eth-block-tracker';
import type { JsonRpcMiddleware } from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';

import { blockTagParamIndex } from './utils/cache';

Expand All @@ -10,7 +11,10 @@ interface BlockRefRewriteMiddlewareOptions {

export function createBlockRefRewriteMiddleware({
blockTracker,
}: BlockRefRewriteMiddlewareOptions = {}): JsonRpcMiddleware<unknown, unknown> {
}: BlockRefRewriteMiddlewareOptions = {}): JsonRpcMiddleware<
JsonRpcParams,
Json
> {
if (!blockTracker) {
throw Error(
'BlockRefRewriteMiddleware - mandatory "blockTracker" option is missing.',
Expand All @@ -24,13 +28,11 @@ export function createBlockRefRewriteMiddleware({
return next();
}
// skip if not "latest"
let blockRef: string | undefined = Array.isArray(req.params)
? req.params[blockRefIndex]
: undefined;
// omitted blockRef implies "latest"
if (blockRef === undefined) {
blockRef = 'latest';
}
const blockRef: string | undefined =
Array.isArray(req.params) && req.params[blockRefIndex]
? (req.params[blockRefIndex] as string)
: // omitted blockRef implies "latest"
'latest';

if (blockRef !== 'latest') {
return next();
Expand Down
4 changes: 2 additions & 2 deletions src/block-ref.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { providerFromEngine } from '@metamask/eth-json-rpc-provider';
import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { JsonRpcEngine } from '@metamask/json-rpc-engine';
import { PollingBlockTracker } from 'eth-block-tracker';
import type { JsonRpcMiddleware } from 'json-rpc-engine';
import { JsonRpcEngine } from 'json-rpc-engine';

import { createBlockRefMiddleware } from '.';
import {
Expand Down
14 changes: 8 additions & 6 deletions src/block-ref.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import clone from 'clone';
import type { PollingBlockTracker } from 'eth-block-tracker';
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type {
JsonRpcMiddleware,
Json,
JsonRpcParams,
PendingJsonRpcResponse,
} from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';
} from '@metamask/utils';
import clone from 'clone';
import type { PollingBlockTracker } from 'eth-block-tracker';
import pify from 'pify';

import { projectLogger, createModuleLogger } from './logging-utils';
Expand All @@ -22,7 +24,7 @@ const log = createModuleLogger(projectLogger, 'block-ref');
export function createBlockRefMiddleware({
provider,
blockTracker,
}: BlockRefMiddlewareOptions = {}): JsonRpcMiddleware<unknown, unknown> {
}: BlockRefMiddlewareOptions = {}): JsonRpcMiddleware<JsonRpcParams, Json> {
if (!provider) {
throw Error('BlockRefMiddleware - mandatory "provider" option is missing.');
}
Expand Down
16 changes: 9 additions & 7 deletions src/block-tracker-inspector.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { PollingBlockTracker } from 'eth-block-tracker';
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type {
JsonRpcMiddleware,
Json,
JsonRpcParams,
PendingJsonRpcResponse,
} from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';
} from '@metamask/utils';
import type { PollingBlockTracker } from 'eth-block-tracker';

import { projectLogger, createModuleLogger } from './logging-utils';

Expand Down Expand Up @@ -37,7 +39,7 @@ function hasProperty<ObjectToCheck, Property extends ValidPropertyType>(
}

function getResultBlockNumber(
response: PendingJsonRpcResponse<unknown>,
response: PendingJsonRpcResponse<Json>,
): string | undefined {
const { result } = response;
if (
Expand All @@ -58,8 +60,8 @@ function getResultBlockNumber(
export function createBlockTrackerInspectorMiddleware({
blockTracker,
}: BlockTrackerInspectorMiddlewareOptions): JsonRpcMiddleware<
unknown,
unknown
JsonRpcParams,
Json
> {
return createAsyncMiddleware(async (req, res, next) => {
if (!futureBlockRefRequests.includes(req.method)) {
Expand Down
29 changes: 15 additions & 14 deletions src/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import type { EthereumRpcError } from 'eth-rpc-errors';
import { ethErrors } from 'eth-rpc-errors';
import type { JsonRpcMiddleware, JsonRpcRequest } from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';
import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type { JsonRpcError, DataWithOptionalCause } from '@metamask/rpc-errors';
import { rpcErrors } from '@metamask/rpc-errors';
import type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';

import type { Block } from './types';
import { timeout } from './utils/timeout';
Expand All @@ -17,7 +18,7 @@
'Failed to fetch',
];

export interface PayloadWithOrigin extends JsonRpcRequest<unknown> {
export interface PayloadWithOrigin extends JsonRpcRequest {
origin?: string;
}
interface Request {
Expand All @@ -33,7 +34,7 @@
/**
* Create middleware for sending a JSON-RPC request to the given RPC URL.
*
* @param options - Options

Check warning on line 37 in src/fetch.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (16.x)

JSDoc description does not satisfy the regex pattern

Check warning on line 37 in src/fetch.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (18.x)

JSDoc description does not satisfy the regex pattern

Check warning on line 37 in src/fetch.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (20.x)

JSDoc description does not satisfy the regex pattern
* @param options.btoa - Generates a base64-encoded string from a binary string.
* @param options.fetch - The `fetch` function; expected to be equivalent to `window.fetch`.
* @param options.rpcUrl - The URL to send the request to.
Expand All @@ -53,7 +54,7 @@
fetch: typeof global.fetch;
rpcUrl: string;
originHttpHeaderKey?: string;
}): JsonRpcMiddleware<unknown, unknown> {
}): JsonRpcMiddleware<JsonRpcParams, Json> {
return createAsyncMiddleware(async (req, res, _next) => {
const { fetchUrl, fetchParams } = createFetchConfigFromReq({
btoa,
Expand Down Expand Up @@ -104,7 +105,7 @@
// check for errors
switch (fetchRes.status) {
case 405:
throw ethErrors.rpc.methodNotFound();
throw rpcErrors.methodNotFound();

case 418:
throw createRatelimitError();
Expand All @@ -121,15 +122,15 @@
function parseResponse(fetchRes: Response, body: Record<string, Block>): Block {
// check for error code
if (fetchRes.status !== 200) {
throw ethErrors.rpc.internal({
throw rpcErrors.internal({
message: `Non-200 status code: '${fetchRes.status}'`,
data: body,
});
}

// check for rpc error
if (body.error) {
throw ethErrors.rpc.internal({
throw rpcErrors.internal({
data: body.error,
});
}
Expand All @@ -140,12 +141,12 @@
/**
* Generate `fetch` configuration for sending the given request to an RPC API.
*
* @param options - Options

Check warning on line 144 in src/fetch.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (16.x)

JSDoc description does not satisfy the regex pattern

Check warning on line 144 in src/fetch.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (18.x)

JSDoc description does not satisfy the regex pattern

Check warning on line 144 in src/fetch.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (20.x)

JSDoc description does not satisfy the regex pattern
* @param options.btoa - Generates a base64-encoded string from a binary string.
* @param options.rpcUrl - The URL to send the request to.
* @param options.originHttpHeaderKey - If provider, the origin field for each JSON-RPC request
* will be attached to each outgoing fetch request under this header.
* @param options.req

Check warning on line 149 in src/fetch.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (16.x)

Missing JSDoc @param "options.req" description

Check warning on line 149 in src/fetch.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (18.x)

Missing JSDoc @param "options.req" description

Check warning on line 149 in src/fetch.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (20.x)

Missing JSDoc @param "options.req" description
* @returns The fetch middleware.
*/
export function createFetchConfigFromReq({
Expand All @@ -165,7 +166,7 @@

// prepare payload
// copy only canonical json rpc properties
const payload: JsonRpcRequest<unknown> = {
const payload: JsonRpcRequest = {
id: req.id,
jsonrpc: req.jsonrpc,
method: req.method,
Expand Down Expand Up @@ -215,12 +216,12 @@
return result;
}

function createRatelimitError(): EthereumRpcError<unknown> {
return ethErrors.rpc.internal({ message: `Request is being rate limited.` });
function createRatelimitError(): JsonRpcError<DataWithOptionalCause> {
return rpcErrors.internal({ message: `Request is being rate limited.` });
}

function createTimeoutError(): EthereumRpcError<unknown> {
function createTimeoutError(): JsonRpcError<DataWithOptionalCause> {
let msg = `Gateway timeout. The request took too long to process. `;
msg += `This can happen when querying logs over too wide a block range.`;
return ethErrors.rpc.internal({ message: msg });
return rpcErrors.internal({ message: msg });
}
2 changes: 1 addition & 1 deletion src/inflight-cache.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { JsonRpcEngine } from 'json-rpc-engine';
import { JsonRpcEngine } from '@metamask/json-rpc-engine';
import pify from 'pify';

import { createInflightCacheMiddleware } from '.';
Expand Down
34 changes: 18 additions & 16 deletions src/inflight-cache.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,30 @@
import { createAsyncMiddleware } from '@metamask/json-rpc-engine';
import type {
JsonRpcParams,
Json,
PendingJsonRpcResponse,
} from '@metamask/utils';
import clone from 'clone';
import type { PendingJsonRpcResponse } from 'json-rpc-engine';
import { createAsyncMiddleware } from 'json-rpc-engine';

import { projectLogger, createModuleLogger } from './logging-utils';
import type { JsonRpcRequestToCache, JsonRpcCacheMiddleware } from './types';
import { cacheIdentifierForRequest } from './utils/cache';

type RequestHandlers = (handledRes: PendingJsonRpcResponse<unknown>) => void;
type RequestHandlers = (handledRes: PendingJsonRpcResponse<Json>) => void;
interface InflightRequest {
[cacheId: string]: RequestHandlers[];
}

const log = createModuleLogger(projectLogger, 'inflight-cache');

export function createInflightCacheMiddleware(): JsonRpcCacheMiddleware<
unknown,
unknown
JsonRpcParams,
Json
> {
const inflightRequests: InflightRequest = {};

return createAsyncMiddleware(
async (req: JsonRpcRequestToCache<unknown>, res, next) => {
async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {
// allow cach to be skipped if so specified
if (req.skipCache) {
return next();
Expand Down Expand Up @@ -68,23 +72,21 @@ export function createInflightCacheMiddleware(): JsonRpcCacheMiddleware<
);

async function createActiveRequestHandler(
res: PendingJsonRpcResponse<unknown>,
res: PendingJsonRpcResponse<Json>,
activeRequestHandlers: RequestHandlers[],
): Promise<void> {
const { resolve, promise } = deferredPromise();
activeRequestHandlers.push(
(handledRes: PendingJsonRpcResponse<unknown>) => {
// append a copy of the result and error to the response
res.result = clone(handledRes.result);
res.error = clone(handledRes.error);
resolve();
},
);
activeRequestHandlers.push((handledRes: PendingJsonRpcResponse<Json>) => {
// append a copy of the result and error to the response
res.result = clone(handledRes.result);
res.error = clone(handledRes.error);
resolve();
});
return promise;
}

function handleActiveRequest(
res: PendingJsonRpcResponse<unknown>,
res: PendingJsonRpcResponse<Json>,
activeRequestHandlers: RequestHandlers[],
): void {
// use setTimeout so we can resolve our original request first
Expand Down
Loading
Loading