Skip to content

Commit

Permalink
stash
Browse files Browse the repository at this point in the history
  • Loading branch information
MajorLift committed Oct 4, 2023
1 parent d7a775e commit 6b99e07
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 49 deletions.
12 changes: 8 additions & 4 deletions packages/network-controller/src/NetworkController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ import {
NetworkType,
isSafeChainId,
} from '@metamask/controller-utils';
import EthQuery from '@metamask/eth-query';
import EthQuery, { type Provider } from '@metamask/eth-query';
import { createEventEmitterProxy } from '@metamask/swappable-obj-proxy';
import type { SwappableProxy } from '@metamask/swappable-obj-proxy';
import type {
EventEmitterLike,

Check failure on line 14 in packages/network-controller/src/NetworkController.ts

View workflow job for this annotation

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

Module '"@metamask/swappable-obj-proxy"' has no exported member 'EventEmitterLike'.
SwappableProxy,
} from '@metamask/swappable-obj-proxy';
import type { Hex } from '@metamask/utils';
import {
assertIsStrictHexString,
Expand All @@ -32,7 +35,6 @@ import { projectLogger, createModuleLogger } from './logger';
import { NetworkClientType } from './types';
import type {
BlockTracker,
Provider,
CustomNetworkClientConfiguration,
InfuraNetworkClientConfiguration,
NetworkClientConfiguration,
Expand Down Expand Up @@ -357,7 +359,9 @@ export type BlockTrackerProxy = SwappableProxy<
* selected network can change without consumers needing to refresh the object
* reference to that network.)
*/
export type ProviderProxy = SwappableProxy<ProxyWithAccessibleTarget<Provider>>;
export type ProviderProxy =
| SwappableProxy<ProxyWithAccessibleTarget<Provider>>
| SwappableProxy<EventEmitterLike>;

export type NetworkControllerStateChangeEvent = {
type: `NetworkController:stateChange`;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import type { NetworkClient } from './create-network-client';
import { createNetworkClient } from './create-network-client';
import type {
BlockTracker,
NetworkClientConfiguration,
Provider,
} from './types';
ProviderSendAsyncCallback,
SendAsyncPayload,
} from '@metamask/eth-query';

import type { NetworkClient } from './create-network-client';
import { createNetworkClient } from './create-network-client';
import type { BlockTracker, NetworkClientConfiguration } from './types';

/**
* The name of the method on both the provider and block tracker proxy which can
Expand Down Expand Up @@ -90,10 +92,13 @@ export function createAutoManagedNetworkClient<
// Ensure that the method on the provider is called with `this` as
// the target, *not* the proxy (which happens by default) —
// this allows private properties to be accessed
return function (this: unknown, ...args: any[]) {
// @ts-expect-error We don't care that `this` may not be compatible
// with the signature of the method being called, as technically
// it can be anything.
return function (
this: unknown,
...args: [
payload: SendAsyncPayload<unknown>,
callback: ProviderSendAsyncCallback<unknown>,
]
) {
return value.apply(this === receiver ? provider : this, args);
};
}
Expand Down
9 changes: 3 additions & 6 deletions packages/network-controller/src/create-network-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ import {
createFetchMiddleware,
createRetryOnEmptyMiddleware,
} from '@metamask/eth-json-rpc-middleware';
import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import {
type SafeEventEmitterProvider,
providerFromEngine,
providerFromMiddleware,
} from '@metamask/eth-json-rpc-provider';
import type { Provider } from '@metamask/eth-query';
import type { Hex } from '@metamask/utils';
import { PollingBlockTracker } from 'eth-block-tracker';
import {
Expand All @@ -25,11 +26,7 @@ import {
} from 'json-rpc-engine';
import type { JsonRpcMiddleware } from 'json-rpc-engine';

import type {
BlockTracker,
NetworkClientConfiguration,
Provider,
} from './types';
import type { BlockTracker, NetworkClientConfiguration } from './types';
import { NetworkClientType } from './types';

const SECOND = 1000;
Expand Down
8 changes: 5 additions & 3 deletions packages/network-controller/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
export * from './NetworkController';
export * from './constants';
export type { BlockTracker, Provider } from './types';
export type { NetworkClientConfiguration } from './types';
export { NetworkClientType } from './types';
export type {
BlockTracker,
NetworkClientConfiguration,
NetworkClientType,
} from './types';
3 changes: 0 additions & 3 deletions packages/network-controller/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import type { InfuraNetworkType } from '@metamask/controller-utils';
import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import type { Hex } from '@metamask/utils';
import type { PollingBlockTracker } from 'eth-block-tracker';

export type Provider = SafeEventEmitterProvider;

export type BlockTracker = PollingBlockTracker;

/**
Expand Down
37 changes: 21 additions & 16 deletions packages/network-controller/tests/NetworkController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
NetworkType,
toHex,
} from '@metamask/controller-utils';
import type { Provider } from '@metamask/eth-query';
import assert from 'assert';
import { ethErrors } from 'eth-rpc-errors';
import type { Patch } from 'immer';
Expand All @@ -27,10 +28,8 @@ import type {
ProviderConfig,
} from '../src/NetworkController';
import { NetworkController } from '../src/NetworkController';
import type { Provider } from '../src/types';
import { NetworkClientType } from '../src/types';
import type { FakeProviderStub } from './fake-provider';
import { FakeProvider } from './fake-provider';
import { FakeProvider, type FakeProviderStub } from './fake-provider';

jest.mock('../src/create-network-client');

Expand Down Expand Up @@ -978,9 +977,10 @@ describe('NetworkController', () => {
provider,
);
const response1 = await promisifiedSendAsync1({
id: '1',
id: 1,
jsonrpc: '2.0',
method: 'test',
params: [],
});
expect(response1.result).toBe('test response 1');

Expand All @@ -989,9 +989,10 @@ describe('NetworkController', () => {
provider,
);
const response2 = await promisifiedSendAsync2({
id: '2',
id: 2,
jsonrpc: '2.0',
method: 'test',
params: [],
});
expect(response2.result).toBe('test response 2');
},
Expand Down Expand Up @@ -1072,9 +1073,10 @@ describe('NetworkController', () => {
provider,
);
const response1 = await promisifiedSendAsync1({
id: '1',
id: 1,
jsonrpc: '2.0',
method: 'test',
params: [],
});
expect(response1.result).toBe('test response 1');

Expand All @@ -1083,9 +1085,10 @@ describe('NetworkController', () => {
provider,
);
const response2 = await promisifiedSendAsync2({
id: '2',
id: 2,
jsonrpc: '2.0',
method: 'test',
params: [],
});
expect(response2.result).toBe('test response 2');
},
Expand Down Expand Up @@ -3134,7 +3137,7 @@ describe('NetworkController', () => {
},
},
async ({ controller, messenger }) => {
setFakeProvider(controller, {
await setFakeProvider(controller, {
stubLookupNetworkWhileSetting: true,
});
const promiseForNoStateChanges = waitForStateChanges({
Expand Down Expand Up @@ -4871,10 +4874,10 @@ describe('NetworkController', () => {
// We only care about the first state change, because it
// happens before networkDidChange
count: 1,
operation: () => {
operation: async () => {
// Intentionally not awaited because we want to check state
// while this operation is in-progress
controller.rollbackToPreviousProvider();
await controller.rollbackToPreviousProvider();
},
beforeResolving: () => {
expect(
Expand Down Expand Up @@ -4948,9 +4951,10 @@ describe('NetworkController', () => {
provider,
);
const response = await promisifiedSendAsync({
id: '1',
id: 1,
jsonrpc: '2.0',
method: 'test',
params: [],
});
expect(response.result).toBe('test response');
},
Expand Down Expand Up @@ -5431,10 +5435,10 @@ describe('NetworkController', () => {
// We only care about the first state change, because it
// happens before networkDidChange
count: 1,
operation: () => {
operation: async () => {
// Intentionally not awaited because we want to check state
// while this operation is in-progress
controller.rollbackToPreviousProvider();
await controller.rollbackToPreviousProvider();
},
beforeResolving: () => {
expect(
Expand Down Expand Up @@ -5502,9 +5506,10 @@ describe('NetworkController', () => {
provider,
);
const response = await promisifiedSendAsync({
id: '1',
id: 1,
jsonrpc: '2.0',
method: 'test',
params: [],
});
expect(response.result).toBe('test response');
},
Expand Down Expand Up @@ -7092,14 +7097,14 @@ async function waitForPublishedEvents<E extends NetworkControllerEvents>({
// the signature of `subscribe` and the way that we're using it. Try
// changing `any` to either `((...args: E['payload']) => void)` or
// `ExtractEventHandler<E, E['type']>` to see the issue.
const eventListener: any = (...payload: E['payload']) => {
const eventListener: any = async (...payload: E['payload']) => {
allEventPayloads.push(payload);

if (isEventPayloadInteresting(payload)) {
interestingEventPayloads.push(payload);
if (interestingEventPayloads.length === expectedNumberOfEvents) {
stopTimer();
end();
await end();
} else {
resetTimer();
}
Expand Down
29 changes: 21 additions & 8 deletions packages/network-controller/tests/fake-provider.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider/dist/safe-event-emitter-provider';
import { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
import type { ProviderSendAsyncResponse } from '@metamask/eth-query';
import type { JsonRpcRequest, JsonRpcResponse } from 'json-rpc-engine';
import { JsonRpcEngine } from 'json-rpc-engine';
import { inspect, isDeepStrictEqual } from 'util';
Expand Down Expand Up @@ -105,21 +106,30 @@ export class FakeProvider extends SafeEventEmitterProvider {

send = (
payload: JsonRpcRequest<any>,
callback: (error: unknown, response?: JsonRpcResponse<any>) => void,
callback: (
error: unknown,
response?: JsonRpcResponse<unknown> | ProviderSendAsyncResponse<unknown>,
) => void,
) => {
return this.#handleSend(payload, callback);
};

sendAsync = (
payload: JsonRpcRequest<any>,
callback: (error: unknown, response?: JsonRpcResponse<any>) => void,
payload: JsonRpcRequest<unknown>,
callback: (
error: unknown,
response: JsonRpcResponse<unknown> | ProviderSendAsyncResponse<unknown>,
) => void,
) => {
return this.#handleSend(payload, callback);
};

#handleSend(
payload: JsonRpcRequest<any>,
callback: (error: unknown, response?: JsonRpcResponse<any>) => void,
payload: JsonRpcRequest<unknown>,
callback: (
error: unknown,
response: JsonRpcResponse<unknown> | ProviderSendAsyncResponse<unknown>,
) => void,
) {
if (Array.isArray(payload)) {
throw new Error("Arrays aren't supported");
Expand Down Expand Up @@ -173,7 +183,10 @@ export class FakeProvider extends SafeEventEmitterProvider {

async #handleRequest(
stub: FakeProviderStub,
callback: (error: unknown, response?: JsonRpcResponse<any>) => void,
callback: (
error: unknown,
response: JsonRpcResponse<unknown> | ProviderSendAsyncResponse<unknown>,
) => void,
) {
if (stub.beforeCompleting) {
await stub.beforeCompleting();
Expand All @@ -199,7 +212,7 @@ export class FakeProvider extends SafeEventEmitterProvider {
});
}
} else if ('error' in stub) {
return callback(stub.error);
return callback(stub.error, { result: undefined });
}

return undefined;
Expand Down

0 comments on commit 6b99e07

Please sign in to comment.