1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 09:52:26 +01:00

Make certain network controller methods private ()

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
This commit is contained in:
Mark Stacey 2022-12-13 15:43:54 -03:30 committed by GitHub
parent 06d87fb98b
commit 69e5d6da4a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 74 additions and 82 deletions

View File

@ -75,7 +75,7 @@ describe('DetectTokensController', function () {
}); });
sandbox sandbox
.stub(network, 'getLatestBlock') .stub(network, '_getLatestBlock')
.callsFake(() => Promise.resolve({})); .callsFake(() => Promise.resolve({}));
sandbox sandbox
.stub(tokensController, '_instantiateNewEthersProvider') .stub(tokensController, '_instantiateNewEthersProvider')

View File

@ -15,7 +15,7 @@ describe('NetworkController', () => {
beforeEach(() => { beforeEach(() => {
networkController = new NetworkController({ infuraProjectId: 'foo' }); networkController = new NetworkController({ infuraProjectId: 'foo' });
getLatestBlockStub = sinon getLatestBlockStub = sinon
.stub(networkController, 'getLatestBlock') .stub(networkController, '_getLatestBlock')
.callsFake(() => Promise.resolve({})); .callsFake(() => Promise.resolve({}));
setProviderTypeAndWait = () => setProviderTypeAndWait = () =>
new Promise((resolve) => { new Promise((resolve) => {
@ -48,14 +48,6 @@ describe('NetworkController', () => {
}); });
}); });
describe('#setNetworkState', () => {
it('should update the network', () => {
networkController.setNetworkState('1');
const networkState = networkController.getNetworkState();
expect(networkState).toStrictEqual('1');
});
});
describe('#setProviderType', () => { describe('#setProviderType', () => {
it('should update provider.type', () => { it('should update provider.type', () => {
networkController.initializeProvider(networkControllerProviderConfig); networkController.initializeProvider(networkControllerProviderConfig);
@ -67,7 +59,7 @@ describe('NetworkController', () => {
it('should set the network to loading', () => { it('should set the network to loading', () => {
networkController.initializeProvider(networkControllerProviderConfig); networkController.initializeProvider(networkControllerProviderConfig);
const spy = sinon.spy(networkController, 'setNetworkState'); const spy = sinon.spy(networkController, '_setNetworkState');
networkController.setProviderType('mainnet'); networkController.setProviderType('mainnet');
expect(spy.callCount).toStrictEqual(1); expect(spy.callCount).toStrictEqual(1);
@ -93,7 +85,7 @@ describe('NetworkController', () => {
expect(supportsEIP1559).toStrictEqual(true); expect(supportsEIP1559).toStrictEqual(true);
}); });
it('should store EIP1559 support in state to reduce calls to getLatestBlock', async () => { it('should store EIP1559 support in state to reduce calls to _getLatestBlock', async () => {
networkController.initializeProvider(networkControllerProviderConfig); networkController.initializeProvider(networkControllerProviderConfig);
getLatestBlockStub.callsFake(() => getLatestBlockStub.callsFake(() =>
Promise.resolve({ baseFeePerGas: '0xa ' }), Promise.resolve({ baseFeePerGas: '0xa ' }),

View File

@ -136,27 +136,6 @@ export default class NetworkController extends EventEmitter {
return { provider, blockTracker }; return { provider, blockTracker };
} }
/**
* Method to return the latest block for the current network
*
* @returns {object} Block header
*/
getLatestBlock() {
return new Promise((resolve, reject) => {
const { provider } = this.getProviderAndBlockTracker();
const ethQuery = new EthQuery(provider);
ethQuery.sendAsync(
{ method: 'eth_getBlockByNumber', params: ['latest', false] },
(err, block) => {
if (err) {
return reject(err);
}
return resolve(block);
},
);
});
}
/** /**
* Method to check if the block header contains fields that indicate EIP 1559 * Method to check if the block header contains fields that indicate EIP 1559
* support (baseFeePerGas). * support (baseFeePerGas).
@ -168,10 +147,10 @@ export default class NetworkController extends EventEmitter {
if (EIPS[1559] !== undefined) { if (EIPS[1559] !== undefined) {
return EIPS[1559]; return EIPS[1559];
} }
const latestBlock = await this.getLatestBlock(); const latestBlock = await this._getLatestBlock();
const supportsEIP1559 = const supportsEIP1559 =
latestBlock && latestBlock.baseFeePerGas !== undefined; latestBlock && latestBlock.baseFeePerGas !== undefined;
this.setNetworkEIPSupport(1559, supportsEIP1559); this._setNetworkEIPSupport(1559, supportsEIP1559);
return supportsEIP1559; return supportsEIP1559;
} }
@ -179,31 +158,6 @@ export default class NetworkController extends EventEmitter {
return this.networkStore.getState(); return this.networkStore.getState();
} }
setNetworkState(network) {
this.networkStore.putState(network);
}
/**
* Set EIP support indication in the networkDetails store
*
* @param {number} EIPNumber - The number of the EIP to mark support for
* @param {boolean} isSupported - True if the EIP is supported
*/
setNetworkEIPSupport(EIPNumber, isSupported) {
this.networkDetails.updateState({
EIPS: {
[EIPNumber]: isSupported,
},
});
}
/**
* Reset EIP support to default (no support)
*/
clearNetworkDetails() {
this.networkDetails.putState({ ...defaultNetworkDetailsState });
}
isNetworkLoading() { isNetworkLoading() {
return this.getNetworkState() === 'loading'; return this.getNetworkState() === 'loading';
} }
@ -222,9 +176,9 @@ export default class NetworkController extends EventEmitter {
log.warn( log.warn(
'NetworkController - lookupNetwork aborted due to missing chainId', 'NetworkController - lookupNetwork aborted due to missing chainId',
); );
this.setNetworkState('loading'); this._setNetworkState('loading');
// keep network details in sync with network state // keep network details in sync with network state
this.clearNetworkDetails(); this._clearNetworkDetails();
return; return;
} }
@ -244,13 +198,13 @@ export default class NetworkController extends EventEmitter {
const currentNetwork = this.getNetworkState(); const currentNetwork = this.getNetworkState();
if (initialNetwork === currentNetwork) { if (initialNetwork === currentNetwork) {
if (err) { if (err) {
this.setNetworkState('loading'); this._setNetworkState('loading');
// keep network details in sync with network state // keep network details in sync with network state
this.clearNetworkDetails(); this._clearNetworkDetails();
return; return;
} }
this.setNetworkState(networkVersion); this._setNetworkState(networkVersion);
// look up EIP-1559 support // look up EIP-1559 support
this.getEIP1559Compatibility(); this.getEIP1559Compatibility();
} }
@ -276,7 +230,7 @@ export default class NetworkController extends EventEmitter {
isSafeChainId(parseInt(chainId, 16)), isSafeChainId(parseInt(chainId, 16)),
`Invalid chain ID "${chainId}": numerical value greater than max safe value.`, `Invalid chain ID "${chainId}": numerical value greater than max safe value.`,
); );
this.setProviderConfig({ this._setProviderConfig({
type: NETWORK_TYPES.RPC, type: NETWORK_TYPES.RPC,
rpcUrl, rpcUrl,
chainId, chainId,
@ -297,7 +251,7 @@ export default class NetworkController extends EventEmitter {
`Unknown Infura provider type "${type}".`, `Unknown Infura provider type "${type}".`,
); );
const { chainId, ticker } = BUILT_IN_NETWORKS[type]; const { chainId, ticker } = BUILT_IN_NETWORKS[type];
this.setProviderConfig({ this._setProviderConfig({
type, type,
rpcUrl: '', rpcUrl: '',
chainId, chainId,
@ -307,18 +261,7 @@ export default class NetworkController extends EventEmitter {
} }
resetConnection() { resetConnection() {
this.setProviderConfig(this.getProviderConfig()); this._setProviderConfig(this.getProviderConfig());
}
/**
* Sets the provider config and switches the network.
*
* @param config
*/
setProviderConfig(config) {
this.previousProviderStore.updateState(this.getProviderConfig());
this.providerStore.updateState(config);
this._switchNetwork(config);
} }
rollbackToPreviousProvider() { rollbackToPreviousProvider() {
@ -342,6 +285,63 @@ export default class NetworkController extends EventEmitter {
// Private // Private
// //
/**
* Method to return the latest block for the current network
*
* @returns {object} Block header
*/
_getLatestBlock() {
return new Promise((resolve, reject) => {
const { provider } = this.getProviderAndBlockTracker();
const ethQuery = new EthQuery(provider);
ethQuery.sendAsync(
{ method: 'eth_getBlockByNumber', params: ['latest', false] },
(err, block) => {
if (err) {
return reject(err);
}
return resolve(block);
},
);
});
}
_setNetworkState(network) {
this.networkStore.putState(network);
}
/**
* Set EIP support indication in the networkDetails store
*
* @param {number} EIPNumber - The number of the EIP to mark support for
* @param {boolean} isSupported - True if the EIP is supported
*/
_setNetworkEIPSupport(EIPNumber, isSupported) {
this.networkDetails.updateState({
EIPS: {
[EIPNumber]: isSupported,
},
});
}
/**
* Reset EIP support to default (no support)
*/
_clearNetworkDetails() {
this.networkDetails.putState({ ...defaultNetworkDetailsState });
}
/**
* Sets the provider config and switches the network.
*
* @param config
*/
_setProviderConfig(config) {
this.previousProviderStore.updateState(this.getProviderConfig());
this.providerStore.updateState(config);
this._switchNetwork(config);
}
async _checkInfuraAvailability(network) { async _checkInfuraAvailability(network) {
const rpcUrl = `https://${network}.infura.io/v3/${this._infuraProjectId}`; const rpcUrl = `https://${network}.infura.io/v3/${this._infuraProjectId}`;
@ -385,9 +385,9 @@ export default class NetworkController extends EventEmitter {
// Indicate to subscribers that network is about to change // Indicate to subscribers that network is about to change
this.emit(NETWORK_EVENTS.NETWORK_WILL_CHANGE); this.emit(NETWORK_EVENTS.NETWORK_WILL_CHANGE);
// Set loading state // Set loading state
this.setNetworkState('loading'); this._setNetworkState('loading');
// Reset network details // Reset network details
this.clearNetworkDetails(); this._clearNetworkDetails();
// Configure the provider appropriately // Configure the provider appropriately
this._configureProvider(opts); this._configureProvider(opts);
// Notify subscribers that network has changed // Notify subscribers that network has changed

View File

@ -35,7 +35,7 @@ describe('preferences controller', function () {
}); });
sandbox sandbox
.stub(network, 'getLatestBlock') .stub(network, '_getLatestBlock')
.callsFake(() => Promise.resolve({})); .callsFake(() => Promise.resolve({}));
sandbox.stub(network, 'getCurrentChainId').callsFake(() => currentChainId); sandbox.stub(network, 'getCurrentChainId').callsFake(() => currentChainId);
sandbox sandbox