1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-22 19:26:13 +02:00
Commit Graph

160 Commits

Author SHA1 Message Date
Elliot Winkler
1304ec7af5
Convert shared/constants/metametrics to TS (#18353)
We want to convert NetworkController to TypeScript in order to be able
to compare differences in the controller between in this repo and the
core repo. To do this, however, we need to convert the dependencies of
the controller to TypeScript.

As a part of this effort, this commit converts
`shared/constants/metametrics` to TypeScript. Note that simple objects
have been largely replaced with enums. There are some cases where I even
split up some of these objects into multiple enums.

Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2023-04-03 09:31:04 -06:00
Elliot Winkler
ed3cc404f2
NetworkController: Split network into networkId and networkStatus (#17556)
The `network` store of the network controller crams two types of data
into one place. It roughly tracks whether we have enough information to
make requests to the network and whether the network is capable of
receiving requests, but it also stores the ID of the network (as
obtained via `net_version`).

Generally we shouldn't be using the network ID for anything, as it has
been completely replaced by chain ID, which all custom RPC endpoints
have been required to support for over a year now. However, as the
network ID is used in various places within the extension codebase,
removing it entirely would be a non-trivial effort. So, minimally, this
commit splits `network` into two stores: `networkId` and
`networkStatus`. But it also expands the concept of network status.

Previously, the network was in one of two states: "loading" and
"not-loading". But now it can be in one of four states:

- `available`: The network is able to receive and respond to requests.
- `unavailable`: The network is not able to receive and respond to
  requests for unknown reasons.
- `blocked`: The network is actively blocking requests based on the
  user's geolocation. (This is specific to Infura.)
- `unknown`: We don't know whether the network can receive and respond
  to requests, either because we haven't checked or we tried to check
  and were unsuccessful.

This commit also changes how the network status is determined —
specifically, how many requests are used to determine that status, when
they occur, and whether they are awaited. Previously, the network
controller would make 2 to 3 requests during the course of running
`lookupNetwork`.

* First, if it was an Infura network, it would make a request for
  `eth_blockNumber` to determine whether Infura was blocking requests or
  not, then emit an appropriate event. This operation was not awaited.
* Then, regardless of the network, it would fetch the network ID via
  `net_version`. This operation was awaited.
* Finally, regardless of the network, it would fetch the latest block
  via `eth_getBlockByNumber`, then use the result to determine whether
  the network supported EIP-1559. This operation was awaited.

Now:

* One fewer request is made, specifically `eth_blockNumber`, as we don't
  need to make an extra request to determine whether Infura is blocking
  requests; we can reuse `eth_getBlockByNumber`;
* All requests are awaited, which makes `lookupNetwork` run fully
  in-band instead of partially out-of-band; and
* Both requests for `net_version` and `eth_getBlockByNumber` are
  performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-30 16:49:12 -06:00
Elliot Winkler
9b0a6ecc90
NetworkController: Use messenger for events (#18041)
Currently, the network controller notifies consumers about events by
emitting them directly from the controller. In order to migrate the
controller to the core repo, where controllers use the BaseControllerV2
interface, events should be emitted via a messenger object.

This commit updates the network controller to use a messenger, and then
updates all of the controllers that listen for network events to use the
messenger as well.
2023-03-30 12:39:36 -06:00
Alex Donesky
349c9d4a03
Refactor network client constructor (#17652) 2023-03-22 17:20:59 -05:00
Elliot Winkler
bf851a56a4
Align network client tests with core repo (#17904)
When the network client tests in this repo were copied over to the core
repo, some alterations were made. This commit copies them back to this
repo so that the two test suites are easier to compare to each other.
Changes include:

* Extracting `testsFor*` functions (functions that bundle similar tests
  together) into separate files
* Reordering the tests defined in
  `testsForRpcMethodsThatCheckForBlockHashInResponse`
* Reordering the set of RPC methods listed in `shared-tests.js`
* Reordering the type definitions defined in `shared-tests.js` to be
  closer to the functions that use them
* Updating the tests defined in `testsForRpcMethodSupportingBlockParam`
  so that when they make requests they pass params, even if it's just an
  empty array
2023-03-20 10:50:52 -06:00
Alex Donesky
d45c4ed497
make network-controller methods overwrite rather than merge provider state (#18127)
* make network-controller methods overwrite rather than merge provider state
2023-03-16 15:53:29 -05:00
Mark Stacey
bd23a49013
Revert "Moved subscribe and filter into network controller (#16693)" (#18129)
* Revert "Moved subscribe and filter into network controller (#16693)"

This reverts commit 6f6984fa58. That
commit was an RPC middleware refactor intended to move the subscribe
and filter middleware into the network controller, to simplify the
process of sharing this middleware between clients.

This refactor resulted in `eth_subscribe` notifications being sent on
the wrong connections, causing the UI to break in some cases (the UI
`provider` connection does not support notifications). This happened
because the `setupProviderEngine` function runs per-connection,
whereas the engine setup inside the network controller is global. The
global network client cannot support notifications because it has no
way to route them; they'll need to stay in the per-connection provider
engine.

Closes #17467

* Add e2e test

An e2e test has been added that confirms subscriptions are only
broadcast to the site that registered them. This test fails on
`develop`.
2023-03-15 12:16:31 -02:30
Alex Donesky
23ca4460cf
Migrate network configurations (previously frequentRpcListDetail) from PreferencesController to NetworkController (#17421) 2023-03-09 15:00:28 -06:00
Mark Stacey
e223348fb3
Update eth-json-rpc-middleware from v9 to v10 (#17591)
This release only includes one breaking change, which is the renaming
of the package to be under the `@metamask` scope. It includes
improvements to the types that will unblock migrating our network
clients to TypeScript.
2023-02-27 13:19:08 -03:30
Elliot Winkler
b106bbf1d9
Remove extraneous methods from NetworkController (#17522)
The network controller has a variety of methods that just retrieve
controller state. These methods are not necessary because controller
state is already part of the public API of the controller and can be
accessed directly.

These methods are:

- getCurrentChainId
- getCurrentRpcUrl
- getNetworkIdentifier
- getNetworkState
- getProviderConfig
- isNetworkLoading

This is part of a larger effort to normalize the API of both network
controllers, to make them easier to merge.
2023-02-22 10:43:37 -07:00
Elliot Winkler
7e97ff2be4
Expand network controller unit test coverage (#17498)
The network controller has some tests, but they are incomplete and don't
follow our latest best practices for writing unit tests.

This commit greatly increases the amount of test coverage for the API
that we want to retain in NetworkController, in particular the seemingly
myriad paths that the code takes starting from `initializeProvider`,
`resetConnection`, `setRpcTarget`, `setProviderType`,
`rollbackToPreviousProvider`, and `lookupNetwork`.

There were a couple of pieces of logic I noted which don't seem to have
any effect due to being redundant or unreachable, but they also don't
make our lives more difficult, either, so I opted to leave them in.

Co-authored-by: Mark Stacey <markjstacey@gmail.com>
Co-authored-by: Zachary Belford <belfordz66@gmail.com>
2023-02-08 13:10:04 -07:00
Mark Stacey
d2f50d47fa
Add network client tests for methods not supported by Infura (#17347)
Any methods in the Ethereum JSON-RPC spec are now included in our
network client tests. These tests were skipped previously because they
are not supported by Infura.

Closes #16938
2023-02-02 15:44:22 -03:30
Mark Stacey
db2e461416
Add tests for retryOnEmpty middleware (#17364)
* Add tests for `retryOnEmpty` middleware

Tests have been added for the `retryOnEmpty` middleware.

This middleware is only used on the Infura network client, so the tests
that demonstrate this retry behavior are only enabled for the `infura`
provider type.

Most of the tests added were to cover cases where the retry middleware
is skipped, so they were applicable for both provider types.

Closes #17004

* Improve readability of block number tests

The test cases for passing a block number parameter have been made more
readable. Specifically, a comment has been added each time params are
built to call attention to the block parameter and what value it has,
so that it's clear whether it's larger or smaller than the current
block number.

Additionally the blocks for "less than the current block number" and
"equal to the current block number" have been combined using
`describe.each`.
2023-02-01 16:33:26 -03:30
Mark Stacey
001ea4c951
Test parameter change cache miss (#17346)
Tests have been added to ensure that our middleware will not return a
cached response to a request with unique parameters. Each parameter
supported by each method is tested independently.

Closes #17003
2023-01-26 12:27:46 -03:30
Mark Stacey
d6cf809bcc
Setup network controller mocks per-test (#17250)
The network controller unit test network mocks are now setup for each
test. This makes modifying network behavior on a per-test basis easier,
and makes it more clear which test relies upon which mocks.
2023-01-23 10:52:42 -03:30
Mark Stacey
7d77554f3b
Refactor: Construct the network controller within each test (#17199)
The network controller is now constructed within each network
controller unit test, rather than in the `beforeEach`. This allows us
to customize the constructor options in each test, which some planned
future tests will require.

The controller is constructed with a helper function that also handles
calling `destroy` after each test, even if the test failed. This helps
to prevent tests from affecting each other.

Co-authored-by: Elliot Winkler <elliot.winkler@gmail.com>
2023-01-17 19:58:16 -03:30
Mark Stacey
3c52e80713
Remove unnecessary test (#17181)
This test was testing a function that was only present in the test
module.

The function under test was mistakenly moved here when it was
discovered that it wasn't being used elsewhere, under the assumption
that it was used in these tests. I hadn't realized it was being tested
directly.
2023-01-17 19:57:41 -03:30
Mark Stacey
61d8fbb1d4
Refactor: Use network mocks for network unit tests (#17126)
The network controller unit tests now use network mocks rather than
mocking controller methods.

This makes the tests less brittle, as they will no longer break when
internal changes to the `_getLatestBlock` method are made.
2023-01-17 14:39:02 -03:30
Mark Stacey
15ee9e1556
Await initializeProvider in network controller tests (#17180)
The network controller unit tests have been updated to wait until the
network controller is fully initialized before proceeding. This ensures
that the initialization doesn't have any side-effects that affect later
tests.
2023-01-13 12:53:39 -03:30
Mark Stacey
6482848610
Fix NetworkController destroy before initialization (#17136)
The NetworkController `destroy` method has been updated to ensure that
it no longer throws if called before initialization.

This method was added recently in #17032, but we forgot to handle the
case where the controller was not initialized.
2023-01-11 15:26:33 -03:30
Mark Stacey
e8e0cf5786
Remove unecessary code from the network controller tests (#17137)
The `initializeProvider` parameters were removed recently in #16863,
but they were still being set in tests. They have now been removed.

An unused property was also being set in the tests, which has now also
been removed.
2023-01-11 15:26:18 -03:30
Mark Stacey
87ce653c86
Move MetaMask middleware out of network controller (#16863)
The "MetaMask middleware" is the set of middleware for handling methods that
we don't send to the network. This includes signing, encryption, `getAccounts`,
and methods that rely on pending transaction state.

Previously this middleware was setup as part of the network client, despite
having nothing to do with the network. They have been moved into the main RPC
pipeline established in `metamask-controller.js` instead.

This is a pure refactor, and should have no functional changes. The middleware
are still run in exactly the same order with the same arguments.
2023-01-06 13:44:50 -03:30
Zachary Belford
cd2249f193
Add tests for custom JSON-RPC network client (#16337)
Previously we had written tests for `createInfuraClient`, which creates a middleware stack designed to connect to an Infura provider. These tests exercise various RPC methods that relate to the behavior that the middleware provides (mainly around caching). 

Now we need to write the same tests but for `createJsonRpcClient`, which creates a middleware stack designed to connect to a non-Infura RPC endpoint. To do this, we had to:

- Consolidate the tests for both types of RPC client into a single test file.
- Add conditions around tests or assertions in tests to account for differences in behavior between the two sets of middleware stacks.
- Relocate code in `createJsonRpcClient` which slows down `eth_estimateGas` calls just for tests so that this behavior can be disabled in the network client tests.

Eventually, as we unify the network controllers in this repo and in the core repo, we will move these tests into the core repo.

Co-authored-by: Elliot Winkler <elliot.winkler@gmail.com>
2023-01-06 10:10:17 -07:00
Mark Stacey
8d28fbccc5
Stop block tracker after each network controller unit test (#17032)
The network controller unit tests have been updated to stop the block
tracker after each test. This was accomplished with a new `destroy`
method.
2023-01-04 17:46:22 -03:30
Zachary Belford
6f6984fa58
Moved subscribe and filter into network controller (#16693)
Our middleware for handling subscription and filter-related methods (`eth-json-rpc-filters`) currently lives in our RPC pipeline ahead of the network stack. This commit moves this middleware to the network client middleware instead. There are two reasons for this change. First, this middleware wraps RPC methods that are supported by the network. Second, it is necessary for this middleware to live with the network client so that it will aid us in unifying the NetworkController in this repo and the NetworkController in the `controllers` repo.

Co-authored-by: Elliot Winkler <elliot.winkler@gmail.com>
2022-12-20 10:28:09 -07:00
Mark Stacey
3e98758719
Rename the network controller module (#16974)
The network controller module has been renamed from `network.js` to
`network-controller.js`. All of our newer controllers have "controller"
in the module names, so this aligns better with that convention. It
also brings the test module name into alignment (it's already called
"network-controller.test.js").
2022-12-16 16:37:06 -03:30
Mark Stacey
dbe77289d3
Make initializeProvider and lookupNetwork async (#16881)
* Make `initializeProvider` and `lookupNetwork` async

These two methods were "synchronous" previously, but initiated an
asynchronous operation. They have both been made `async` to bring them
more in-line with the mobile controller API, and to make them easier
to test.

This should include zero functional changes. These methods are still
being invoked without an `await`, to preserve the same behaviour they
had previously.

This relates to https://github.com/MetaMask/controllers/issues/971

* Move 'net_version' query to private function

* Fix error made when resolving conflicts

* Refactor to improve readability
2022-12-16 13:03:22 -03:30
Elliot Winkler
dd59792392
Remove if to expose more network client tests (#16906)
This commit affects the network client tests, which were added in a
previous PR to test the behavior of `createInfuraClient`, a function
called that sets up a portion of the middleware stack in the JSON-RPC
layer.

An `if` statement appears in the tests which limits the execution of
certain tests. However, this seems to have been added for debugging
purposes and is not actually needed.

Co-authored-by: Brad Decker <bhdecker84@gmail.com>
2022-12-13 12:49:58 -07:00
Mark Stacey
69e5d6da4a
Make certain network controller methods private (#16883)
Five network controller methods have been renamed to start with an
underscore:
* `getLatestBlock`
* `setNetworkState`
* `setNetworkEIPSupport`
* `clearNetworkDetails`
* `setProviderConfig`

All of these methods were used solely within the network controller.
The leading underscore now documents these methods as being private.

A few tests required updates as well because they were stubbing out one
of these methods.

This should include zero functional changes.

This relates to https://github.com/MetaMask/controllers/issues/971
2022-12-13 15:43:54 -03:30
Mark Stacey
75177c5998
Make setProviderType synchronous (#16879)
The network controller method `setProviderType` was marked as `async`
despite doing nothing async internally. The `async` has been dropped.

This should have zero functional impact.

This relates to https://github.com/MetaMask/controllers/issues/971
2022-12-13 13:57:48 -03:30
Mark Stacey
5df6f653af
Remove unused verifyNetwork method (#16882)
The network controller method `verifyNetwork` has been deleted. It was
unused.

This relates to https://github.com/MetaMask/controllers/issues/971
2022-12-13 13:57:28 -03:30
Mark Stacey
6d64951938
Move infuraProjectId to network controller constructor (#16884)
The network controller `setInfuraProjectId` method has been deleted.
The Infura project ID is only ever set upon construction, so it is now
passed in as a constructor parameter instead.

Rather than adding this as a second parameter, the network controller
now uses an "options bag" for constructor parameters. The initial state
was the first parameter, but it's now passed in as the `state` option
instead.

These changes make the API more similar to the mobile network
controller API.

This should have zero functional changes.

This relates to https://github.com/MetaMask/controllers/issues/971

Co-authored-by: legobeat <109787230+legobeat@users.noreply.github.com>
2022-12-13 12:09:21 -03:30
Mark Stacey
048b7e4cb6
Fix shared mocks in RPC network client test (#16856)
* Fix shared mocks in RPC network client test

Some of the provider api unit tests were inadvertently sharing test
mocks. A `params` object used for mock RPC calls was being shared
between tests and between calls within individual tests. They have been
updated to generate a fresh `params` object for each mock RPC call.

* Explicitly set blockParam to undefined
2022-12-12 13:49:22 -03:30
Mark Stacey
f6f8edfd15
Update eth-json-rpc-middleware to v9.0.1 (#16096)
This update includes fixes for our `block-ref` and `retry-on-empty`
middleware.

The `block-ref` middleware resolves the block reference `latest` to a
specific block number, the latest one we are aware of. This is meant to
protect against situations where the network gives inconsistent answers
for what the latest block number is due to some nodes being out-of-sync
with each other (this was a frequent problem years ago with Infura).

It was broken in that the `latest` resolution was failing, and we were
submitting an additional redundant request to Infura for each request.

The `retry-on-empty` middleware is meant to retry certain methods
when they return an empty response. This was also meant to deal with
network synchronization issues that were more common years ago. This
middleware works by making a "child" request over and over until either
a retry limit is reached, or a non-empty response is received.

It was broken in that the final response recieved was thrown away, so
it's as though the middleware was not used. Except that it did result
in additional redundant network requests.

As a result of this update we should see that the extension is more
resilient to certain network synchronization issues. But this is
difficult to test, and these issues may not happen in production
anymore today.

We should see a reduction in requests to Infura as well. This should
be easier to test.
2022-10-10 13:16:58 -02:30
Elliot Winkler
d7a812f42f
Add remaining tests for createInfuraClient (#15717)
Add tests for the `block-tracker-inspector` middleware — which makes
sure that the block tracker never has a reference to the latest block
which is less than a block number that shows up in an RPC method's
response — and the Infura middleware — which takes care of sending the
request to Infura, and will retry the request up to 5 times if Infura
sends back a certain type of error.

Note that the `retry-on-empty` middleware is not tested because it
currently has a [bug][1] which is making it ineffective.

[1]: https://github.com/MetaMask/eth-json-rpc-middleware/issues/139
2022-09-29 10:39:35 -06:00
ryanml
0bc1eeaf37
Deprecating the Rinkeby, Ropsten, and Kovan test networks (#15989)
* Deprecating Rinkeby, setting default debug network to Goerli

* Deprecating Ropsten and Kovan

* Conflict fix

* Remove unused localization, test fixes

* Add migration for moving used deprecated testnets to custom networks

* Fix migrator test

* Add more unit tests

* Migration updates provider type to rpc if deprecated network is selected

* Migration fully and correctly updates the provider if selected network is a deprecated testnet

* Continue to show deprecation warning on each of rinkeby, ropsten and kovan

* Add rpcUrl deprecation message to loading screen

* Removing mayBeFauceting prop

Co-authored-by: Dan Miller <danjm.com@gmail.com>
2022-09-28 20:26:01 -07:00
Elliot Winkler
d91eabfd16
Add initial provider API tests for Infura client (#15556)
We are working on migrating the extension to a unified network
controller, but before we do so we want to extract some of the existing
pieces, specifically `createInfuraClient` and `createJsonRpcClient`,
which provide the majority of the behavior exhibited within the provider
API that the existing NetworkController exposes. This necessitates that
we understand and test that behavior as a whole.

With that in mind, this commit starts with the Infura-specific network
client and adds some initial functional tests for `createInfuraClient`,
specifically covering three pieces of middleware provided by
`eth-json-rpc-middleware`: `createNetworkAndChainIdMiddleware`,
`createBlockCacheMiddleware`, and `createBlockRefMiddleware`.

These tests exercise logic that originate from multiple different places
and combine in sometimes surprising ways, and as a result, understanding
the nature of the tests can be tricky. I've tried to explain the logic
(both of the implementation and the tests) via comments. Additionally,
debugging why a certain test is failing is not the most fun thing in the
world, so to aid with this, I've added some logging to the underlying
packages used when a request passes through the middleware stack.
Because some middleware change the request being made, or make new
requests altogether, this greatly helps to peel back the curtain, as
failures from Nock do not supply much meaningful information on their
own. This logging is disabled by default, but can be activated by
setting `DEBUG=metamask:*,eth-query DEBUG_COLORS=1` alongside the `jest`
command.

We use this logging by bumping `eth-block-tracker`, and
`eth-json-rpc-middleware`.
2022-09-16 10:48:33 -02:30
Mark Stacey
929a1a0d52
Update eth-json-rpc-infura (#15845)
* Update `eth-json-rpc-infura`

The package `eth-json-rpc-infura@5` has been updated to
`@metamask/eth-json-rpc-infura@7`. This update includes TypeScript
support, and it drops support for older node.js versions. The exports
have also been changed from default to named exports.

See here for a full list of changes: https://github.com/MetaMask/eth-json-rpc-infura/blob/main/CHANGELOG.md#700

* Fix LavaMoat policy issue

The `web3` package used by `@metamask/controllers` unintentionally
overwrites the `XMLHttpRequest` global, which breaks things. This was
fixed by revoking `web3`'s write access to that global using a policy
override.

Previously this policy override was applied to `web3`, but for some
unknown reason, this update caused that override to no longer apply.
2022-09-15 14:41:18 -02:30
ryanml
7b04bf8b47
Adding Sepolia as a default test network (#15787) 2022-09-14 13:26:45 -05:00
Brad Decker
c87980bbfe
migrate network constants to typescript (#15610) 2022-09-14 09:55:31 -05:00
Brad Decker
c72199a1a6
update prettier (#15360) 2022-07-31 13:26:40 -05:00
Brad Decker
652d631cda
remove exclusions for mismatched object jsdoc type casing (#15351) 2022-07-27 08:28:05 -05:00
David Walsh
95adbc245c
Set default getFetchWithTimeout default timeout value (#14218) 2022-07-19 11:13:45 -05:00
Alex Donesky
d92936475a
Fix default currency symbol for wallet_addEthereumChain + improve warnings for data that doesn't match our validation expectations (#15201)
* set more appropriate default for ticker symbol when wallet_addEthereumChain is called

* throw error to dapp when site suggests network with same chainId but different ticker symbol from already added network, instead of showing error and disabled notification to user
2022-07-18 10:59:38 -05:00
Alex Donesky
fbeae57247
Add testnet name as prefix for native currency of preloaded testnets (#14454)
* add testnet name as prefix for native currency of preloaded testnets
2022-04-21 14:09:41 -05:00
Mark Stacey
3732c5f71e
Add JSDoc ESLint rules (#12112)
ESLint rules have been added to enforce our JSDoc conventions. These
rules were introduced by updating `@metamask/eslint-config` to v9.

Some of the rules have been disabled because the effort to fix all lint
errors was too high. It might be easiest to enable these rules one
directory at a time, or one rule at a time.

Most of the changes in this PR were a result of running
`yarn lint:fix`. There were a handful of manual changes that seemed
obvious and simple to make. Anything beyond that and the rule was left
disabled.
2022-01-07 12:27:33 -03:30
Thomas Huang
c9cb2ae1a1
Jestify app/scripts/controller/network/**/*.test.js (#12985) 2021-12-10 11:25:58 -06:00
Mark Stacey
7226357422
Fix isMainnet propType error (#12951)
A propType error was showing up during e2e tests with a `testDev`
build. It was caused by `process.env.IN_TEST` being treated as a
boolean, when in fact it is either the string `'true'` or a boolean.

`IN_TEST` has been updated to always be a boolean. `loose-envify` has
no trouble injecting boolean values, so there's no reason to treat this
as a string.
2021-12-02 14:46:46 -03:30
Ikko Ashimine
568289f29e
Fix typo in network.js (#12636)
intialize -> initialize
2021-11-16 10:40:49 -03:30
Erik Marks
b3963daaab
eth-json-rpc-middleware@8.0.0 (#10738)
We're bumping from `^6` to `^8`. All imports are now named, and they have been updated. This is a breaking change, in that support for `eth_signTransaction` is added in `^8.0.0`. We do not support this method in our UI, so our middleware stack has been instrumented to reject.

In addition, there are some non-breaking behavioral changes in this version that reviewers should be aware of, see the [7.0.0 release](https://github.com/MetaMask/eth-json-rpc-middleware/releases).
2021-11-11 12:26:49 -08:00