migrate network constants to typescript (#15610)

feature/default_network_editable
Brad Decker 2 years ago committed by GitHub
parent 506d1e74e5
commit c87980bbfe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 18
      app/scripts/controllers/cached-balances.test.js
  2. 6
      app/scripts/controllers/detect-tokens.js
  3. 14
      app/scripts/controllers/detect-tokens.test.js
  4. 28
      app/scripts/controllers/incoming-transactions.js
  5. 178
      app/scripts/controllers/incoming-transactions.test.js
  6. 49
      app/scripts/controllers/metametrics.test.js
  7. 6
      app/scripts/controllers/network/createInfuraClient.js
  8. 36
      app/scripts/controllers/network/network.js
  9. 8
      app/scripts/controllers/preferences.js
  10. 4
      app/scripts/controllers/preferences.test.js
  11. 18
      app/scripts/controllers/swaps.test.js
  12. 11
      app/scripts/controllers/transactions/index.js
  13. 17
      app/scripts/controllers/transactions/tx-state-manager.test.js
  14. 36
      app/scripts/lib/account-tracker.js
  15. 16
      app/scripts/lib/buy-url.js
  16. 27
      app/scripts/lib/buy-url.test.js
  17. 4
      app/scripts/lib/rpc-method-middleware/handlers/switch-ethereum-chain.js
  18. 7
      app/scripts/lib/util.js
  19. 8
      app/scripts/metamask-controller.js
  20. 4
      app/scripts/metamask-controller.test.js
  21. 4
      app/scripts/migrations/051.js
  22. 6
      app/scripts/migrations/051.test.js
  23. 82
      app/scripts/migrations/052.js
  24. 124
      app/scripts/migrations/052.test.js
  25. 37
      app/scripts/migrations/054.test.js
  26. 5
      app/scripts/migrations/055.js
  27. 33
      app/scripts/migrations/055.test.js
  28. 35
      app/scripts/migrations/059.test.js
  29. 10
      app/scripts/migrations/064.test.js
  30. 426
      shared/constants/network.js
  31. 675
      shared/constants/network.ts
  32. 108
      shared/constants/swaps.js
  33. 16
      shared/modules/network.utils.js
  34. 8
      test/jest/mock-store.js
  35. 6
      ui/components/app/alerts/unconnected-account-alert/unconnected-account-alert.test.js
  36. 21
      ui/components/app/collectible-details/collectible-details.js
  37. 4
      ui/components/app/dropdowns/network-dropdown.js
  38. 4
      ui/components/app/gas-details-item/gas-details-item-title/gas-details-item-title.test.js
  39. 4
      ui/components/app/loading-network-screen/loading-network-screen.container.js
  40. 4
      ui/components/app/menu-bar/menu-bar.test.js
  41. 16
      ui/components/app/network-display/network-display.js
  42. 14
      ui/components/app/network-display/network-display.stories.js
  43. 57
      ui/components/app/transaction-activity-log/transaction-activity-log.util.test.js
  44. 4
      ui/components/ui/new-network-info/new-network-info.js
  45. 13
      ui/ducks/confirm-transaction/confirm-transaction.duck.test.js
  46. 4
      ui/ducks/ens.js
  47. 4
      ui/ducks/metamask/metamask.js
  48. 41
      ui/ducks/send/send.test.js
  49. 15
      ui/ducks/swaps/swaps.test.js
  50. 9
      ui/helpers/utils/tx-helper.test.js
  51. 21
      ui/helpers/utils/util.js
  52. 24
      ui/hooks/useTokensToSearch.js
  53. 4
      ui/hooks/useTransactionDisplayData.test.js
  54. 7
      ui/pages/confirm-approve/confirm-approve-content/confirm-approve-content.component.js
  55. 8
      ui/pages/send/send.test.js
  56. 10
      ui/pages/settings/networks-tab/networks-form/networks-form.test.js
  57. 9
      ui/pages/settings/networks-tab/networks-list-item/networks-list-item.js
  58. 79
      ui/pages/settings/networks-tab/networks-tab.constants.js
  59. 6
      ui/pages/settings/networks-tab/networks-tab.js
  60. 21
      ui/pages/swaps/fee-card/fee-card.js
  61. 4
      ui/pages/swaps/fee-card/fee-card.stories.js
  62. 4
      ui/pages/swaps/fee-card/fee-card.test.js
  63. 34
      ui/pages/swaps/swaps.util.js
  64. 137
      ui/pages/swaps/swaps.util.test.js
  65. 4
      ui/pages/swaps/view-quote/view-quote-price-difference.test.js
  66. 4
      ui/pages/token-details/token-details-page.js
  67. 14
      ui/selectors/confirm-transaction.test.js
  68. 4
      ui/selectors/nonce-sorted-transactions-selector.test.js
  69. 4
      ui/selectors/permissions.test.js
  70. 33
      ui/selectors/selectors.js
  71. 17
      ui/selectors/transactions.test.js
  72. 4
      ui/store/actionConstants.test.js

@ -1,13 +1,13 @@
import { strict as assert } from 'assert'; import { strict as assert } from 'assert';
import sinon from 'sinon'; import sinon from 'sinon';
import { KOVAN_CHAIN_ID } from '../../../shared/constants/network'; import { CHAIN_IDS } from '../../../shared/constants/network';
import CachedBalancesController from './cached-balances'; import CachedBalancesController from './cached-balances';
describe('CachedBalancesController', function () { describe('CachedBalancesController', function () {
describe('updateCachedBalances', function () { describe('updateCachedBalances', function () {
it('should update the cached balances', async function () { it('should update the cached balances', async function () {
const controller = new CachedBalancesController({ const controller = new CachedBalancesController({
getCurrentChainId: () => KOVAN_CHAIN_ID, getCurrentChainId: () => CHAIN_IDS.KOVAN,
accountTracker: { accountTracker: {
store: { store: {
subscribe: () => undefined, subscribe: () => undefined,
@ -27,7 +27,7 @@ describe('CachedBalancesController', function () {
assert.equal(controller._generateBalancesToCache.callCount, 1); assert.equal(controller._generateBalancesToCache.callCount, 1);
assert.deepEqual(controller._generateBalancesToCache.args[0], [ assert.deepEqual(controller._generateBalancesToCache.args[0], [
'mockAccounts', 'mockAccounts',
KOVAN_CHAIN_ID, CHAIN_IDS.KOVAN,
]); ]);
assert.equal( assert.equal(
controller.store.getState().cachedBalances, controller.store.getState().cachedBalances,
@ -46,7 +46,7 @@ describe('CachedBalancesController', function () {
}, },
initState: { initState: {
cachedBalances: { cachedBalances: {
[KOVAN_CHAIN_ID]: { [CHAIN_IDS.KOVAN]: {
a: '0x1', a: '0x1',
b: '0x2', b: '0x2',
c: '0x3', c: '0x3',
@ -66,11 +66,11 @@ describe('CachedBalancesController', function () {
b: { balance: null }, b: { balance: null },
c: { balance: '0x5' }, c: { balance: '0x5' },
}, },
KOVAN_CHAIN_ID, CHAIN_IDS.KOVAN,
); );
assert.deepEqual(result, { assert.deepEqual(result, {
[KOVAN_CHAIN_ID]: { [CHAIN_IDS.KOVAN]: {
a: '0x4', a: '0x4',
b: '0x2', b: '0x2',
c: '0x5', c: '0x5',
@ -92,7 +92,7 @@ describe('CachedBalancesController', function () {
}, },
initState: { initState: {
cachedBalances: { cachedBalances: {
[KOVAN_CHAIN_ID]: { [CHAIN_IDS.KOVAN]: {
a: '0x1', a: '0x1',
b: '0x2', b: '0x2',
c: '0x3', c: '0x3',
@ -111,7 +111,7 @@ describe('CachedBalancesController', function () {
); );
assert.deepEqual(result, { assert.deepEqual(result, {
[KOVAN_CHAIN_ID]: { [CHAIN_IDS.KOVAN]: {
a: '0x1', a: '0x1',
b: '0x2', b: '0x2',
c: '0x3', c: '0x3',
@ -128,7 +128,7 @@ describe('CachedBalancesController', function () {
it('should subscribe to the account tracker with the updateCachedBalances method', async function () { it('should subscribe to the account tracker with the updateCachedBalances method', async function () {
const subscribeSpy = sinon.spy(); const subscribeSpy = sinon.spy();
const controller = new CachedBalancesController({ const controller = new CachedBalancesController({
getCurrentChainId: () => KOVAN_CHAIN_ID, getCurrentChainId: () => CHAIN_IDS.KOVAN,
accountTracker: { accountTracker: {
store: { store: {
subscribe: subscribeSpy, subscribe: subscribeSpy,

@ -1,6 +1,6 @@
import { warn } from 'loglevel'; import { warn } from 'loglevel';
import { MINUTE } from '../../../shared/constants/time'; import { MINUTE } from '../../../shared/constants/time';
import { MAINNET_CHAIN_ID } from '../../../shared/constants/network'; import { CHAIN_IDS } from '../../../shared/constants/network';
import { STATIC_MAINNET_TOKEN_LIST } from '../../../shared/constants/tokens'; import { STATIC_MAINNET_TOKEN_LIST } from '../../../shared/constants/tokens';
import { isTokenDetectionEnabledForNetwork } from '../../../shared/modules/network.utils'; import { isTokenDetectionEnabledForNetwork } from '../../../shared/modules/network.utils';
import { isEqualCaseInsensitive } from '../../../shared/modules/string-utils'; import { isEqualCaseInsensitive } from '../../../shared/modules/string-utils';
@ -96,14 +96,14 @@ export default class DetectTokensController {
} }
if ( if (
!this.useTokenDetection && !this.useTokenDetection &&
this.getChainIdFromNetworkStore(this._network) !== MAINNET_CHAIN_ID this.getChainIdFromNetworkStore(this._network) !== CHAIN_IDS.MAINNET
) { ) {
return; return;
} }
const isTokenDetectionInactiveInMainnet = const isTokenDetectionInactiveInMainnet =
!this.useTokenDetection && !this.useTokenDetection &&
this.getChainIdFromNetworkStore(this._network) === MAINNET_CHAIN_ID; this.getChainIdFromNetworkStore(this._network) === CHAIN_IDS.MAINNET;
const { tokenList } = this._tokenList.state; const { tokenList } = this._tokenList.state;
const tokenListUsed = isTokenDetectionInactiveInMainnet const tokenListUsed = isTokenDetectionInactiveInMainnet

@ -9,7 +9,7 @@ import {
TokensController, TokensController,
AssetsContractController, AssetsContractController,
} from '@metamask/controllers'; } from '@metamask/controllers';
import { MAINNET, ROPSTEN } from '../../../shared/constants/network'; import { NETWORK_TYPES } from '../../../shared/constants/network';
import { toChecksumHexAddress } from '../../../shared/modules/hexstring-utils'; import { toChecksumHexAddress } from '../../../shared/modules/hexstring-utils';
import DetectTokensController from './detect-tokens'; import DetectTokensController from './detect-tokens';
import NetworkController from './network'; import NetworkController from './network';
@ -169,7 +169,7 @@ describe('DetectTokensController', function () {
it('should be called on every polling period', async function () { it('should be called on every polling period', async function () {
const clock = sandbox.useFakeTimers(); const clock = sandbox.useFakeTimers();
network.setProviderType(MAINNET); network.setProviderType(NETWORK_TYPES.MAINNET);
const controller = new DetectTokensController({ const controller = new DetectTokensController({
preferences, preferences,
network, network,
@ -195,7 +195,7 @@ describe('DetectTokensController', function () {
it('should not check and add tokens while on unsupported networks', async function () { it('should not check and add tokens while on unsupported networks', async function () {
sandbox.useFakeTimers(); sandbox.useFakeTimers();
network.setProviderType(ROPSTEN); network.setProviderType(NETWORK_TYPES.ROPSTEN);
const tokenListMessengerRopsten = new ControllerMessenger().getRestricted({ const tokenListMessengerRopsten = new ControllerMessenger().getRestricted({
name: 'TokenListController', name: 'TokenListController',
}); });
@ -228,7 +228,7 @@ describe('DetectTokensController', function () {
it('should skip adding tokens listed in ignoredTokens array', async function () { it('should skip adding tokens listed in ignoredTokens array', async function () {
sandbox.useFakeTimers(); sandbox.useFakeTimers();
network.setProviderType(MAINNET); network.setProviderType(NETWORK_TYPES.MAINNET);
const controller = new DetectTokensController({ const controller = new DetectTokensController({
preferences, preferences,
network, network,
@ -279,7 +279,7 @@ describe('DetectTokensController', function () {
it('should check and add tokens while on supported networks', async function () { it('should check and add tokens while on supported networks', async function () {
sandbox.useFakeTimers(); sandbox.useFakeTimers();
network.setProviderType(MAINNET); network.setProviderType(NETWORK_TYPES.MAINNET);
const controller = new DetectTokensController({ const controller = new DetectTokensController({
preferences, preferences,
network, network,
@ -374,7 +374,7 @@ describe('DetectTokensController', function () {
it('should not trigger detect new tokens when not unlocked', async function () { it('should not trigger detect new tokens when not unlocked', async function () {
const clock = sandbox.useFakeTimers(); const clock = sandbox.useFakeTimers();
network.setProviderType(MAINNET); network.setProviderType(NETWORK_TYPES.MAINNET);
const controller = new DetectTokensController({ const controller = new DetectTokensController({
preferences, preferences,
network, network,
@ -395,7 +395,7 @@ describe('DetectTokensController', function () {
it('should not trigger detect new tokens when not open', async function () { it('should not trigger detect new tokens when not open', async function () {
const clock = sandbox.useFakeTimers(); const clock = sandbox.useFakeTimers();
network.setProviderType(MAINNET); network.setProviderType(NETWORK_TYPES.MAINNET);
const controller = new DetectTokensController({ const controller = new DetectTokensController({
preferences, preferences,
network, network,

@ -10,13 +10,9 @@ import {
TRANSACTION_STATUSES, TRANSACTION_STATUSES,
} from '../../../shared/constants/transaction'; } from '../../../shared/constants/transaction';
import { import {
CHAIN_IDS,
CHAIN_ID_TO_NETWORK_ID_MAP, CHAIN_ID_TO_NETWORK_ID_MAP,
CHAIN_ID_TO_TYPE_MAP, CHAIN_ID_TO_TYPE_MAP,
GOERLI_CHAIN_ID,
KOVAN_CHAIN_ID,
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID,
} from '../../../shared/constants/network'; } from '../../../shared/constants/network';
const fetchWithTimeout = getFetchWithTimeout(); const fetchWithTimeout = getFetchWithTimeout();
@ -53,11 +49,11 @@ const fetchWithTimeout = getFetchWithTimeout();
* attempt to retrieve incoming transactions on any custom RPC endpoints. * attempt to retrieve incoming transactions on any custom RPC endpoints.
*/ */
const etherscanSupportedNetworks = [ const etherscanSupportedNetworks = [
GOERLI_CHAIN_ID, CHAIN_IDS.GOERLI,
KOVAN_CHAIN_ID, CHAIN_IDS.KOVAN,
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
RINKEBY_CHAIN_ID, CHAIN_IDS.RINKEBY,
ROPSTEN_CHAIN_ID, CHAIN_IDS.ROPSTEN,
]; ];
export default class IncomingTransactionsController { export default class IncomingTransactionsController {
@ -81,11 +77,11 @@ export default class IncomingTransactionsController {
const initState = { const initState = {
incomingTransactions: {}, incomingTransactions: {},
incomingTxLastFetchedBlockByChainId: { incomingTxLastFetchedBlockByChainId: {
[GOERLI_CHAIN_ID]: null, [CHAIN_IDS.GOERLI]: null,
[KOVAN_CHAIN_ID]: null, [CHAIN_IDS.KOVAN]: null,
[MAINNET_CHAIN_ID]: null, [CHAIN_IDS.MAINNET]: null,
[RINKEBY_CHAIN_ID]: null, [CHAIN_IDS.RINKEBY]: null,
[ROPSTEN_CHAIN_ID]: null, [CHAIN_IDS.ROPSTEN]: null,
}, },
...opts.initState, ...opts.initState,
}; };
@ -225,7 +221,7 @@ export default class IncomingTransactionsController {
*/ */
async _getNewIncomingTransactions(address, fromBlock, chainId) { async _getNewIncomingTransactions(address, fromBlock, chainId) {
const etherscanSubdomain = const etherscanSubdomain =
chainId === MAINNET_CHAIN_ID chainId === CHAIN_IDS.MAINNET
? 'api' ? 'api'
: `api-${CHAIN_ID_TO_TYPE_MAP[chainId]}`; : `api-${CHAIN_ID_TO_TYPE_MAP[chainId]}`;

@ -7,13 +7,9 @@ import { cloneDeep } from 'lodash';
import waitUntilCalled from '../../../test/lib/wait-until-called'; import waitUntilCalled from '../../../test/lib/wait-until-called';
import { import {
CHAIN_ID_TO_TYPE_MAP, CHAIN_ID_TO_TYPE_MAP,
GOERLI_CHAIN_ID, CHAIN_IDS,
KOVAN_CHAIN_ID, NETWORK_TYPES,
MAINNET_CHAIN_ID, NETWORK_IDS,
RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID,
ROPSTEN_NETWORK_ID,
ROPSTEN,
} from '../../../shared/constants/network'; } from '../../../shared/constants/network';
import { import {
TRANSACTION_TYPES, TRANSACTION_TYPES,
@ -34,18 +30,18 @@ const PREPOPULATED_INCOMING_TXS_BY_HASH = {
[EXISTING_INCOMING_TX.hash]: EXISTING_INCOMING_TX, [EXISTING_INCOMING_TX.hash]: EXISTING_INCOMING_TX,
}; };
const PREPOPULATED_BLOCKS_BY_NETWORK = { const PREPOPULATED_BLOCKS_BY_NETWORK = {
[GOERLI_CHAIN_ID]: 1, [CHAIN_IDS.GOERLI]: 1,
[KOVAN_CHAIN_ID]: 2, [CHAIN_IDS.KOVAN]: 2,
[MAINNET_CHAIN_ID]: 3, [CHAIN_IDS.MAINNET]: 3,
[RINKEBY_CHAIN_ID]: 5, [CHAIN_IDS.RINKEBY]: 5,
[ROPSTEN_CHAIN_ID]: 4, [CHAIN_IDS.ROPSTEN]: 4,
}; };
const EMPTY_BLOCKS_BY_NETWORK = { const EMPTY_BLOCKS_BY_NETWORK = {
[GOERLI_CHAIN_ID]: null, [CHAIN_IDS.GOERLI]: null,
[KOVAN_CHAIN_ID]: null, [CHAIN_IDS.KOVAN]: null,
[MAINNET_CHAIN_ID]: null, [CHAIN_IDS.MAINNET]: null,
[RINKEBY_CHAIN_ID]: null, [CHAIN_IDS.RINKEBY]: null,
[ROPSTEN_CHAIN_ID]: null, [CHAIN_IDS.ROPSTEN]: null,
}; };
function getEmptyInitState() { function getEmptyInitState() {
@ -148,16 +144,16 @@ const getFakeEtherscanTransaction = ({
function nockEtherscanApiForAllChains(mockResponse) { function nockEtherscanApiForAllChains(mockResponse) {
for (const chainId of [ for (const chainId of [
GOERLI_CHAIN_ID, CHAIN_IDS.GOERLI,
KOVAN_CHAIN_ID, CHAIN_IDS.KOVAN,
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
RINKEBY_CHAIN_ID, CHAIN_IDS.RINKEBY,
ROPSTEN_CHAIN_ID, CHAIN_IDS.ROPSTEN,
'undefined', 'undefined',
]) { ]) {
nock( nock(
`https://api${ `https://api${
chainId === MAINNET_CHAIN_ID ? '' : `-${CHAIN_ID_TO_TYPE_MAP[chainId]}` chainId === CHAIN_IDS.MAINNET ? '' : `-${CHAIN_ID_TO_TYPE_MAP[chainId]}`
}.etherscan.io`, }.etherscan.io`,
) )
.get(/api.+/u) .get(/api.+/u)
@ -247,14 +243,14 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
); );
const startBlock = const startBlock =
getNonEmptyInitState().incomingTxLastFetchedBlockByChainId[ getNonEmptyInitState().incomingTxLastFetchedBlockByChainId[
ROPSTEN_CHAIN_ID CHAIN_IDS.ROPSTEN
]; ];
nock('https://api-ropsten.etherscan.io') nock('https://api-ropsten.etherscan.io')
.get( .get(
@ -306,8 +302,8 @@ describe('IncomingTransactionsController', function () {
'0xfake': { '0xfake': {
blockNumber: '10', blockNumber: '10',
hash: '0xfake', hash: '0xfake',
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
status: TRANSACTION_STATUSES.CONFIRMED, status: TRANSACTION_STATUSES.CONFIRMED,
time: 16000000000000000, time: 16000000000000000,
type: TRANSACTION_TYPES.INCOMING, type: TRANSACTION_TYPES.INCOMING,
@ -323,8 +319,8 @@ describe('IncomingTransactionsController', function () {
'0xfakeeip1559': { '0xfakeeip1559': {
blockNumber: '10', blockNumber: '10',
hash: '0xfakeeip1559', hash: '0xfakeeip1559',
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
status: TRANSACTION_STATUSES.CONFIRMED, status: TRANSACTION_STATUSES.CONFIRMED,
time: 16000000000000000, time: 16000000000000000,
type: TRANSACTION_TYPES.INCOMING, type: TRANSACTION_TYPES.INCOMING,
@ -341,7 +337,7 @@ describe('IncomingTransactionsController', function () {
}, },
incomingTxLastFetchedBlockByChainId: { incomingTxLastFetchedBlockByChainId: {
...getNonEmptyInitState().incomingTxLastFetchedBlockByChainId, ...getNonEmptyInitState().incomingTxLastFetchedBlockByChainId,
[ROPSTEN_CHAIN_ID]: 11, [CHAIN_IDS.ROPSTEN]: 11,
}, },
}, },
'State should have been updated after first block was received', 'State should have been updated after first block was received',
@ -449,7 +445,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -494,7 +490,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -541,7 +537,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -549,7 +545,7 @@ describe('IncomingTransactionsController', function () {
const NEW_MOCK_SELECTED_ADDRESS = `${MOCK_SELECTED_ADDRESS}9`; const NEW_MOCK_SELECTED_ADDRESS = `${MOCK_SELECTED_ADDRESS}9`;
const startBlock = const startBlock =
getNonEmptyInitState().incomingTxLastFetchedBlockByChainId[ getNonEmptyInitState().incomingTxLastFetchedBlockByChainId[
ROPSTEN_CHAIN_ID CHAIN_IDS.ROPSTEN
]; ];
nock('https://api-ropsten.etherscan.io') nock('https://api-ropsten.etherscan.io')
.get( .get(
@ -604,8 +600,8 @@ describe('IncomingTransactionsController', function () {
'0xfake': { '0xfake': {
blockNumber: '10', blockNumber: '10',
hash: '0xfake', hash: '0xfake',
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
status: TRANSACTION_STATUSES.CONFIRMED, status: TRANSACTION_STATUSES.CONFIRMED,
time: 16000000000000000, time: 16000000000000000,
type: TRANSACTION_TYPES.INCOMING, type: TRANSACTION_TYPES.INCOMING,
@ -621,7 +617,7 @@ describe('IncomingTransactionsController', function () {
}, },
incomingTxLastFetchedBlockByChainId: { incomingTxLastFetchedBlockByChainId: {
...getNonEmptyInitState().incomingTxLastFetchedBlockByChainId, ...getNonEmptyInitState().incomingTxLastFetchedBlockByChainId,
[ROPSTEN_CHAIN_ID]: 11, [CHAIN_IDS.ROPSTEN]: 11,
}, },
}, },
'State should have been updated after first block was received', 'State should have been updated after first block was received',
@ -687,8 +683,9 @@ describe('IncomingTransactionsController', function () {
}); });
it('should update when switching to a supported network', async function () { it('should update when switching to a supported network', async function () {
const mockedNetworkMethods = const mockedNetworkMethods = getMockNetworkControllerMethods(
getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID); CHAIN_IDS.ROPSTEN,
);
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
@ -699,7 +696,7 @@ describe('IncomingTransactionsController', function () {
); );
const startBlock = const startBlock =
getNonEmptyInitState().incomingTxLastFetchedBlockByChainId[ getNonEmptyInitState().incomingTxLastFetchedBlockByChainId[
ROPSTEN_CHAIN_ID CHAIN_IDS.ROPSTEN
]; ];
nock('https://api-ropsten.etherscan.io') nock('https://api-ropsten.etherscan.io')
.get( .get(
@ -723,7 +720,7 @@ describe('IncomingTransactionsController', function () {
const subscription = const subscription =
mockedNetworkMethods.onNetworkDidChange.getCall(0).args[0]; mockedNetworkMethods.onNetworkDidChange.getCall(0).args[0];
await subscription(ROPSTEN_CHAIN_ID); await subscription(CHAIN_IDS.ROPSTEN);
await updateStateCalled(); await updateStateCalled();
const actualState = incomingTransactionsController.store.getState(); const actualState = incomingTransactionsController.store.getState();
@ -744,8 +741,8 @@ describe('IncomingTransactionsController', function () {
'0xfake': { '0xfake': {
blockNumber: '10', blockNumber: '10',
hash: '0xfake', hash: '0xfake',
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
status: TRANSACTION_STATUSES.CONFIRMED, status: TRANSACTION_STATUSES.CONFIRMED,
time: 16000000000000000, time: 16000000000000000,
type: TRANSACTION_TYPES.INCOMING, type: TRANSACTION_TYPES.INCOMING,
@ -761,7 +758,7 @@ describe('IncomingTransactionsController', function () {
}, },
incomingTxLastFetchedBlockByChainId: { incomingTxLastFetchedBlockByChainId: {
...getNonEmptyInitState().incomingTxLastFetchedBlockByChainId, ...getNonEmptyInitState().incomingTxLastFetchedBlockByChainId,
[ROPSTEN_CHAIN_ID]: 11, [CHAIN_IDS.ROPSTEN]: 11,
}, },
}, },
'State should have been updated after first block was received', 'State should have been updated after first block was received',
@ -769,8 +766,9 @@ describe('IncomingTransactionsController', function () {
}); });
it('should not update when switching to an unsupported network', async function () { it('should not update when switching to an unsupported network', async function () {
const mockedNetworkMethods = const mockedNetworkMethods = getMockNetworkControllerMethods(
getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID); CHAIN_IDS.ROPSTEN,
);
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
@ -828,10 +826,10 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = const incomingTransactionsController =
new IncomingTransactionsController({ new IncomingTransactionsController({
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getEmptyInitState(), initState: getEmptyInitState(),
getCurrentChainId: () => ROPSTEN_CHAIN_ID, getCurrentChainId: () => CHAIN_IDS.ROPSTEN,
}); });
sinon.spy(incomingTransactionsController.store, 'updateState'); sinon.spy(incomingTransactionsController.store, 'updateState');
@ -846,14 +844,14 @@ describe('IncomingTransactionsController', function () {
assert.deepStrictEqual( assert.deepStrictEqual(
incomingTransactionsController._getNewIncomingTransactions.getCall(0) incomingTransactionsController._getNewIncomingTransactions.getCall(0)
.args, .args,
['fakeAddress', 999, ROPSTEN_CHAIN_ID], ['fakeAddress', 999, CHAIN_IDS.ROPSTEN],
); );
assert.deepStrictEqual( assert.deepStrictEqual(
incomingTransactionsController.store.updateState.getCall(0).args[0], incomingTransactionsController.store.updateState.getCall(0).args[0],
{ {
incomingTxLastFetchedBlockByChainId: { incomingTxLastFetchedBlockByChainId: {
...EMPTY_BLOCKS_BY_NETWORK, ...EMPTY_BLOCKS_BY_NETWORK,
[ROPSTEN_CHAIN_ID]: 1000, [CHAIN_IDS.ROPSTEN]: 1000,
}, },
incomingTransactions: {}, incomingTransactions: {},
}, },
@ -864,10 +862,10 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = const incomingTransactionsController =
new IncomingTransactionsController({ new IncomingTransactionsController({
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getEmptyInitState(), initState: getEmptyInitState(),
getCurrentChainId: () => ROPSTEN_CHAIN_ID, getCurrentChainId: () => CHAIN_IDS.ROPSTEN,
}); });
const NEW_TRANSACTION_ONE = { const NEW_TRANSACTION_ONE = {
@ -893,7 +891,7 @@ describe('IncomingTransactionsController', function () {
assert.deepStrictEqual( assert.deepStrictEqual(
incomingTransactionsController._getNewIncomingTransactions.getCall(0) incomingTransactionsController._getNewIncomingTransactions.getCall(0)
.args, .args,
['fakeAddress', 10, ROPSTEN_CHAIN_ID], ['fakeAddress', 10, CHAIN_IDS.ROPSTEN],
); );
assert.deepStrictEqual( assert.deepStrictEqual(
@ -901,7 +899,7 @@ describe('IncomingTransactionsController', function () {
{ {
incomingTxLastFetchedBlockByChainId: { incomingTxLastFetchedBlockByChainId: {
...EMPTY_BLOCKS_BY_NETWORK, ...EMPTY_BLOCKS_BY_NETWORK,
[ROPSTEN_CHAIN_ID]: 445, [CHAIN_IDS.ROPSTEN]: 445,
}, },
incomingTransactions: { incomingTransactions: {
[NEW_TRANSACTION_ONE.hash]: NEW_TRANSACTION_ONE, [NEW_TRANSACTION_ONE.hash]: NEW_TRANSACTION_ONE,
@ -917,10 +915,10 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = const incomingTransactionsController =
new IncomingTransactionsController({ new IncomingTransactionsController({
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
getCurrentChainId: () => ROPSTEN_CHAIN_ID, getCurrentChainId: () => CHAIN_IDS.ROPSTEN,
}); });
sinon.spy(incomingTransactionsController.store, 'updateState'); sinon.spy(incomingTransactionsController.store, 'updateState');
incomingTransactionsController._getNewIncomingTransactions = sinon incomingTransactionsController._getNewIncomingTransactions = sinon
@ -936,7 +934,7 @@ describe('IncomingTransactionsController', function () {
assert.deepStrictEqual( assert.deepStrictEqual(
incomingTransactionsController._getNewIncomingTransactions.getCall(0) incomingTransactionsController._getNewIncomingTransactions.getCall(0)
.args, .args,
['fakeAddress', 4, ROPSTEN_CHAIN_ID], ['fakeAddress', 4, CHAIN_IDS.ROPSTEN],
); );
assert.deepStrictEqual( assert.deepStrictEqual(
@ -944,8 +942,8 @@ describe('IncomingTransactionsController', function () {
{ {
incomingTxLastFetchedBlockByChainId: { incomingTxLastFetchedBlockByChainId: {
...PREPOPULATED_BLOCKS_BY_NETWORK, ...PREPOPULATED_BLOCKS_BY_NETWORK,
[ROPSTEN_CHAIN_ID]: [CHAIN_IDS.ROPSTEN]:
PREPOPULATED_BLOCKS_BY_NETWORK[ROPSTEN_CHAIN_ID] + 1, PREPOPULATED_BLOCKS_BY_NETWORK[CHAIN_IDS.ROPSTEN] + 1,
}, },
incomingTransactions: PREPOPULATED_INCOMING_TXS_BY_HASH, incomingTransactions: PREPOPULATED_INCOMING_TXS_BY_HASH,
}, },
@ -957,10 +955,10 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
getCurrentChainId: () => ROPSTEN_CHAIN_ID, getCurrentChainId: () => CHAIN_IDS.ROPSTEN,
}, },
); );
@ -987,7 +985,7 @@ describe('IncomingTransactionsController', function () {
assert.deepStrictEqual( assert.deepStrictEqual(
incomingTransactionsController._getNewIncomingTransactions.getCall(0) incomingTransactionsController._getNewIncomingTransactions.getCall(0)
.args, .args,
['fakeAddress', 4, ROPSTEN_CHAIN_ID], ['fakeAddress', 4, CHAIN_IDS.ROPSTEN],
); );
assert.deepStrictEqual( assert.deepStrictEqual(
@ -995,7 +993,7 @@ describe('IncomingTransactionsController', function () {
{ {
incomingTxLastFetchedBlockByChainId: { incomingTxLastFetchedBlockByChainId: {
...PREPOPULATED_BLOCKS_BY_NETWORK, ...PREPOPULATED_BLOCKS_BY_NETWORK,
[ROPSTEN_CHAIN_ID]: 445, [CHAIN_IDS.ROPSTEN]: 445,
}, },
incomingTransactions: { incomingTransactions: {
...PREPOPULATED_INCOMING_TXS_BY_HASH, ...PREPOPULATED_INCOMING_TXS_BY_HASH,
@ -1032,7 +1030,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -1041,13 +1039,13 @@ describe('IncomingTransactionsController', function () {
await incomingTransactionsController._getNewIncomingTransactions( await incomingTransactionsController._getNewIncomingTransactions(
ADDRESS_TO_FETCH_FOR, ADDRESS_TO_FETCH_FOR,
'789', '789',
ROPSTEN_CHAIN_ID, CHAIN_IDS.ROPSTEN,
); );
assert(mockFetch.calledOnce); assert(mockFetch.calledOnce);
assert.strictEqual( assert.strictEqual(
mockFetch.getCall(0).args[0], mockFetch.getCall(0).args[0],
`https://api-${ROPSTEN}.etherscan.io/api?module=account&action=txlist&address=0xfakeaddress&tag=latest&page=1&startBlock=789`, `https://api-${NETWORK_TYPES.ROPSTEN}.etherscan.io/api?module=account&action=txlist&address=0xfakeaddress&tag=latest&page=1&startBlock=789`,
); );
}); });
@ -1055,7 +1053,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(MAINNET_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.MAINNET),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -1064,7 +1062,7 @@ describe('IncomingTransactionsController', function () {
await incomingTransactionsController._getNewIncomingTransactions( await incomingTransactionsController._getNewIncomingTransactions(
ADDRESS_TO_FETCH_FOR, ADDRESS_TO_FETCH_FOR,
'789', '789',
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
); );
assert(mockFetch.calledOnce); assert(mockFetch.calledOnce);
@ -1078,7 +1076,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -1087,13 +1085,13 @@ describe('IncomingTransactionsController', function () {
await incomingTransactionsController._getNewIncomingTransactions( await incomingTransactionsController._getNewIncomingTransactions(
ADDRESS_TO_FETCH_FOR, ADDRESS_TO_FETCH_FOR,
null, null,
ROPSTEN_CHAIN_ID, CHAIN_IDS.ROPSTEN,
); );
assert(mockFetch.calledOnce); assert(mockFetch.calledOnce);
assert.strictEqual( assert.strictEqual(
mockFetch.getCall(0).args[0], mockFetch.getCall(0).args[0],
`https://api-${ROPSTEN}.etherscan.io/api?module=account&action=txlist&address=0xfakeaddress&tag=latest&page=1`, `https://api-${NETWORK_TYPES.ROPSTEN}.etherscan.io/api?module=account&action=txlist&address=0xfakeaddress&tag=latest&page=1`,
); );
}); });
@ -1101,7 +1099,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -1111,14 +1109,14 @@ describe('IncomingTransactionsController', function () {
await incomingTransactionsController._getNewIncomingTransactions( await incomingTransactionsController._getNewIncomingTransactions(
ADDRESS_TO_FETCH_FOR, ADDRESS_TO_FETCH_FOR,
'789', '789',
ROPSTEN_CHAIN_ID, CHAIN_IDS.ROPSTEN,
); );
assert(mockFetch.calledOnce); assert(mockFetch.calledOnce);
assert.deepStrictEqual(result, [ assert.deepStrictEqual(result, [
incomingTransactionsController._normalizeTxFromEtherscan( incomingTransactionsController._normalizeTxFromEtherscan(
FETCHED_TX, FETCHED_TX,
ROPSTEN_CHAIN_ID, CHAIN_IDS.ROPSTEN,
), ),
]); ]);
}); });
@ -1134,7 +1132,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -1144,7 +1142,7 @@ describe('IncomingTransactionsController', function () {
await incomingTransactionsController._getNewIncomingTransactions( await incomingTransactionsController._getNewIncomingTransactions(
ADDRESS_TO_FETCH_FOR, ADDRESS_TO_FETCH_FOR,
'789', '789',
ROPSTEN_CHAIN_ID, CHAIN_IDS.ROPSTEN,
); );
assert.deepStrictEqual(result, []); assert.deepStrictEqual(result, []);
window.fetch = tempFetchStatusZero; window.fetch = tempFetchStatusZero;
@ -1162,7 +1160,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -1172,7 +1170,7 @@ describe('IncomingTransactionsController', function () {
await incomingTransactionsController._getNewIncomingTransactions( await incomingTransactionsController._getNewIncomingTransactions(
ADDRESS_TO_FETCH_FOR, ADDRESS_TO_FETCH_FOR,
'789', '789',
ROPSTEN_CHAIN_ID, CHAIN_IDS.ROPSTEN,
); );
assert.deepStrictEqual(result, []); assert.deepStrictEqual(result, []);
window.fetch = tempFetchEmptyResult; window.fetch = tempFetchEmptyResult;
@ -1185,7 +1183,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -1204,14 +1202,14 @@ describe('IncomingTransactionsController', function () {
value: '15', value: '15',
hash: '0xg', hash: '0xg',
}, },
ROPSTEN_CHAIN_ID, CHAIN_IDS.ROPSTEN,
); );
assert.deepStrictEqual(result, { assert.deepStrictEqual(result, {
blockNumber: 333, blockNumber: 333,
id: 54321, id: 54321,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
status: TRANSACTION_STATUSES.FAILED, status: TRANSACTION_STATUSES.FAILED,
time: 4444000, time: 4444000,
txParams: { txParams: {
@ -1231,7 +1229,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -1250,14 +1248,14 @@ describe('IncomingTransactionsController', function () {
value: '15', value: '15',
hash: '0xg', hash: '0xg',
}, },
ROPSTEN_CHAIN_ID, CHAIN_IDS.ROPSTEN,
); );
assert.deepStrictEqual(result, { assert.deepStrictEqual(result, {
blockNumber: 333, blockNumber: 333,
id: 54321, id: 54321,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
status: TRANSACTION_STATUSES.CONFIRMED, status: TRANSACTION_STATUSES.CONFIRMED,
time: 4444000, time: 4444000,
txParams: { txParams: {
@ -1277,7 +1275,7 @@ describe('IncomingTransactionsController', function () {
const incomingTransactionsController = new IncomingTransactionsController( const incomingTransactionsController = new IncomingTransactionsController(
{ {
blockTracker: getMockBlockTracker(), blockTracker: getMockBlockTracker(),
...getMockNetworkControllerMethods(ROPSTEN_CHAIN_ID), ...getMockNetworkControllerMethods(CHAIN_IDS.ROPSTEN),
preferencesController: getMockPreferencesController(), preferencesController: getMockPreferencesController(),
initState: getNonEmptyInitState(), initState: getNonEmptyInitState(),
}, },
@ -1297,14 +1295,14 @@ describe('IncomingTransactionsController', function () {
value: '15', value: '15',
hash: '0xg', hash: '0xg',
}, },
ROPSTEN_CHAIN_ID, CHAIN_IDS.ROPSTEN,
); );
assert.deepStrictEqual(result, { assert.deepStrictEqual(result, {
blockNumber: 333, blockNumber: 333,
id: 54321, id: 54321,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
status: TRANSACTION_STATUSES.CONFIRMED, status: TRANSACTION_STATUSES.CONFIRMED,
time: 4444000, time: 4444000,
txParams: { txParams: {

@ -8,12 +8,7 @@ import {
TRAITS, TRAITS,
} from '../../../shared/constants/metametrics'; } from '../../../shared/constants/metametrics';
import waitUntilCalled from '../../../test/lib/wait-until-called'; import waitUntilCalled from '../../../test/lib/wait-until-called';
import { import { CHAIN_IDS, CURRENCY_SYMBOLS } from '../../../shared/constants/network';
ETH_SYMBOL,
MAINNET_CHAIN_ID,
ROPSTEN_CHAIN_ID,
TEST_ETH_SYMBOL,
} from '../../../shared/constants/network';
import MetaMetricsController from './metametrics'; import MetaMetricsController from './metametrics';
import { NETWORK_EVENTS } from './network'; import { NETWORK_EVENTS } from './network';
@ -642,8 +637,8 @@ describe('MetaMetricsController', function () {
const metaMetricsController = getMetaMetricsController(); const metaMetricsController = getMetaMetricsController();
const traits = metaMetricsController._buildUserTraitsObject({ const traits = metaMetricsController._buildUserTraitsObject({
addressBook: { addressBook: {
[MAINNET_CHAIN_ID]: [{ address: '0x' }], [CHAIN_IDS.MAINNET]: [{ address: '0x' }],
[ROPSTEN_CHAIN_ID]: [{ address: '0x' }, { address: '0x0' }], [CHAIN_IDS.ROPSTEN]: [{ address: '0x' }, { address: '0x0' }],
}, },
allCollectibles: { allCollectibles: {
'0xac706cE8A9BF27Afecf080fB298d0ee13cfb978A': { '0xac706cE8A9BF27Afecf080fB298d0ee13cfb978A': {
@ -673,8 +668,8 @@ describe('MetaMetricsController', function () {
}, },
allTokens: MOCK_ALL_TOKENS, allTokens: MOCK_ALL_TOKENS,
frequentRpcListDetail: [ frequentRpcListDetail: [
{ chainId: MAINNET_CHAIN_ID, ticker: ETH_SYMBOL }, { chainId: CHAIN_IDS.MAINNET, ticker: CURRENCY_SYMBOLS.ETH },
{ chainId: ROPSTEN_CHAIN_ID, ticker: TEST_ETH_SYMBOL }, { chainId: CHAIN_IDS.ROPSTEN, ticker: CURRENCY_SYMBOLS.TEST_ETH },
{ chainId: '0xaf' }, { chainId: '0xaf' },
], ],
identities: [{}, {}], identities: [{}, {}],
@ -690,7 +685,7 @@ describe('MetaMetricsController', function () {
[TRAITS.ADDRESS_BOOK_ENTRIES]: 3, [TRAITS.ADDRESS_BOOK_ENTRIES]: 3,
[TRAITS.INSTALL_DATE_EXT]: '', [TRAITS.INSTALL_DATE_EXT]: '',
[TRAITS.LEDGER_CONNECTION_TYPE]: 'web-hid', [TRAITS.LEDGER_CONNECTION_TYPE]: 'web-hid',
[TRAITS.NETWORKS_ADDED]: [MAINNET_CHAIN_ID, ROPSTEN_CHAIN_ID, '0xaf'], [TRAITS.NETWORKS_ADDED]: [CHAIN_IDS.MAINNET, CHAIN_IDS.ROPSTEN, '0xaf'],
[TRAITS.NETWORKS_WITHOUT_TICKER]: ['0xaf'], [TRAITS.NETWORKS_WITHOUT_TICKER]: ['0xaf'],
[TRAITS.NFT_AUTODETECTION_ENABLED]: false, [TRAITS.NFT_AUTODETECTION_ENABLED]: false,
[TRAITS.NUMBER_OF_ACCOUNTS]: 2, [TRAITS.NUMBER_OF_ACCOUNTS]: 2,
@ -708,13 +703,13 @@ describe('MetaMetricsController', function () {
const metaMetricsController = getMetaMetricsController(); const metaMetricsController = getMetaMetricsController();
metaMetricsController._buildUserTraitsObject({ metaMetricsController._buildUserTraitsObject({
addressBook: { addressBook: {
[MAINNET_CHAIN_ID]: [{ address: '0x' }], [CHAIN_IDS.MAINNET]: [{ address: '0x' }],
[ROPSTEN_CHAIN_ID]: [{ address: '0x' }, { address: '0x0' }], [CHAIN_IDS.ROPSTEN]: [{ address: '0x' }, { address: '0x0' }],
}, },
allTokens: {}, allTokens: {},
frequentRpcListDetail: [ frequentRpcListDetail: [
{ chainId: MAINNET_CHAIN_ID }, { chainId: CHAIN_IDS.MAINNET },
{ chainId: ROPSTEN_CHAIN_ID }, { chainId: CHAIN_IDS.ROPSTEN },
], ],
ledgerTransportType: 'web-hid', ledgerTransportType: 'web-hid',
openSeaEnabled: true, openSeaEnabled: true,
@ -727,15 +722,15 @@ describe('MetaMetricsController', function () {
const updatedTraits = metaMetricsController._buildUserTraitsObject({ const updatedTraits = metaMetricsController._buildUserTraitsObject({
addressBook: { addressBook: {
[MAINNET_CHAIN_ID]: [{ address: '0x' }, { address: '0x1' }], [CHAIN_IDS.MAINNET]: [{ address: '0x' }, { address: '0x1' }],
[ROPSTEN_CHAIN_ID]: [{ address: '0x' }, { address: '0x0' }], [CHAIN_IDS.ROPSTEN]: [{ address: '0x' }, { address: '0x0' }],
}, },
allTokens: { allTokens: {
'0x1': { '0xabcde': [{ '0x12345': { address: '0xtestAddress' } }] }, '0x1': { '0xabcde': [{ '0x12345': { address: '0xtestAddress' } }] },
}, },
frequentRpcListDetail: [ frequentRpcListDetail: [
{ chainId: MAINNET_CHAIN_ID }, { chainId: CHAIN_IDS.MAINNET },
{ chainId: ROPSTEN_CHAIN_ID }, { chainId: CHAIN_IDS.ROPSTEN },
], ],
ledgerTransportType: 'web-hid', ledgerTransportType: 'web-hid',
openSeaEnabled: false, openSeaEnabled: false,
@ -758,13 +753,13 @@ describe('MetaMetricsController', function () {
const metaMetricsController = getMetaMetricsController(); const metaMetricsController = getMetaMetricsController();
metaMetricsController._buildUserTraitsObject({ metaMetricsController._buildUserTraitsObject({
addressBook: { addressBook: {
[MAINNET_CHAIN_ID]: [{ address: '0x' }], [CHAIN_IDS.MAINNET]: [{ address: '0x' }],
[ROPSTEN_CHAIN_ID]: [{ address: '0x' }, { address: '0x0' }], [CHAIN_IDS.ROPSTEN]: [{ address: '0x' }, { address: '0x0' }],
}, },
allTokens: {}, allTokens: {},
frequentRpcListDetail: [ frequentRpcListDetail: [
{ chainId: MAINNET_CHAIN_ID }, { chainId: CHAIN_IDS.MAINNET },
{ chainId: ROPSTEN_CHAIN_ID }, { chainId: CHAIN_IDS.ROPSTEN },
], ],
ledgerTransportType: 'web-hid', ledgerTransportType: 'web-hid',
openSeaEnabled: true, openSeaEnabled: true,
@ -777,13 +772,13 @@ describe('MetaMetricsController', function () {
const updatedTraits = metaMetricsController._buildUserTraitsObject({ const updatedTraits = metaMetricsController._buildUserTraitsObject({
addressBook: { addressBook: {
[MAINNET_CHAIN_ID]: [{ address: '0x' }], [CHAIN_IDS.MAINNET]: [{ address: '0x' }],
[ROPSTEN_CHAIN_ID]: [{ address: '0x' }, { address: '0x0' }], [CHAIN_IDS.ROPSTEN]: [{ address: '0x' }, { address: '0x0' }],
}, },
allTokens: {}, allTokens: {},
frequentRpcListDetail: [ frequentRpcListDetail: [
{ chainId: MAINNET_CHAIN_ID }, { chainId: CHAIN_IDS.MAINNET },
{ chainId: ROPSTEN_CHAIN_ID }, { chainId: CHAIN_IDS.ROPSTEN },
], ],
ledgerTransportType: 'web-hid', ledgerTransportType: 'web-hid',
openSeaEnabled: true, openSeaEnabled: true,

@ -11,7 +11,7 @@ import {
import createInfuraMiddleware from 'eth-json-rpc-infura'; import createInfuraMiddleware from 'eth-json-rpc-infura';
import { PollingBlockTracker } from 'eth-block-tracker'; import { PollingBlockTracker } from 'eth-block-tracker';
import { NETWORK_TYPE_TO_ID_MAP } from '../../../../shared/constants/network'; import { BUILT_IN_NETWORKS } from '../../../../shared/constants/network';
export default function createInfuraClient({ network, projectId }) { export default function createInfuraClient({ network, projectId }) {
const infuraMiddleware = createInfuraMiddleware({ const infuraMiddleware = createInfuraMiddleware({
@ -36,11 +36,11 @@ export default function createInfuraClient({ network, projectId }) {
} }
function createNetworkAndChainIdMiddleware({ network }) { function createNetworkAndChainIdMiddleware({ network }) {
if (!NETWORK_TYPE_TO_ID_MAP[network]) { if (!BUILT_IN_NETWORKS[network]) {
throw new Error(`createInfuraClient - unknown network "${network}"`); throw new Error(`createInfuraClient - unknown network "${network}"`);
} }
const { chainId, networkId } = NETWORK_TYPE_TO_ID_MAP[network]; const { chainId, networkId } = BUILT_IN_NETWORKS[network];
return createScaffoldMiddleware({ return createScaffoldMiddleware({
eth_chainId: chainId, eth_chainId: chainId,

@ -10,15 +10,12 @@ import {
} from 'swappable-obj-proxy'; } from 'swappable-obj-proxy';
import EthQuery from 'eth-query'; import EthQuery from 'eth-query';
import { import {
RINKEBY,
MAINNET,
INFURA_PROVIDER_TYPES, INFURA_PROVIDER_TYPES,
NETWORK_TYPE_RPC, BUILT_IN_NETWORKS,
NETWORK_TYPE_TO_ID_MAP,
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
INFURA_BLOCKED_KEY, INFURA_BLOCKED_KEY,
TEST_NETWORK_TICKER_MAP, TEST_NETWORK_TICKER_MAP,
CHAIN_IDS,
NETWORK_TYPES,
} from '../../../../shared/constants/network'; } from '../../../../shared/constants/network';
import { import {
isPrefixedFormattedHexString, isPrefixedFormattedHexString,
@ -35,19 +32,22 @@ const fetchWithTimeout = getFetchWithTimeout();
let defaultProviderConfigOpts; let defaultProviderConfigOpts;
if (process.env.IN_TEST) { if (process.env.IN_TEST) {
defaultProviderConfigOpts = { defaultProviderConfigOpts = {
type: NETWORK_TYPE_RPC, type: NETWORK_TYPES.RPC,
rpcUrl: 'http://localhost:8545', rpcUrl: 'http://localhost:8545',
chainId: '0x539', chainId: '0x539',
nickname: 'Localhost 8545', nickname: 'Localhost 8545',
}; };
} else if (process.env.METAMASK_DEBUG || env === 'test') { } else if (process.env.METAMASK_DEBUG || env === 'test') {
defaultProviderConfigOpts = { defaultProviderConfigOpts = {
type: RINKEBY, type: NETWORK_TYPES.RINKEBY,
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
ticker: TEST_NETWORK_TICKER_MAP.rinkeby, ticker: TEST_NETWORK_TICKER_MAP.rinkeby,
}; };
} else { } else {
defaultProviderConfigOpts = { type: MAINNET, chainId: MAINNET_CHAIN_ID }; defaultProviderConfigOpts = {
type: NETWORK_TYPES.MAINNET,
chainId: CHAIN_IDS.MAINNET,
};
} }
const defaultProviderConfig = { const defaultProviderConfig = {
@ -268,7 +268,7 @@ export default class NetworkController extends EventEmitter {
getCurrentChainId() { getCurrentChainId() {
const { type, chainId: configChainId } = this.getProviderConfig(); const { type, chainId: configChainId } = this.getProviderConfig();
return NETWORK_TYPE_TO_ID_MAP[type]?.chainId || configChainId; return BUILT_IN_NETWORKS[type]?.chainId || configChainId;
} }
getCurrentRpcUrl() { getCurrentRpcUrl() {
@ -286,7 +286,7 @@ export default class NetworkController extends EventEmitter {
`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_TYPE_RPC, type: NETWORK_TYPES.RPC,
rpcUrl, rpcUrl,
chainId, chainId,
ticker, ticker,
@ -298,14 +298,14 @@ export default class NetworkController extends EventEmitter {
async setProviderType(type) { async setProviderType(type) {
assert.notStrictEqual( assert.notStrictEqual(
type, type,
NETWORK_TYPE_RPC, NETWORK_TYPES.RPC,
`NetworkController - cannot call "setProviderType" with type "${NETWORK_TYPE_RPC}". Use "setRpcTarget"`, `NetworkController - cannot call "setProviderType" with type "${NETWORK_TYPES.RPC}". Use "setRpcTarget"`,
); );
assert.ok( assert.ok(
INFURA_PROVIDER_TYPES.includes(type), INFURA_PROVIDER_TYPES.includes(type),
`Unknown Infura provider type "${type}".`, `Unknown Infura provider type "${type}".`,
); );
const { chainId, ticker } = NETWORK_TYPE_TO_ID_MAP[type]; const { chainId, ticker } = BUILT_IN_NETWORKS[type];
this.setProviderConfig({ this.setProviderConfig({
type, type,
rpcUrl: '', rpcUrl: '',
@ -342,7 +342,9 @@ export default class NetworkController extends EventEmitter {
getNetworkIdentifier() { getNetworkIdentifier() {
const provider = this.providerStore.getState(); const provider = this.providerStore.getState();
return provider.type === NETWORK_TYPE_RPC ? provider.rpcUrl : provider.type; return provider.type === NETWORK_TYPES.RPC
? provider.rpcUrl
: provider.type;
} }
// //
@ -407,7 +409,7 @@ export default class NetworkController extends EventEmitter {
if (isInfura) { if (isInfura) {
this._configureInfuraProvider(type, this._infuraProjectId); this._configureInfuraProvider(type, this._infuraProjectId);
// url-based rpc endpoints // url-based rpc endpoints
} else if (type === NETWORK_TYPE_RPC) { } else if (type === NETWORK_TYPES.RPC) {
this._configureStandardProvider(rpcUrl, chainId); this._configureStandardProvider(rpcUrl, chainId);
} else { } else {
throw new Error( throw new Error(

@ -5,7 +5,7 @@ import { ethers } from 'ethers';
import log from 'loglevel'; import log from 'loglevel';
import { import {
IPFS_DEFAULT_GATEWAY_URL, IPFS_DEFAULT_GATEWAY_URL,
NETWORK_TYPE_TO_ID_MAP, BUILT_IN_NETWORKS,
} from '../../../shared/constants/network'; } from '../../../shared/constants/network';
import { isPrefixedFormattedHexString } from '../../../shared/modules/network.utils'; import { isPrefixedFormattedHexString } from '../../../shared/modules/network.utils';
import { LEDGER_TRANSPORT_TYPES } from '../../../shared/constants/hardware-wallets'; import { LEDGER_TRANSPORT_TYPES } from '../../../shared/constants/hardware-wallets';
@ -424,9 +424,9 @@ export default class PreferencesController {
// on both networks, since we don't know which network each contact is intended for. // on both networks, since we don't know which network each contact is intended for.
let duplicate = false; let duplicate = false;
const builtInProviderNetworkIds = Object.values( const builtInProviderNetworkIds = Object.values(BUILT_IN_NETWORKS).map(
NETWORK_TYPE_TO_ID_MAP, (ids) => ids.networkId,
).map((ids) => ids.networkId); );
const otherRpcEntries = rpcList.filter( const otherRpcEntries = rpcList.filter(
(entry) => entry.rpcUrl !== newRpcDetails.rpcUrl, (entry) => entry.rpcUrl !== newRpcDetails.rpcUrl,
); );

@ -4,7 +4,7 @@ import {
ControllerMessenger, ControllerMessenger,
TokenListController, TokenListController,
} from '@metamask/controllers'; } from '@metamask/controllers';
import { MAINNET_CHAIN_ID } from '../../../shared/constants/network'; import { CHAIN_IDS } from '../../../shared/constants/network';
import PreferencesController from './preferences'; import PreferencesController from './preferences';
import NetworkController from './network'; import NetworkController from './network';
@ -18,7 +18,7 @@ describe('preferences controller', function () {
beforeEach(function () { beforeEach(function () {
const sandbox = sinon.createSandbox(); const sandbox = sinon.createSandbox();
currentChainId = MAINNET_CHAIN_ID; currentChainId = CHAIN_IDS.MAINNET;
const networkControllerProviderConfig = { const networkControllerProviderConfig = {
getAccounts: () => undefined, getAccounts: () => undefined,
}; };

@ -4,11 +4,7 @@ import sinon from 'sinon';
import { ethers } from 'ethers'; import { ethers } from 'ethers';
import { mapValues } from 'lodash'; import { mapValues } from 'lodash';
import BigNumber from 'bignumber.js'; import BigNumber from 'bignumber.js';
import { import { CHAIN_IDS, NETWORK_IDS } from '../../../shared/constants/network';
ROPSTEN_NETWORK_ID,
MAINNET_NETWORK_ID,
MAINNET_CHAIN_ID,
} from '../../../shared/constants/network';
import { ETH_SWAPS_TOKEN_OBJECT } from '../../../shared/constants/swaps'; import { ETH_SWAPS_TOKEN_OBJECT } from '../../../shared/constants/swaps';
import { createTestProviderTools } from '../../../test/stub/provider'; import { createTestProviderTools } from '../../../test/stub/provider';
import { SECOND } from '../../../shared/constants/time'; import { SECOND } from '../../../shared/constants/time';
@ -82,7 +78,7 @@ const MOCK_FETCH_METADATA = {
symbol: 'FOO', symbol: 'FOO',
decimals: 18, decimals: 18,
}, },
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
}; };
const MOCK_TOKEN_RATES_STORE = () => ({ const MOCK_TOKEN_RATES_STORE = () => ({
@ -104,7 +100,7 @@ function getMockNetworkController() {
store: { store: {
getState: () => { getState: () => {
return { return {
network: ROPSTEN_NETWORK_ID, network: NETWORK_IDS.ROPSTEN,
}; };
}, },
}, },
@ -149,7 +145,7 @@ const EMPTY_INIT_STATE = {
const sandbox = sinon.createSandbox(); const sandbox = sinon.createSandbox();
const fetchTradesInfoStub = sandbox.stub(); const fetchTradesInfoStub = sandbox.stub();
const getCurrentChainIdStub = sandbox.stub(); const getCurrentChainIdStub = sandbox.stub();
getCurrentChainIdStub.returns(MAINNET_CHAIN_ID); getCurrentChainIdStub.returns(CHAIN_IDS.MAINNET);
const getEIP1559GasFeeEstimatesStub = sandbox.stub(() => { const getEIP1559GasFeeEstimatesStub = sandbox.stub(() => {
return { return {
gasFeeEstimates: { gasFeeEstimates: {
@ -225,7 +221,7 @@ describe('SwapsController', function () {
const currentEthersInstance = swapsController.ethersProvider; const currentEthersInstance = swapsController.ethersProvider;
const onNetworkDidChange = networkController.on.getCall(0).args[1]; const onNetworkDidChange = networkController.on.getCall(0).args[1];
onNetworkDidChange(MAINNET_NETWORK_ID); onNetworkDidChange(NETWORK_IDS.MAINNET);
const newEthersInstance = swapsController.ethersProvider; const newEthersInstance = swapsController.ethersProvider;
assert.notStrictEqual( assert.notStrictEqual(
@ -273,7 +269,7 @@ describe('SwapsController', function () {
const currentEthersInstance = swapsController.ethersProvider; const currentEthersInstance = swapsController.ethersProvider;
const onNetworkDidChange = networkController.on.getCall(0).args[1]; const onNetworkDidChange = networkController.on.getCall(0).args[1];
onNetworkDidChange(ROPSTEN_NETWORK_ID); onNetworkDidChange(NETWORK_IDS.ROPSTEN);
const newEthersInstance = swapsController.ethersProvider; const newEthersInstance = swapsController.ethersProvider;
assert.strictEqual( assert.strictEqual(
@ -726,7 +722,7 @@ describe('SwapsController', function () {
allowanceStub.calledOnceWithExactly( allowanceStub.calledOnceWithExactly(
MOCK_FETCH_PARAMS.sourceToken, MOCK_FETCH_PARAMS.sourceToken,
MOCK_FETCH_PARAMS.fromAddress, MOCK_FETCH_PARAMS.fromAddress,
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
), ),
true, true,
); );

@ -46,9 +46,8 @@ import { isSwapsDefaultTokenAddress } from '../../../../shared/modules/swaps.uti
import { EVENT } from '../../../../shared/constants/metametrics'; import { EVENT } from '../../../../shared/constants/metametrics';
import { import {
HARDFORKS, HARDFORKS,
MAINNET,
NETWORK_TYPE_RPC,
CHAIN_ID_TO_GAS_LIMIT_BUFFER_MAP, CHAIN_ID_TO_GAS_LIMIT_BUFFER_MAP,
NETWORK_TYPES,
} from '../../../../shared/constants/network'; } from '../../../../shared/constants/network';
import { import {
determineTransactionAssetType, determineTransactionAssetType,
@ -257,7 +256,7 @@ export default class TransactionController extends EventEmitter {
// type will be one of our default network names or 'rpc'. the default // type will be one of our default network names or 'rpc'. the default
// network names are sufficient configuration, simply pass the name as the // network names are sufficient configuration, simply pass the name as the
// chain argument in the constructor. // chain argument in the constructor.
if (type !== NETWORK_TYPE_RPC) { if (type !== NETWORK_TYPES.RPC) {
return new Common({ return new Common({
chain: type, chain: type,
hardfork, hardfork,
@ -286,7 +285,11 @@ export default class TransactionController extends EventEmitter {
networkId: networkId === 'loading' ? 0 : parseInt(networkId, 10), networkId: networkId === 'loading' ? 0 : parseInt(networkId, 10),
}; };
return Common.forCustomChain(MAINNET, customChainParams, hardfork); return Common.forCustomChain(
NETWORK_TYPES.MAINNET,
customChainParams,
hardfork,
);
} }
/** /**

@ -4,12 +4,7 @@ import {
TRANSACTION_STATUSES, TRANSACTION_STATUSES,
TRANSACTION_TYPES, TRANSACTION_TYPES,
} from '../../../../shared/constants/transaction'; } from '../../../../shared/constants/transaction';
import { import { CHAIN_IDS, NETWORK_IDS } from '../../../../shared/constants/network';
KOVAN_CHAIN_ID,
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
KOVAN_NETWORK_ID,
} from '../../../../shared/constants/network';
import { GAS_LIMITS } from '../../../../shared/constants/gas'; import { GAS_LIMITS } from '../../../../shared/constants/gas';
import { ORIGIN_METAMASK } from '../../../../shared/constants/app'; import { ORIGIN_METAMASK } from '../../../../shared/constants/app';
import TxStateManager, { ERROR_SUBMITTING } from './tx-state-manager'; import TxStateManager, { ERROR_SUBMITTING } from './tx-state-manager';
@ -49,8 +44,8 @@ function generateTransactions(
} }
describe('TransactionStateManager', function () { describe('TransactionStateManager', function () {
let txStateManager; let txStateManager;
const currentNetworkId = KOVAN_NETWORK_ID; const currentNetworkId = NETWORK_IDS.KOVAN;
const currentChainId = KOVAN_CHAIN_ID; const currentChainId = CHAIN_IDS.MAINNET;
const otherNetworkId = '2'; const otherNetworkId = '2';
beforeEach(function () { beforeEach(function () {
@ -681,9 +676,9 @@ describe('TransactionStateManager', function () {
const txs = generateTransactions(limit + 5, { const txs = generateTransactions(limit + 5, {
chainId: (i) => { chainId: (i) => {
if (i === 0 || i === 1) { if (i === 0 || i === 1) {
return MAINNET_CHAIN_ID; return CHAIN_IDS.MAINNET;
} else if (i === 4 || i === 5) { } else if (i === 4 || i === 5) {
return RINKEBY_CHAIN_ID; return CHAIN_IDS.RINKEBY;
} }
return currentChainId; return currentChainId;
}, },
@ -713,7 +708,7 @@ describe('TransactionStateManager', function () {
assert.equal( assert.equal(
result.some( result.some(
(tx) => (tx) =>
tx.chainId === MAINNET_CHAIN_ID && tx.txParams.nonce === '0x0', tx.chainId === CHAIN_IDS.MAINNET && tx.txParams.nonce === '0x0',
), ),
false, false,
'the mainnet transactions with nonce 0x0 should not be present in the result', 'the mainnet transactions with nonce 0x0 should not be present in the result',

@ -14,19 +14,7 @@ import log from 'loglevel';
import pify from 'pify'; import pify from 'pify';
import { ethers } from 'ethers'; import { ethers } from 'ethers';
import SINGLE_CALL_BALANCES_ABI from 'single-call-balance-checker-abi'; import SINGLE_CALL_BALANCES_ABI from 'single-call-balance-checker-abi';
import { import { CHAIN_IDS } from '../../../shared/constants/network';
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID,
KOVAN_CHAIN_ID,
GOERLI_CHAIN_ID,
BSC_CHAIN_ID,
OPTIMISM_CHAIN_ID,
POLYGON_CHAIN_ID,
AVALANCHE_CHAIN_ID,
FANTOM_CHAIN_ID,
ARBITRUM_CHAIN_ID,
} from '../../../shared/constants/network';
import { import {
SINGLE_CALL_BALANCES_ADDRESS, SINGLE_CALL_BALANCES_ADDRESS,
@ -215,77 +203,77 @@ export default class AccountTracker {
const chainId = this.getCurrentChainId(); const chainId = this.getCurrentChainId();
switch (chainId) { switch (chainId) {
case MAINNET_CHAIN_ID: case CHAIN_IDS.MAINNET:
await this._updateAccountsViaBalanceChecker( await this._updateAccountsViaBalanceChecker(
addresses, addresses,
SINGLE_CALL_BALANCES_ADDRESS, SINGLE_CALL_BALANCES_ADDRESS,
); );
break; break;
case RINKEBY_CHAIN_ID: case CHAIN_IDS.RINKEBY:
await this._updateAccountsViaBalanceChecker( await this._updateAccountsViaBalanceChecker(
addresses, addresses,
SINGLE_CALL_BALANCES_ADDRESS_RINKEBY, SINGLE_CALL_BALANCES_ADDRESS_RINKEBY,
); );
break; break;
case ROPSTEN_CHAIN_ID: case CHAIN_IDS.ROPSTEN:
await this._updateAccountsViaBalanceChecker( await this._updateAccountsViaBalanceChecker(
addresses, addresses,
SINGLE_CALL_BALANCES_ADDRESS_ROPSTEN, SINGLE_CALL_BALANCES_ADDRESS_ROPSTEN,
); );
break; break;
case KOVAN_CHAIN_ID: case CHAIN_IDS.KOVAN:
await this._updateAccountsViaBalanceChecker( await this._updateAccountsViaBalanceChecker(
addresses, addresses,
SINGLE_CALL_BALANCES_ADDRESS_KOVAN, SINGLE_CALL_BALANCES_ADDRESS_KOVAN,
); );
break; break;
case GOERLI_CHAIN_ID: case CHAIN_IDS.GOERLI:
await this._updateAccountsViaBalanceChecker( await this._updateAccountsViaBalanceChecker(
addresses, addresses,
SINGLE_CALL_BALANCES_ADDRESS_GOERLI, SINGLE_CALL_BALANCES_ADDRESS_GOERLI,
); );
break; break;
case BSC_CHAIN_ID: case CHAIN_IDS.BSC:
await this._updateAccountsViaBalanceChecker( await this._updateAccountsViaBalanceChecker(
addresses, addresses,
SINGLE_CALL_BALANCES_ADDRESS_BSC, SINGLE_CALL_BALANCES_ADDRESS_BSC,
); );
break; break;
case OPTIMISM_CHAIN_ID: case CHAIN_IDS.OPTIMISM:
await this._updateAccountsViaBalanceChecker( await this._updateAccountsViaBalanceChecker(
addresses, addresses,
SINGLE_CALL_BALANCES_ADDRESS_OPTIMISM, SINGLE_CALL_BALANCES_ADDRESS_OPTIMISM,
); );
break; break;
case POLYGON_CHAIN_ID: case CHAIN_IDS.POLYGON:
await this._updateAccountsViaBalanceChecker( await this._updateAccountsViaBalanceChecker(
addresses, addresses,
SINGLE_CALL_BALANCES_ADDRESS_POLYGON, SINGLE_CALL_BALANCES_ADDRESS_POLYGON,
); );
break; break;
case AVALANCHE_CHAIN_ID: case CHAIN_IDS.AVALANCHE:
await this._updateAccountsViaBalanceChecker( await this._updateAccountsViaBalanceChecker(
addresses, addresses,
SINGLE_CALL_BALANCES_ADDRESS_AVALANCHE, SINGLE_CALL_BALANCES_ADDRESS_AVALANCHE,
); );
break; break;
case FANTOM_CHAIN_ID: case CHAIN_IDS.FANTOM:
await this._updateAccountsViaBalanceChecker( await this._updateAccountsViaBalanceChecker(
addresses, addresses,
SINGLE_CALL_BALANCES_ADDRESS_FANTOM, SINGLE_CALL_BALANCES_ADDRESS_FANTOM,
); );
break; break;
case ARBITRUM_CHAIN_ID: case CHAIN_IDS.ARBITRUM:
await this._updateAccountsViaBalanceChecker( await this._updateAccountsViaBalanceChecker(
addresses, addresses,
SINGLE_CALL_BALANCES_ADDRESS_ARBITRUM, SINGLE_CALL_BALANCES_ADDRESS_ARBITRUM,

@ -2,12 +2,8 @@ import log from 'loglevel';
import { SWAPS_API_V2_BASE_URL } from '../../../shared/constants/swaps'; import { SWAPS_API_V2_BASE_URL } from '../../../shared/constants/swaps';
import { import {
GOERLI_CHAIN_ID,
KOVAN_CHAIN_ID,
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID,
BUYABLE_CHAINS_MAP, BUYABLE_CHAINS_MAP,
CHAIN_IDS,
} from '../../../shared/constants/network'; } from '../../../shared/constants/network';
import getFetchWithTimeout from '../../../shared/modules/fetch-with-timeout'; import getFetchWithTimeout from '../../../shared/modules/fetch-with-timeout';
import { import {
@ -179,15 +175,15 @@ export default async function getBuyUrl({ chainId, address, service }) {
function getDefaultServiceForChain(chainId) { function getDefaultServiceForChain(chainId) {
switch (chainId) { switch (chainId) {
case MAINNET_CHAIN_ID: case CHAIN_IDS.MAINNET:
return 'wyre'; return 'wyre';
case ROPSTEN_CHAIN_ID: case CHAIN_IDS.ROPSTEN:
return 'metamask-faucet'; return 'metamask-faucet';
case RINKEBY_CHAIN_ID: case CHAIN_IDS.RINKEBY:
return 'rinkeby-faucet'; return 'rinkeby-faucet';
case KOVAN_CHAIN_ID: case CHAIN_IDS.KOVAN:
return 'kovan-faucet'; return 'kovan-faucet';
case GOERLI_CHAIN_ID: case CHAIN_IDS.GOERLI:
return 'goerli-faucet'; return 'goerli-faucet';
default: default:
throw new Error( throw new Error(

@ -1,13 +1,8 @@
import nock from 'nock'; import nock from 'nock';
import { import {
KOVAN_CHAIN_ID,
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID,
BSC_CHAIN_ID,
POLYGON_CHAIN_ID,
ETH_SYMBOL,
BUYABLE_CHAINS_MAP, BUYABLE_CHAINS_MAP,
CHAIN_IDS,
CURRENCY_SYMBOLS,
} from '../../../shared/constants/network'; } from '../../../shared/constants/network';
import { TRANSAK_API_KEY, MOONPAY_API_KEY } from '../constants/on-ramp'; import { TRANSAK_API_KEY, MOONPAY_API_KEY } from '../constants/on-ramp';
import { SWAPS_API_V2_BASE_URL } from '../../../shared/constants/swaps'; import { SWAPS_API_V2_BASE_URL } from '../../../shared/constants/swaps';
@ -16,26 +11,26 @@ import getBuyUrl from './buy-url';
const WYRE_ACCOUNT_ID = 'AC-7AG3W4XH4N2'; const WYRE_ACCOUNT_ID = 'AC-7AG3W4XH4N2';
const ETH_ADDRESS = '0x0dcd5d886577d5581b0c524242ef2ee70be3e7bc'; const ETH_ADDRESS = '0x0dcd5d886577d5581b0c524242ef2ee70be3e7bc';
const MAINNET = { const MAINNET = {
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
amount: 5, amount: 5,
address: ETH_ADDRESS, address: ETH_ADDRESS,
}; };
const ROPSTEN = { const ROPSTEN = {
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
}; };
const RINKEBY = { const RINKEBY = {
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
}; };
const KOVAN = { const KOVAN = {
chainId: KOVAN_CHAIN_ID, chainId: CHAIN_IDS.KOVAN,
}; };
const BSC = { const BSC = {
chainId: BSC_CHAIN_ID, chainId: CHAIN_IDS.BSC,
amount: 5, amount: 5,
address: ETH_ADDRESS, address: ETH_ADDRESS,
}; };
const POLYGON = { const POLYGON = {
chainId: POLYGON_CHAIN_ID, chainId: CHAIN_IDS.POLYGON,
amount: 5, amount: 5,
address: ETH_ADDRESS, address: ETH_ADDRESS,
}; };
@ -47,11 +42,11 @@ describe('buy-url', () => {
`/networks/1/fiatOnRampUrl?serviceName=wyre&destinationAddress=${ETH_ADDRESS}`, `/networks/1/fiatOnRampUrl?serviceName=wyre&destinationAddress=${ETH_ADDRESS}`,
) )
.reply(200, { .reply(200, {
url: `https://pay.sendwyre.com/purchase?accountId=${WYRE_ACCOUNT_ID}&utm_campaign=${WYRE_ACCOUNT_ID}&destCurrency=${ETH_SYMBOL}&utm_medium=widget&paymentMethod=debit-card&reservation=MLZVUF8FMXZUMARJC23B&dest=ethereum%3A${ETH_ADDRESS}&utm_source=checkout`, url: `https://pay.sendwyre.com/purchase?accountId=${WYRE_ACCOUNT_ID}&utm_campaign=${WYRE_ACCOUNT_ID}&destCurrency=${CURRENCY_SYMBOLS.ETH}&utm_medium=widget&paymentMethod=debit-card&reservation=MLZVUF8FMXZUMARJC23B&dest=ethereum%3A${ETH_ADDRESS}&utm_source=checkout`,
}); });
const wyreUrl = await getBuyUrl(MAINNET); const wyreUrl = await getBuyUrl(MAINNET);
expect(wyreUrl).toStrictEqual( expect(wyreUrl).toStrictEqual(
`https://pay.sendwyre.com/purchase?accountId=${WYRE_ACCOUNT_ID}&utm_campaign=${WYRE_ACCOUNT_ID}&destCurrency=${ETH_SYMBOL}&utm_medium=widget&paymentMethod=debit-card&reservation=MLZVUF8FMXZUMARJC23B&dest=ethereum%3A${ETH_ADDRESS}&utm_source=checkout`, `https://pay.sendwyre.com/purchase?accountId=${WYRE_ACCOUNT_ID}&utm_campaign=${WYRE_ACCOUNT_ID}&destCurrency=${CURRENCY_SYMBOLS.ETH}&utm_medium=widget&paymentMethod=debit-card&reservation=MLZVUF8FMXZUMARJC23B&dest=ethereum%3A${ETH_ADDRESS}&utm_source=checkout`,
); );
nock.cleanAll(); nock.cleanAll();
}); });
@ -60,7 +55,7 @@ describe('buy-url', () => {
const wyreUrl = await getBuyUrl(MAINNET); const wyreUrl = await getBuyUrl(MAINNET);
expect(wyreUrl).toStrictEqual( expect(wyreUrl).toStrictEqual(
`https://pay.sendwyre.com/purchase?dest=ethereum:${ETH_ADDRESS}&destCurrency=${ETH_SYMBOL}&accountId=${WYRE_ACCOUNT_ID}&paymentMethod=debit-card`, `https://pay.sendwyre.com/purchase?dest=ethereum:${ETH_ADDRESS}&destCurrency=${CURRENCY_SYMBOLS.ETH}&accountId=${WYRE_ACCOUNT_ID}&paymentMethod=debit-card`,
); );
}); });

@ -2,10 +2,10 @@ import { ethErrors } from 'eth-rpc-errors';
import { omit } from 'lodash'; import { omit } from 'lodash';
import { MESSAGE_TYPE } from '../../../../../shared/constants/app'; import { MESSAGE_TYPE } from '../../../../../shared/constants/app';
import { import {
ETH_SYMBOL,
CHAIN_ID_TO_TYPE_MAP, CHAIN_ID_TO_TYPE_MAP,
NETWORK_TO_NAME_MAP, NETWORK_TO_NAME_MAP,
CHAIN_ID_TO_RPC_URL_MAP, CHAIN_ID_TO_RPC_URL_MAP,
CURRENCY_SYMBOLS,
} from '../../../../../shared/constants/network'; } from '../../../../../shared/constants/network';
import { import {
isPrefixedFormattedHexString, isPrefixedFormattedHexString,
@ -29,7 +29,7 @@ function findExistingNetwork(chainId, findCustomRpcBy) {
if (chainId in CHAIN_ID_TO_TYPE_MAP) { if (chainId in CHAIN_ID_TO_TYPE_MAP) {
return { return {
chainId, chainId,
ticker: ETH_SYMBOL, ticker: CURRENCY_SYMBOLS.ETH,
nickname: NETWORK_TO_NAME_MAP[chainId], nickname: NETWORK_TO_NAME_MAP[chainId],
rpcUrl: CHAIN_ID_TO_RPC_URL_MAP[chainId], rpcUrl: CHAIN_ID_TO_RPC_URL_MAP[chainId],
type: CHAIN_ID_TO_TYPE_MAP[chainId], type: CHAIN_ID_TO_TYPE_MAP[chainId],

@ -3,10 +3,7 @@ import browser from 'webextension-polyfill';
import { stripHexPrefix } from 'ethereumjs-util'; import { stripHexPrefix } from 'ethereumjs-util';
import BN from 'bn.js'; import BN from 'bn.js';
import { memoize } from 'lodash'; import { memoize } from 'lodash';
import { import { CHAIN_IDS, TEST_CHAINS } from '../../../shared/constants/network';
MAINNET_CHAIN_ID,
TEST_CHAINS,
} from '../../../shared/constants/network';
import { import {
ENVIRONMENT_TYPE_POPUP, ENVIRONMENT_TYPE_POPUP,
@ -148,7 +145,7 @@ function bnToHex(inputBn) {
} }
function getChainType(chainId) { function getChainType(chainId) {
if (chainId === MAINNET_CHAIN_ID) { if (chainId === CHAIN_IDS.MAINNET) {
return 'mainnet'; return 'mainnet';
} else if (TEST_CHAINS.includes(chainId)) { } else if (TEST_CHAINS.includes(chainId)) {
return 'testnet'; return 'testnet';

@ -65,7 +65,7 @@ import {
GAS_DEV_API_BASE_URL, GAS_DEV_API_BASE_URL,
SWAPS_CLIENT_ID, SWAPS_CLIENT_ID,
} from '../../shared/constants/swaps'; } from '../../shared/constants/swaps';
import { MAINNET_CHAIN_ID } from '../../shared/constants/network'; import { CHAIN_IDS } from '../../shared/constants/network';
import { import {
DEVICE_NAMES, DEVICE_NAMES,
KEYRING_TYPES, KEYRING_TYPES,
@ -431,11 +431,11 @@ export default class MetamaskController extends EventEmitter {
EIP1559APIEndpoint: `${gasApiBaseUrl}/networks/<chain_id>/suggestedGasFees`, EIP1559APIEndpoint: `${gasApiBaseUrl}/networks/<chain_id>/suggestedGasFees`,
getCurrentNetworkLegacyGasAPICompatibility: () => { getCurrentNetworkLegacyGasAPICompatibility: () => {
const chainId = this.networkController.getCurrentChainId(); const chainId = this.networkController.getCurrentChainId();
return process.env.IN_TEST || chainId === MAINNET_CHAIN_ID; return process.env.IN_TEST || chainId === CHAIN_IDS.MAINNET;
}, },
getChainId: () => { getChainId: () => {
return process.env.IN_TEST return process.env.IN_TEST
? MAINNET_CHAIN_ID ? CHAIN_IDS.MAINNET
: this.networkController.getCurrentChainId(); : this.networkController.getCurrentChainId();
}, },
}); });
@ -2262,7 +2262,7 @@ export default class MetamaskController extends EventEmitter {
const isTokenDetectionInactiveInMainnet = const isTokenDetectionInactiveInMainnet =
!useTokenDetection && !useTokenDetection &&
this.networkController.store.getState().provider.chainId === this.networkController.store.getState().provider.chainId ===
MAINNET_CHAIN_ID; CHAIN_IDS.MAINNET;
const { tokenList } = this.tokenListController.state; const { tokenList } = this.tokenListController.state;
const caseInSensitiveTokenList = isTokenDetectionInactiveInMainnet const caseInSensitiveTokenList = isTokenDetectionInactiveInMainnet
? STATIC_MAINNET_TOKEN_LIST ? STATIC_MAINNET_TOKEN_LIST

@ -9,7 +9,7 @@ import proxyquire from 'proxyquire';
import browser from 'webextension-polyfill'; import browser from 'webextension-polyfill';
import { TRANSACTION_STATUSES } from '../../shared/constants/transaction'; import { TRANSACTION_STATUSES } from '../../shared/constants/transaction';
import createTxMeta from '../../test/lib/createTxMeta'; import createTxMeta from '../../test/lib/createTxMeta';
import { NETWORK_TYPE_RPC } from '../../shared/constants/network'; import { NETWORK_TYPES } from '../../shared/constants/network';
import { import {
KEYRING_TYPES, KEYRING_TYPES,
DEVICE_NAMES, DEVICE_NAMES,
@ -24,7 +24,7 @@ const firstTimeState = {
config: {}, config: {},
NetworkController: { NetworkController: {
provider: { provider: {
type: NETWORK_TYPE_RPC, type: NETWORK_TYPES.RPC,
rpcUrl: 'http://localhost:8545', rpcUrl: 'http://localhost:8545',
chainId: '0x539', chainId: '0x539',
}, },

@ -1,5 +1,5 @@
import { cloneDeep } from 'lodash'; import { cloneDeep } from 'lodash';
import { NETWORK_TYPE_TO_ID_MAP } from '../../../shared/constants/network'; import { BUILT_IN_NETWORKS } from '../../../shared/constants/network';
const version = 51; const version = 51;
@ -19,7 +19,7 @@ export default {
function transformState(state) { function transformState(state) {
const { chainId, type } = state?.NetworkController?.provider || {}; const { chainId, type } = state?.NetworkController?.provider || {};
const enumChainId = NETWORK_TYPE_TO_ID_MAP[type]?.chainId; const enumChainId = BUILT_IN_NETWORKS[type]?.chainId;
if (enumChainId && chainId !== enumChainId) { if (enumChainId && chainId !== enumChainId) {
state.NetworkController.provider.chainId = enumChainId; state.NetworkController.provider.chainId = enumChainId;

@ -1,6 +1,6 @@
import { import {
INFURA_PROVIDER_TYPES, INFURA_PROVIDER_TYPES,
NETWORK_TYPE_TO_ID_MAP, BUILT_IN_NETWORKS,
} from '../../../shared/constants/network'; } from '../../../shared/constants/network';
import migration51 from './051'; import migration51 from './051';
@ -44,7 +44,7 @@ describe('migration #51', () => {
}, },
provider: { provider: {
type, type,
chainId: NETWORK_TYPE_TO_ID_MAP[type].chainId, chainId: BUILT_IN_NETWORKS[type].chainId,
}, },
}, },
foo: 'bar', foo: 'bar',
@ -75,7 +75,7 @@ describe('migration #51', () => {
}, },
provider: { provider: {
type, type,
chainId: NETWORK_TYPE_TO_ID_MAP[type].chainId, chainId: BUILT_IN_NETWORKS[type].chainId,
}, },
}, },
foo: 'bar', foo: 'bar',

@ -1,17 +1,5 @@
import { cloneDeep } from 'lodash'; import { cloneDeep } from 'lodash';
import { import { CHAIN_IDS, NETWORK_TYPES } from '../../../shared/constants/network';
GOERLI,
GOERLI_CHAIN_ID,
KOVAN,
KOVAN_CHAIN_ID,
MAINNET,
MAINNET_CHAIN_ID,
NETWORK_TYPE_RPC,
RINKEBY,
RINKEBY_CHAIN_ID,
ROPSTEN,
ROPSTEN_CHAIN_ID,
} from '../../../shared/constants/network';
const version = 52; const version = 52;
@ -43,33 +31,33 @@ function transformState(state = {}) {
if (accountTokens && Object.keys(accountTokens).length > 0) { if (accountTokens && Object.keys(accountTokens).length > 0) {
for (const address of Object.keys(accountTokens)) { for (const address of Object.keys(accountTokens)) {
newAccountTokens[address] = {}; newAccountTokens[address] = {};
if (accountTokens[address][NETWORK_TYPE_RPC]) { if (accountTokens[address][NETWORK_TYPES.RPC]) {
frequentRpcListDetail.forEach((detail) => { frequentRpcListDetail.forEach((detail) => {
newAccountTokens[address][detail.chainId] = newAccountTokens[address][detail.chainId] =
accountTokens[address][NETWORK_TYPE_RPC]; accountTokens[address][NETWORK_TYPES.RPC];
}); });
} }
for (const providerType of Object.keys(accountTokens[address])) { for (const providerType of Object.keys(accountTokens[address])) {
switch (providerType) { switch (providerType) {
case MAINNET: case NETWORK_TYPES.MAINNET:
newAccountTokens[address][MAINNET_CHAIN_ID] = newAccountTokens[address][CHAIN_IDS.MAINNET] =
accountTokens[address][MAINNET]; accountTokens[address][NETWORK_TYPES.MAINNET];
break; break;
case ROPSTEN: case NETWORK_TYPES.ROPSTEN:
newAccountTokens[address][ROPSTEN_CHAIN_ID] = newAccountTokens[address][CHAIN_IDS.ROPSTEN] =
accountTokens[address][ROPSTEN]; accountTokens[address][NETWORK_TYPES.ROPSTEN];
break; break;
case RINKEBY: case NETWORK_TYPES.RINKEBY:
newAccountTokens[address][RINKEBY_CHAIN_ID] = newAccountTokens[address][CHAIN_IDS.RINKEBY] =
accountTokens[address][RINKEBY]; accountTokens[address][NETWORK_TYPES.RINKEBY];
break; break;
case GOERLI: case NETWORK_TYPES.GOERLI:
newAccountTokens[address][GOERLI_CHAIN_ID] = newAccountTokens[address][CHAIN_IDS.GOERLI] =
accountTokens[address][GOERLI]; accountTokens[address][NETWORK_TYPES.GOERLI];
break; break;
case KOVAN: case NETWORK_TYPES.KOVAN:
newAccountTokens[address][KOVAN_CHAIN_ID] = newAccountTokens[address][CHAIN_IDS.KOVAN] =
accountTokens[address][KOVAN]; accountTokens[address][NETWORK_TYPES.KOVAN];
break; break;
default: default:
break; break;
@ -82,33 +70,33 @@ function transformState(state = {}) {
if (accountHiddenTokens && Object.keys(accountHiddenTokens).length > 0) { if (accountHiddenTokens && Object.keys(accountHiddenTokens).length > 0) {
for (const address of Object.keys(accountHiddenTokens)) { for (const address of Object.keys(accountHiddenTokens)) {
newAccountHiddenTokens[address] = {}; newAccountHiddenTokens[address] = {};
if (accountHiddenTokens[address][NETWORK_TYPE_RPC]) { if (accountHiddenTokens[address][NETWORK_TYPES.RPC]) {
frequentRpcListDetail.forEach((detail) => { frequentRpcListDetail.forEach((detail) => {
newAccountHiddenTokens[address][detail.chainId] = newAccountHiddenTokens[address][detail.chainId] =
accountHiddenTokens[address][NETWORK_TYPE_RPC]; accountHiddenTokens[address][NETWORK_TYPES.RPC];
}); });
} }
for (const providerType of Object.keys(accountHiddenTokens[address])) { for (const providerType of Object.keys(accountHiddenTokens[address])) {
switch (providerType) { switch (providerType) {
case MAINNET: case NETWORK_TYPES.MAINNET:
newAccountHiddenTokens[address][MAINNET_CHAIN_ID] = newAccountHiddenTokens[address][CHAIN_IDS.MAINNET] =
accountHiddenTokens[address][MAINNET]; accountHiddenTokens[address][NETWORK_TYPES.MAINNET];
break; break;
case ROPSTEN: case NETWORK_TYPES.ROPSTEN:
newAccountHiddenTokens[address][ROPSTEN_CHAIN_ID] = newAccountHiddenTokens[address][CHAIN_IDS.ROPSTEN] =
accountHiddenTokens[address][ROPSTEN]; accountHiddenTokens[address][NETWORK_TYPES.ROPSTEN];
break; break;
case RINKEBY: case NETWORK_TYPES.RINKEBY:
newAccountHiddenTokens[address][RINKEBY_CHAIN_ID] = newAccountHiddenTokens[address][CHAIN_IDS.RINKEBY] =
accountHiddenTokens[address][RINKEBY]; accountHiddenTokens[address][NETWORK_TYPES.RINKEBY];
break; break;
case GOERLI: case NETWORK_TYPES.GOERLI:
newAccountHiddenTokens[address][GOERLI_CHAIN_ID] = newAccountHiddenTokens[address][CHAIN_IDS.GOERLI] =
accountHiddenTokens[address][GOERLI]; accountHiddenTokens[address][NETWORK_TYPES.GOERLI];
break; break;
case KOVAN: case NETWORK_TYPES.KOVAN:
newAccountHiddenTokens[address][KOVAN_CHAIN_ID] = newAccountHiddenTokens[address][CHAIN_IDS.KOVAN] =
accountHiddenTokens[address][KOVAN]; accountHiddenTokens[address][NETWORK_TYPES.KOVAN];
break; break;
default: default:
break; break;

@ -1,16 +1,4 @@
import { import { CHAIN_IDS, NETWORK_TYPES } from '../../../shared/constants/network';
GOERLI,
GOERLI_CHAIN_ID,
KOVAN,
KOVAN_CHAIN_ID,
MAINNET,
MAINNET_CHAIN_ID,
NETWORK_TYPE_RPC,
RINKEBY,
RINKEBY_CHAIN_ID,
ROPSTEN,
ROPSTEN_CHAIN_ID,
} from '../../../shared/constants/network';
import migration52 from './052'; import migration52 from './052';
const TOKEN1 = { symbol: 'TST', address: '0x10', decimals: 18 }; const TOKEN1 = { symbol: 'TST', address: '0x10', decimals: 18 };
@ -33,25 +21,25 @@ describe('migration #52', () => {
}); });
}); });
it(`should move ${MAINNET} tokens and hidden tokens to be keyed by ${MAINNET_CHAIN_ID} for each address`, async () => { it(`should move ${NETWORK_TYPES.MAINNET} tokens and hidden tokens to be keyed by ${CHAIN_IDS.MAINNET} for each address`, async () => {
const oldStorage = { const oldStorage = {
meta: {}, meta: {},
data: { data: {
PreferencesController: { PreferencesController: {
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[MAINNET]: [TOKEN1], [NETWORK_TYPES.MAINNET]: [TOKEN1],
}, },
'0x1112': { '0x1112': {
[MAINNET]: [TOKEN3], [NETWORK_TYPES.MAINNET]: [TOKEN3],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[MAINNET]: [TOKEN1, TOKEN2], [NETWORK_TYPES.MAINNET]: [TOKEN1, TOKEN2],
}, },
'0x1112': { '0x1112': {
[MAINNET]: [TOKEN1, TOKEN3], [NETWORK_TYPES.MAINNET]: [TOKEN1, TOKEN3],
}, },
}, },
bar: 'baz', bar: 'baz',
@ -65,18 +53,18 @@ describe('migration #52', () => {
PreferencesController: { PreferencesController: {
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[MAINNET_CHAIN_ID]: [TOKEN1], [CHAIN_IDS.MAINNET]: [TOKEN1],
}, },
'0x1112': { '0x1112': {
[MAINNET_CHAIN_ID]: [TOKEN3], [CHAIN_IDS.MAINNET]: [TOKEN3],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[MAINNET_CHAIN_ID]: [TOKEN1, TOKEN2], [CHAIN_IDS.MAINNET]: [TOKEN1, TOKEN2],
}, },
'0x1112': { '0x1112': {
[MAINNET_CHAIN_ID]: [TOKEN1, TOKEN3], [CHAIN_IDS.MAINNET]: [TOKEN1, TOKEN3],
}, },
}, },
bar: 'baz', bar: 'baz',
@ -85,25 +73,25 @@ describe('migration #52', () => {
}); });
}); });
it(`should move ${RINKEBY} tokens and hidden tokens to be keyed by ${RINKEBY_CHAIN_ID} for each address`, async () => { it(`should move ${NETWORK_TYPES.RINKEBY} tokens and hidden tokens to be keyed by ${CHAIN_IDS.RINKEBY} for each address`, async () => {
const oldStorage = { const oldStorage = {
meta: {}, meta: {},
data: { data: {
PreferencesController: { PreferencesController: {
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[RINKEBY]: [TOKEN1], [NETWORK_TYPES.RINKEBY]: [TOKEN1],
}, },
'0x1112': { '0x1112': {
[RINKEBY]: [TOKEN3], [NETWORK_TYPES.RINKEBY]: [TOKEN3],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[RINKEBY]: [TOKEN1, TOKEN2], [NETWORK_TYPES.RINKEBY]: [TOKEN1, TOKEN2],
}, },
'0x1112': { '0x1112': {
[RINKEBY]: [TOKEN1, TOKEN3], [NETWORK_TYPES.RINKEBY]: [TOKEN1, TOKEN3],
}, },
}, },
bar: 'baz', bar: 'baz',
@ -117,18 +105,18 @@ describe('migration #52', () => {
PreferencesController: { PreferencesController: {
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[RINKEBY_CHAIN_ID]: [TOKEN1], [CHAIN_IDS.RINKEBY]: [TOKEN1],
}, },
'0x1112': { '0x1112': {
[RINKEBY_CHAIN_ID]: [TOKEN3], [CHAIN_IDS.RINKEBY]: [TOKEN3],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[RINKEBY_CHAIN_ID]: [TOKEN1, TOKEN2], [CHAIN_IDS.RINKEBY]: [TOKEN1, TOKEN2],
}, },
'0x1112': { '0x1112': {
[RINKEBY_CHAIN_ID]: [TOKEN1, TOKEN3], [CHAIN_IDS.RINKEBY]: [TOKEN1, TOKEN3],
}, },
}, },
bar: 'baz', bar: 'baz',
@ -137,25 +125,25 @@ describe('migration #52', () => {
}); });
}); });
it(`should move ${KOVAN} tokens and hidden tokens to be keyed by ${KOVAN_CHAIN_ID} for each address`, async () => { it(`should move ${NETWORK_TYPES.KOVAN} tokens and hidden tokens to be keyed by ${CHAIN_IDS.KOVAN} for each address`, async () => {
const oldStorage = { const oldStorage = {
meta: {}, meta: {},
data: { data: {
PreferencesController: { PreferencesController: {
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[KOVAN]: [TOKEN1], [NETWORK_TYPES.KOVAN]: [TOKEN1],
}, },
'0x1112': { '0x1112': {
[KOVAN]: [TOKEN3], [NETWORK_TYPES.KOVAN]: [TOKEN3],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[KOVAN]: [TOKEN1, TOKEN2], [NETWORK_TYPES.KOVAN]: [TOKEN1, TOKEN2],
}, },
'0x1112': { '0x1112': {
[KOVAN]: [TOKEN1, TOKEN3], [NETWORK_TYPES.KOVAN]: [TOKEN1, TOKEN3],
}, },
}, },
bar: 'baz', bar: 'baz',
@ -169,18 +157,18 @@ describe('migration #52', () => {
PreferencesController: { PreferencesController: {
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[KOVAN_CHAIN_ID]: [TOKEN1], [CHAIN_IDS.KOVAN]: [TOKEN1],
}, },
'0x1112': { '0x1112': {
[KOVAN_CHAIN_ID]: [TOKEN3], [CHAIN_IDS.KOVAN]: [TOKEN3],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[KOVAN_CHAIN_ID]: [TOKEN1, TOKEN2], [CHAIN_IDS.KOVAN]: [TOKEN1, TOKEN2],
}, },
'0x1112': { '0x1112': {
[KOVAN_CHAIN_ID]: [TOKEN1, TOKEN3], [CHAIN_IDS.KOVAN]: [TOKEN1, TOKEN3],
}, },
}, },
bar: 'baz', bar: 'baz',
@ -189,25 +177,25 @@ describe('migration #52', () => {
}); });
}); });
it(`should move ${GOERLI} tokens and hidden tokens to be keyed by ${GOERLI_CHAIN_ID} for each address`, async () => { it(`should move ${NETWORK_TYPES.GOERLI} tokens and hidden tokens to be keyed by ${CHAIN_IDS.GOERLI} for each address`, async () => {
const oldStorage = { const oldStorage = {
meta: {}, meta: {},
data: { data: {
PreferencesController: { PreferencesController: {
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[GOERLI]: [TOKEN1], [NETWORK_TYPES.GOERLI]: [TOKEN1],
}, },
'0x1112': { '0x1112': {
[GOERLI]: [TOKEN3], [NETWORK_TYPES.GOERLI]: [TOKEN3],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[GOERLI]: [TOKEN1, TOKEN2], [NETWORK_TYPES.GOERLI]: [TOKEN1, TOKEN2],
}, },
'0x1112': { '0x1112': {
[GOERLI]: [TOKEN1, TOKEN3], [NETWORK_TYPES.GOERLI]: [TOKEN1, TOKEN3],
}, },
}, },
bar: 'baz', bar: 'baz',
@ -221,18 +209,18 @@ describe('migration #52', () => {
PreferencesController: { PreferencesController: {
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[GOERLI_CHAIN_ID]: [TOKEN1], [CHAIN_IDS.GOERLI]: [TOKEN1],
}, },
'0x1112': { '0x1112': {
[GOERLI_CHAIN_ID]: [TOKEN3], [CHAIN_IDS.GOERLI]: [TOKEN3],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[GOERLI_CHAIN_ID]: [TOKEN1, TOKEN2], [CHAIN_IDS.GOERLI]: [TOKEN1, TOKEN2],
}, },
'0x1112': { '0x1112': {
[GOERLI_CHAIN_ID]: [TOKEN1, TOKEN3], [CHAIN_IDS.GOERLI]: [TOKEN1, TOKEN3],
}, },
}, },
bar: 'baz', bar: 'baz',
@ -241,25 +229,25 @@ describe('migration #52', () => {
}); });
}); });
it(`should move ${ROPSTEN} tokens and hidden tokens to be keyed by ${ROPSTEN_CHAIN_ID} for each address`, async () => { it(`should move ${NETWORK_TYPES.ROPSTEN} tokens and hidden tokens to be keyed by ${CHAIN_IDS.ROPSTEN} for each address`, async () => {
const oldStorage = { const oldStorage = {
meta: {}, meta: {},
data: { data: {
PreferencesController: { PreferencesController: {
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[ROPSTEN]: [TOKEN1], [NETWORK_TYPES.ROPSTEN]: [TOKEN1],
}, },
'0x1112': { '0x1112': {
[ROPSTEN]: [TOKEN3], [NETWORK_TYPES.ROPSTEN]: [TOKEN3],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[ROPSTEN]: [TOKEN1, TOKEN2], [NETWORK_TYPES.ROPSTEN]: [TOKEN1, TOKEN2],
}, },
'0x1112': { '0x1112': {
[ROPSTEN]: [TOKEN1, TOKEN3], [NETWORK_TYPES.ROPSTEN]: [TOKEN1, TOKEN3],
}, },
}, },
bar: 'baz', bar: 'baz',
@ -273,18 +261,18 @@ describe('migration #52', () => {
PreferencesController: { PreferencesController: {
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[ROPSTEN_CHAIN_ID]: [TOKEN1], [CHAIN_IDS.ROPSTEN]: [TOKEN1],
}, },
'0x1112': { '0x1112': {
[ROPSTEN_CHAIN_ID]: [TOKEN3], [CHAIN_IDS.ROPSTEN]: [TOKEN3],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[ROPSTEN_CHAIN_ID]: [TOKEN1, TOKEN2], [CHAIN_IDS.ROPSTEN]: [TOKEN1, TOKEN2],
}, },
'0x1112': { '0x1112': {
[ROPSTEN_CHAIN_ID]: [TOKEN1, TOKEN3], [CHAIN_IDS.ROPSTEN]: [TOKEN1, TOKEN3],
}, },
}, },
bar: 'baz', bar: 'baz',
@ -293,7 +281,7 @@ describe('migration #52', () => {
}); });
}); });
it(`should duplicate ${NETWORK_TYPE_RPC} tokens and hidden tokens to all custom networks for each address`, async () => { it(`should duplicate ${NETWORK_TYPES.RPC} tokens and hidden tokens to all custom networks for each address`, async () => {
const oldStorage = { const oldStorage = {
meta: {}, meta: {},
data: { data: {
@ -305,18 +293,18 @@ describe('migration #52', () => {
], ],
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[NETWORK_TYPE_RPC]: [TOKEN1], [NETWORK_TYPES.RPC]: [TOKEN1],
}, },
'0x1112': { '0x1112': {
[NETWORK_TYPE_RPC]: [TOKEN3], [NETWORK_TYPES.RPC]: [TOKEN3],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[NETWORK_TYPE_RPC]: [TOKEN1, TOKEN2], [NETWORK_TYPES.RPC]: [TOKEN1, TOKEN2],
}, },
'0x1112': { '0x1112': {
[NETWORK_TYPE_RPC]: [TOKEN1, TOKEN3], [NETWORK_TYPES.RPC]: [TOKEN1, TOKEN3],
}, },
}, },
bar: 'baz', bar: 'baz',
@ -363,7 +351,7 @@ describe('migration #52', () => {
}); });
}); });
it(`should overwrite ${NETWORK_TYPE_RPC} tokens with built in networks if chainIds match`, async () => { it(`should overwrite ${NETWORK_TYPES.RPC} tokens with built in networks if chainIds match`, async () => {
const oldStorage = { const oldStorage = {
meta: {}, meta: {},
data: { data: {
@ -371,14 +359,14 @@ describe('migration #52', () => {
frequentRpcListDetail: [{ chainId: '0x1' }], frequentRpcListDetail: [{ chainId: '0x1' }],
accountHiddenTokens: { accountHiddenTokens: {
'0x1111': { '0x1111': {
[NETWORK_TYPE_RPC]: [TOKEN3], [NETWORK_TYPES.RPC]: [TOKEN3],
[MAINNET]: [TOKEN1], [NETWORK_TYPES.MAINNET]: [TOKEN1],
}, },
}, },
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[NETWORK_TYPE_RPC]: [TOKEN1, TOKEN2], [NETWORK_TYPES.RPC]: [TOKEN1, TOKEN2],
[MAINNET]: [TOKEN3, TOKEN4], [NETWORK_TYPES.MAINNET]: [TOKEN3, TOKEN4],
}, },
}, },
bar: 'baz', bar: 'baz',

@ -1,7 +1,4 @@
import { import { CHAIN_IDS } from '../../../shared/constants/network';
MAINNET_CHAIN_ID,
ROPSTEN_CHAIN_ID,
} from '../../../shared/constants/network';
import migration54 from './054'; import migration54 from './054';
describe('migration #54', () => { describe('migration #54', () => {
@ -150,7 +147,7 @@ describe('migration #54', () => {
PreferencesController: { PreferencesController: {
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[MAINNET_CHAIN_ID]: [ [CHAIN_IDS.MAINNET]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: '0', decimals: '0',
@ -174,7 +171,7 @@ describe('migration #54', () => {
], ],
}, },
'0x1112': { '0x1112': {
[ROPSTEN_CHAIN_ID]: [ [CHAIN_IDS.ROPSTEN]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: '0', decimals: '0',
@ -208,7 +205,7 @@ describe('migration #54', () => {
PreferencesController: { PreferencesController: {
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[MAINNET_CHAIN_ID]: [ [CHAIN_IDS.MAINNET]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: 0, decimals: 0,
@ -232,7 +229,7 @@ describe('migration #54', () => {
], ],
}, },
'0x1112': { '0x1112': {
[ROPSTEN_CHAIN_ID]: [ [CHAIN_IDS.ROPSTEN]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: 0, decimals: 0,
@ -268,7 +265,7 @@ describe('migration #54', () => {
PreferencesController: { PreferencesController: {
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[MAINNET_CHAIN_ID]: [ [CHAIN_IDS.MAINNET]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: 0, decimals: 0,
@ -292,7 +289,7 @@ describe('migration #54', () => {
], ],
}, },
'0x1112': { '0x1112': {
[ROPSTEN_CHAIN_ID]: [ [CHAIN_IDS.ROPSTEN]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: 0, decimals: 0,
@ -326,7 +323,7 @@ describe('migration #54', () => {
PreferencesController: { PreferencesController: {
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[MAINNET_CHAIN_ID]: [ [CHAIN_IDS.MAINNET]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: 0, decimals: 0,
@ -350,7 +347,7 @@ describe('migration #54', () => {
], ],
}, },
'0x1112': { '0x1112': {
[ROPSTEN_CHAIN_ID]: [ [CHAIN_IDS.ROPSTEN]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: 0, decimals: 0,
@ -386,7 +383,7 @@ describe('migration #54', () => {
PreferencesController: { PreferencesController: {
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[MAINNET_CHAIN_ID]: [ [CHAIN_IDS.MAINNET]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: '0', decimals: '0',
@ -410,7 +407,7 @@ describe('migration #54', () => {
], ],
}, },
'0x1112': { '0x1112': {
[ROPSTEN_CHAIN_ID]: [ [CHAIN_IDS.ROPSTEN]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: '0', decimals: '0',
@ -465,7 +462,7 @@ describe('migration #54', () => {
PreferencesController: { PreferencesController: {
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[MAINNET_CHAIN_ID]: [ [CHAIN_IDS.MAINNET]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: 0, decimals: 0,
@ -489,7 +486,7 @@ describe('migration #54', () => {
], ],
}, },
'0x1112': { '0x1112': {
[ROPSTEN_CHAIN_ID]: [ [CHAIN_IDS.ROPSTEN]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: 0, decimals: 0,
@ -546,7 +543,7 @@ describe('migration #54', () => {
PreferencesController: { PreferencesController: {
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[MAINNET_CHAIN_ID]: [ [CHAIN_IDS.MAINNET]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: '', decimals: '',
@ -570,7 +567,7 @@ describe('migration #54', () => {
], ],
}, },
'0x1112': { '0x1112': {
[ROPSTEN_CHAIN_ID]: [ [CHAIN_IDS.ROPSTEN]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: '0', decimals: '0',
@ -625,7 +622,7 @@ describe('migration #54', () => {
PreferencesController: { PreferencesController: {
accountTokens: { accountTokens: {
'0x1111': { '0x1111': {
[MAINNET_CHAIN_ID]: [ [CHAIN_IDS.MAINNET]: [
{ {
address: '0x0d8775f648430679a709e98d2b0cb6250d2887ef', address: '0x0d8775f648430679a709e98d2b0cb6250d2887ef',
decimals: 18, decimals: 18,
@ -644,7 +641,7 @@ describe('migration #54', () => {
], ],
}, },
'0x1112': { '0x1112': {
[ROPSTEN_CHAIN_ID]: [ [CHAIN_IDS.ROPSTEN]: [
{ {
address: '0x06012c8cf97bead5deae237070f9587f8e7a266d', address: '0x06012c8cf97bead5deae237070f9587f8e7a266d',
decimals: 0, decimals: 0,

@ -1,5 +1,5 @@
import { cloneDeep, mapKeys } from 'lodash'; import { cloneDeep, mapKeys } from 'lodash';
import { NETWORK_TYPE_TO_ID_MAP } from '../../../shared/constants/network'; import { BUILT_IN_NETWORKS } from '../../../shared/constants/network';
const version = 55; const version = 55;
@ -30,8 +30,7 @@ function transformState(state) {
// using optional chaining in case user's state has fetched blocks for // using optional chaining in case user's state has fetched blocks for
// RPC network types (which don't map to a single chainId). This should // RPC network types (which don't map to a single chainId). This should
// not be possible, but it's safer // not be possible, but it's safer
(_, key) => (_, key) => BUILT_IN_NETWORKS[key]?.chainId ?? UNKNOWN_CHAIN_ID_KEY,
NETWORK_TYPE_TO_ID_MAP[key]?.chainId ?? UNKNOWN_CHAIN_ID_KEY,
); );
// Now that mainnet and test net last fetched blocks are keyed by their // Now that mainnet and test net last fetched blocks are keyed by their
// respective chainIds, we can safely delete anything we had for custom // respective chainIds, we can safely delete anything we had for custom

@ -1,15 +1,4 @@
import { import { CHAIN_IDS, NETWORK_TYPES } from '../../../shared/constants/network';
GOERLI,
GOERLI_CHAIN_ID,
KOVAN,
KOVAN_CHAIN_ID,
MAINNET,
MAINNET_CHAIN_ID,
RINKEBY,
RINKEBY_CHAIN_ID,
ROPSTEN,
ROPSTEN_CHAIN_ID,
} from '../../../shared/constants/network';
import migration55 from './055'; import migration55 from './055';
describe('migration #55', () => { describe('migration #55', () => {
@ -41,11 +30,11 @@ describe('migration #55', () => {
}, },
}, },
incomingTxLastFetchedBlocksByNetwork: { incomingTxLastFetchedBlocksByNetwork: {
[MAINNET]: 1, [NETWORK_TYPES.MAINNET]: 1,
[ROPSTEN]: 2, [NETWORK_TYPES.ROPSTEN]: 2,
[RINKEBY]: 3, [NETWORK_TYPES.RINKEBY]: 3,
[GOERLI]: 4, [NETWORK_TYPES.GOERLI]: 4,
[KOVAN]: 5, [NETWORK_TYPES.KOVAN]: 5,
}, },
}, },
foo: 'bar', foo: 'bar',
@ -58,11 +47,11 @@ describe('migration #55', () => {
incomingTransactions: incomingTransactions:
oldStorage.data.IncomingTransactionsController.incomingTransactions, oldStorage.data.IncomingTransactionsController.incomingTransactions,
incomingTxLastFetchedBlockByChainId: { incomingTxLastFetchedBlockByChainId: {
[MAINNET_CHAIN_ID]: 1, [CHAIN_IDS.MAINNET]: 1,
[ROPSTEN_CHAIN_ID]: 2, [CHAIN_IDS.ROPSTEN]: 2,
[RINKEBY_CHAIN_ID]: 3, [CHAIN_IDS.RINKEBY]: 3,
[GOERLI_CHAIN_ID]: 4, [CHAIN_IDS.GOERLI]: 4,
[KOVAN_CHAIN_ID]: 5, [CHAIN_IDS.KOVAN]: 5,
}, },
}, },
foo: 'bar', foo: 'bar',

@ -1,10 +1,5 @@
import { cloneDeep } from 'lodash'; import { cloneDeep } from 'lodash';
import { import { CHAIN_IDS } from '../../../shared/constants/network';
KOVAN_CHAIN_ID,
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
GOERLI_CHAIN_ID,
} from '../../../shared/constants/network';
import { import {
TRANSACTION_TYPES, TRANSACTION_TYPES,
TRANSACTION_STATUSES, TRANSACTION_STATUSES,
@ -17,7 +12,7 @@ const ERRONEOUS_TRANSACTION_STATE = {
0: { 0: {
type: TRANSACTION_TYPES.CANCEL, type: TRANSACTION_TYPES.CANCEL,
id: 0, id: 0,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
txParams: { txParams: {
nonce: '0x0', nonce: '0x0',
}, },
@ -25,7 +20,7 @@ const ERRONEOUS_TRANSACTION_STATE = {
1: { 1: {
type: SENT_ETHER, type: SENT_ETHER,
id: 1, id: 1,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
txParams: { txParams: {
nonce: '0x1', nonce: '0x1',
}, },
@ -33,7 +28,7 @@ const ERRONEOUS_TRANSACTION_STATE = {
2: { 2: {
type: SENT_ETHER, type: SENT_ETHER,
id: 2, id: 2,
chainId: KOVAN_CHAIN_ID, chainId: CHAIN_IDS.KOVAN,
txParams: { txParams: {
nonce: '0x2', nonce: '0x2',
}, },
@ -41,7 +36,7 @@ const ERRONEOUS_TRANSACTION_STATE = {
3: { 3: {
type: SENT_ETHER, type: SENT_ETHER,
id: 3, id: 3,
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
txParams: { txParams: {
nonce: '0x3', nonce: '0x3',
}, },
@ -49,7 +44,7 @@ const ERRONEOUS_TRANSACTION_STATE = {
4: { 4: {
type: SENT_ETHER, type: SENT_ETHER,
id: 4, id: 4,
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
txParams: { txParams: {
nonce: '0x4', nonce: '0x4',
}, },
@ -57,7 +52,7 @@ const ERRONEOUS_TRANSACTION_STATE = {
5: { 5: {
type: SENT_ETHER, type: SENT_ETHER,
id: 5, id: 5,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
txParams: { txParams: {
nonce: '0x5', nonce: '0x5',
}, },
@ -65,7 +60,7 @@ const ERRONEOUS_TRANSACTION_STATE = {
6: { 6: {
type: SENT_ETHER, type: SENT_ETHER,
id: 6, id: 6,
chainId: KOVAN_CHAIN_ID, chainId: CHAIN_IDS.KOVAN,
txParams: { txParams: {
nonce: '0x6', nonce: '0x6',
}, },
@ -73,7 +68,7 @@ const ERRONEOUS_TRANSACTION_STATE = {
7: { 7: {
type: SENT_ETHER, type: SENT_ETHER,
id: 7, id: 7,
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
txParams: { txParams: {
nonce: '0x7', nonce: '0x7',
}, },
@ -81,7 +76,7 @@ const ERRONEOUS_TRANSACTION_STATE = {
8: { 8: {
type: SENT_ETHER, type: SENT_ETHER,
id: 8, id: 8,
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
txParams: { txParams: {
nonce: '0x8', nonce: '0x8',
}, },
@ -89,7 +84,7 @@ const ERRONEOUS_TRANSACTION_STATE = {
9: { 9: {
type: SENT_ETHER, type: SENT_ETHER,
id: 9, id: 9,
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
status: TRANSACTION_STATUSES.UNAPPROVED, status: TRANSACTION_STATUSES.UNAPPROVED,
}, },
}; };
@ -107,7 +102,7 @@ const ERRONEOUS_TRANSACTION_STATE_MIXED = {
10: { 10: {
type: TRANSACTION_TYPES.RETRY, type: TRANSACTION_TYPES.RETRY,
id: 10, id: 10,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
txParams: { txParams: {
nonce: '0xa', nonce: '0xa',
}, },
@ -115,7 +110,7 @@ const ERRONEOUS_TRANSACTION_STATE_MIXED = {
11: { 11: {
type: TRANSACTION_TYPES.RETRY, type: TRANSACTION_TYPES.RETRY,
id: 11, id: 11,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
txParams: { txParams: {
nonce: '0xb', nonce: '0xb',
}, },
@ -169,7 +164,7 @@ describe('migration #59', () => {
11: { 11: {
...ERRONEOUS_TRANSACTION_STATE['0'], ...ERRONEOUS_TRANSACTION_STATE['0'],
id: 11, id: 11,
chainId: GOERLI_CHAIN_ID, chainId: CHAIN_IDS.GOERLI,
type: SENT_ETHER, type: SENT_ETHER,
}, },
}, },
@ -250,7 +245,7 @@ describe('migration #59', () => {
11: { 11: {
...ERRONEOUS_TRANSACTION_STATE_RETRY['0'], ...ERRONEOUS_TRANSACTION_STATE_RETRY['0'],
id: 11, id: 11,
chainId: GOERLI_CHAIN_ID, chainId: CHAIN_IDS.GOERLI,
type: SENT_ETHER, type: SENT_ETHER,
}, },
}, },

@ -1,5 +1,5 @@
import { CHAIN_IDS } from '../../../shared/constants/network';
import { TRANSACTION_TYPES } from '../../../shared/constants/transaction'; import { TRANSACTION_TYPES } from '../../../shared/constants/transaction';
import { MAINNET_CHAIN_ID } from '../../../shared/constants/network';
import migration64 from './064'; import migration64 from './064';
const SENT_ETHER = 'sentEther'; // the legacy transaction type being replaced in this migration with TRANSACTION_TYPES.SIMPLE_SEND const SENT_ETHER = 'sentEther'; // the legacy transaction type being replaced in this migration with TRANSACTION_TYPES.SIMPLE_SEND
@ -84,7 +84,7 @@ describe('migration #64', () => {
1462177651588364: { 1462177651588364: {
type: TRANSACTION_TYPES.CANCEL, type: TRANSACTION_TYPES.CANCEL,
id: 0, id: 0,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
txParams: { txParams: {
nonce: '0x0', nonce: '0x0',
}, },
@ -100,7 +100,7 @@ describe('migration #64', () => {
1: { 1: {
type: SENT_ETHER, type: SENT_ETHER,
id: 1, id: 1,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
txParams: { txParams: {
nonce: '0x1', nonce: '0x1',
}, },
@ -263,7 +263,7 @@ describe('migration #64', () => {
1462177651588364: { 1462177651588364: {
type: TRANSACTION_TYPES.CANCEL, type: TRANSACTION_TYPES.CANCEL,
id: 0, id: 0,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
txParams: { txParams: {
nonce: '0x0', nonce: '0x0',
}, },
@ -279,7 +279,7 @@ describe('migration #64', () => {
1: { 1: {
type: TRANSACTION_TYPES.SIMPLE_SEND, type: TRANSACTION_TYPES.SIMPLE_SEND,
id: 1, id: 1,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
txParams: { txParams: {
nonce: '0x1', nonce: '0x1',
}, },

@ -1,426 +0,0 @@
import { capitalize } from 'lodash';
export const ROPSTEN = 'ropsten';
export const RINKEBY = 'rinkeby';
export const KOVAN = 'kovan';
export const MAINNET = 'mainnet';
export const GOERLI = 'goerli';
export const LOCALHOST = 'localhost';
export const NETWORK_TYPE_RPC = 'rpc';
export const HOMESTEAD = 'homestead';
export const MAINNET_NETWORK_ID = '1';
export const ROPSTEN_NETWORK_ID = '3';
export const RINKEBY_NETWORK_ID = '4';
export const GOERLI_NETWORK_ID = '5';
export const KOVAN_NETWORK_ID = '42';
export const LOCALHOST_NETWORK_ID = '1337';
export const MAINNET_CHAIN_ID = '0x1';
export const ROPSTEN_CHAIN_ID = '0x3';
export const RINKEBY_CHAIN_ID = '0x4';
export const GOERLI_CHAIN_ID = '0x5';
export const KOVAN_CHAIN_ID = '0x2a';
export const LOCALHOST_CHAIN_ID = '0x539';
export const BSC_CHAIN_ID = '0x38';
export const OPTIMISM_CHAIN_ID = '0xa';
export const OPTIMISM_TESTNET_CHAIN_ID = '0x1a4';
export const POLYGON_CHAIN_ID = '0x89';
export const AVALANCHE_CHAIN_ID = '0xa86a';
export const FANTOM_CHAIN_ID = '0xfa';
export const CELO_CHAIN_ID = '0xa4ec';
export const ARBITRUM_CHAIN_ID = '0xa4b1';
export const HARMONY_CHAIN_ID = '0x63564c40';
export const PALM_CHAIN_ID = '0x2a15c308d';
/**
* The largest possible chain ID we can handle.
* Explanation: https://gist.github.com/rekmarks/a47bd5f2525936c4b8eee31a16345553
*/
export const MAX_SAFE_CHAIN_ID = 4503599627370476;
export const ROPSTEN_DISPLAY_NAME = 'Ropsten';
export const RINKEBY_DISPLAY_NAME = 'Rinkeby';
export const KOVAN_DISPLAY_NAME = 'Kovan';
export const MAINNET_DISPLAY_NAME = 'Ethereum Mainnet';
export const GOERLI_DISPLAY_NAME = 'Goerli';
export const LOCALHOST_DISPLAY_NAME = 'Localhost 8545';
export const BSC_DISPLAY_NAME = 'Binance Smart Chain';
export const POLYGON_DISPLAY_NAME = 'Polygon';
export const AVALANCHE_DISPLAY_NAME = 'Avalanche Network C-Chain';
export const ARBITRUM_DISPLAY_NAME = 'Arbitrum One';
export const BNB_DISPLAY_NAME =
'BNB Smart Chain (previously Binance Smart Chain Mainnet)';
export const OPTIMISM_DISPLAY_NAME = 'Optimism';
export const FANTOM_DISPLAY_NAME = 'Fantom Opera';
export const HARMONY_DISPLAY_NAME = 'Harmony Mainnet Shard 0';
export const PALM_DISPLAY_NAME = 'Palm';
export const infuraProjectId = process.env.INFURA_PROJECT_ID;
export const getRpcUrl = ({ network, excludeProjectId = false }) =>
`https://${network}.infura.io/v3/${excludeProjectId ? '' : infuraProjectId}`;
export const ROPSTEN_RPC_URL = getRpcUrl({ network: ROPSTEN });
export const RINKEBY_RPC_URL = getRpcUrl({ network: RINKEBY });
export const KOVAN_RPC_URL = getRpcUrl({ network: KOVAN });
export const MAINNET_RPC_URL = getRpcUrl({ network: MAINNET });
export const GOERLI_RPC_URL = getRpcUrl({ network: GOERLI });
export const LOCALHOST_RPC_URL = 'http://localhost:8545';
export const ETH_SYMBOL = 'ETH';
export const WETH_SYMBOL = 'WETH';
export const TEST_ETH_SYMBOL = 'TESTETH';
export const BNB_SYMBOL = 'BNB';
export const MATIC_SYMBOL = 'MATIC';
export const AVALANCHE_SYMBOL = 'AVAX';
export const FANTOM_SYMBOL = 'FTM';
export const CELO_SYMBOL = 'CELO';
export const ARBITRUM_SYMBOL = 'ETH';
export const HARMONY_SYMBOL = 'ONE';
export const PALM_SYMBOL = 'PALM';
export const ETH_TOKEN_IMAGE_URL = './images/eth_logo.svg';
export const TEST_ETH_TOKEN_IMAGE_URL = './images/black-eth-logo.svg';
export const BNB_TOKEN_IMAGE_URL = './images/bnb.png';
export const MATIC_TOKEN_IMAGE_URL = './images/matic-token.png';
export const AVAX_TOKEN_IMAGE_URL = './images/avax-token.png';
export const AETH_TOKEN_IMAGE_URL = './images/arbitrum.svg';
export const FTM_TOKEN_IMAGE_URL = './images/fantom-opera.svg';
export const HARMONY_ONE_TOKEN_IMAGE_URL = './images/harmony-one.svg';
export const OPTIMISM_TOKEN_IMAGE_URL = './images/optimism.svg';
export const PALM_TOKEN_IMAGE_URL = './images/palm.svg';
export const INFURA_PROVIDER_TYPES = [ROPSTEN, RINKEBY, KOVAN, MAINNET, GOERLI];
export const TEST_CHAINS = [
ROPSTEN_CHAIN_ID,
RINKEBY_CHAIN_ID,
GOERLI_CHAIN_ID,
KOVAN_CHAIN_ID,
LOCALHOST_CHAIN_ID,
];
export const TEST_NETWORK_TICKER_MAP = {
[ROPSTEN]: `${capitalize(ROPSTEN)}${ETH_SYMBOL}`,
[RINKEBY]: `${capitalize(RINKEBY)}${ETH_SYMBOL}`,
[KOVAN]: `${capitalize(KOVAN)}${ETH_SYMBOL}`,
[GOERLI]: `${capitalize(GOERLI)}${ETH_SYMBOL}`,
};
/**
* Map of all build-in Infura networks to their network, ticker and chain IDs.
*/
export const NETWORK_TYPE_TO_ID_MAP = {
[ROPSTEN]: {
networkId: ROPSTEN_NETWORK_ID,
chainId: ROPSTEN_CHAIN_ID,
ticker: TEST_NETWORK_TICKER_MAP[ROPSTEN],
},
[RINKEBY]: {
networkId: RINKEBY_NETWORK_ID,
chainId: RINKEBY_CHAIN_ID,
ticker: TEST_NETWORK_TICKER_MAP[RINKEBY],
},
[KOVAN]: {
networkId: KOVAN_NETWORK_ID,
chainId: KOVAN_CHAIN_ID,
ticker: TEST_NETWORK_TICKER_MAP[KOVAN],
},
[GOERLI]: {
networkId: GOERLI_NETWORK_ID,
chainId: GOERLI_CHAIN_ID,
ticker: TEST_NETWORK_TICKER_MAP[GOERLI],
},
[MAINNET]: {
networkId: MAINNET_NETWORK_ID,
chainId: MAINNET_CHAIN_ID,
},
[LOCALHOST]: {
networkId: LOCALHOST_NETWORK_ID,
chainId: LOCALHOST_CHAIN_ID,
},
};
export const NETWORK_TO_NAME_MAP = {
[ROPSTEN]: ROPSTEN_DISPLAY_NAME,
[RINKEBY]: RINKEBY_DISPLAY_NAME,
[KOVAN]: KOVAN_DISPLAY_NAME,
[MAINNET]: MAINNET_DISPLAY_NAME,
[GOERLI]: GOERLI_DISPLAY_NAME,
[LOCALHOST]: LOCALHOST_DISPLAY_NAME,
[ROPSTEN_NETWORK_ID]: ROPSTEN_DISPLAY_NAME,
[RINKEBY_NETWORK_ID]: RINKEBY_DISPLAY_NAME,
[KOVAN_NETWORK_ID]: KOVAN_DISPLAY_NAME,
[GOERLI_NETWORK_ID]: GOERLI_DISPLAY_NAME,
[MAINNET_NETWORK_ID]: MAINNET_DISPLAY_NAME,
[LOCALHOST_NETWORK_ID]: LOCALHOST_DISPLAY_NAME,
[ROPSTEN_CHAIN_ID]: ROPSTEN_DISPLAY_NAME,
[RINKEBY_CHAIN_ID]: RINKEBY_DISPLAY_NAME,
[KOVAN_CHAIN_ID]: KOVAN_DISPLAY_NAME,
[GOERLI_CHAIN_ID]: GOERLI_DISPLAY_NAME,
[MAINNET_CHAIN_ID]: MAINNET_DISPLAY_NAME,
[LOCALHOST_CHAIN_ID]: LOCALHOST_DISPLAY_NAME,
};
export const CHAIN_ID_TO_TYPE_MAP = Object.entries(
NETWORK_TYPE_TO_ID_MAP,
).reduce((chainIdToTypeMap, [networkType, { chainId }]) => {
chainIdToTypeMap[chainId] = networkType;
return chainIdToTypeMap;
}, {});
export const CHAIN_ID_TO_RPC_URL_MAP = {
[ROPSTEN_CHAIN_ID]: ROPSTEN_RPC_URL,
[RINKEBY_CHAIN_ID]: RINKEBY_RPC_URL,
[KOVAN_CHAIN_ID]: KOVAN_RPC_URL,
[GOERLI_CHAIN_ID]: GOERLI_RPC_URL,
[MAINNET_CHAIN_ID]: MAINNET_RPC_URL,
[LOCALHOST_CHAIN_ID]: LOCALHOST_RPC_URL,
};
export const CHAIN_ID_TO_NETWORK_IMAGE_URL_MAP = {
[MAINNET_CHAIN_ID]: ETH_TOKEN_IMAGE_URL,
[AVALANCHE_CHAIN_ID]: AVAX_TOKEN_IMAGE_URL,
[BSC_CHAIN_ID]: BNB_TOKEN_IMAGE_URL,
[POLYGON_CHAIN_ID]: MATIC_TOKEN_IMAGE_URL,
[ARBITRUM_CHAIN_ID]: AETH_TOKEN_IMAGE_URL,
[BSC_CHAIN_ID]: BNB_TOKEN_IMAGE_URL,
[FANTOM_CHAIN_ID]: FTM_TOKEN_IMAGE_URL,
[HARMONY_CHAIN_ID]: HARMONY_ONE_TOKEN_IMAGE_URL,
[OPTIMISM_CHAIN_ID]: OPTIMISM_TOKEN_IMAGE_URL,
[PALM_CHAIN_ID]: PALM_TOKEN_IMAGE_URL,
};
export const NETWORK_ID_TO_ETHERS_NETWORK_NAME_MAP = {
[ROPSTEN_NETWORK_ID]: ROPSTEN,
[RINKEBY_NETWORK_ID]: RINKEBY,
[GOERLI_NETWORK_ID]: GOERLI,
[MAINNET_NETWORK_ID]: HOMESTEAD,
};
export const CHAIN_ID_TO_NETWORK_ID_MAP = Object.values(
NETWORK_TYPE_TO_ID_MAP,
).reduce((chainIdToNetworkIdMap, { chainId, networkId }) => {
chainIdToNetworkIdMap[chainId] = networkId;
return chainIdToNetworkIdMap;
}, {});
export const NATIVE_CURRENCY_TOKEN_IMAGE_MAP = {
[ETH_SYMBOL]: ETH_TOKEN_IMAGE_URL,
[TEST_ETH_SYMBOL]: TEST_ETH_TOKEN_IMAGE_URL,
[BNB_SYMBOL]: BNB_TOKEN_IMAGE_URL,
[MATIC_SYMBOL]: MATIC_TOKEN_IMAGE_URL,
[AVALANCHE_SYMBOL]: AVAX_TOKEN_IMAGE_URL,
};
export const INFURA_BLOCKED_KEY = 'countryBlocked';
/**
* Hardforks are points in the chain where logic is changed significantly
* enough where there is a fork and the new fork becomes the active chain.
* These constants are presented in chronological order starting with BERLIN
* because when we first needed to track the hardfork we had launched support
* for EIP-2718 (where transactions can have types and different shapes) and
* EIP-2930 (optional access lists), which were included in BERLIN.
*
* BERLIN - forked at block number 12,244,000, included typed transactions and
* optional access lists
* LONDON - future, upcoming fork that introduces the baseFeePerGas, an amount
* of the ETH transaction fees that will be burned instead of given to the
* miner. This change necessitated the third type of transaction envelope to
* specify maxFeePerGas and maxPriorityFeePerGas moving the fee bidding system
* to a second price auction model.
*/
export const HARDFORKS = {
BERLIN: 'berlin',
LONDON: 'london',
};
export const CHAIN_ID_TO_GAS_LIMIT_BUFFER_MAP = {
[OPTIMISM_CHAIN_ID]: 1,
[OPTIMISM_TESTNET_CHAIN_ID]: 1,
};
/**
* Ethereum JSON-RPC methods that are known to exist but that we intentionally
* do not support.
*/
export const UNSUPPORTED_RPC_METHODS = new Set([
// This is implemented later in our middleware stack – specifically, in
// eth-json-rpc-middleware – but our UI does not support it.
'eth_signTransaction',
]);
export const IPFS_DEFAULT_GATEWAY_URL = 'dweb.link';
// The first item in transakCurrencies must be the
// default crypto currency for the network
const BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME = 'ethereum';
export const BUYABLE_CHAINS_MAP = {
[MAINNET_CHAIN_ID]: {
nativeCurrency: ETH_SYMBOL,
network: BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME,
transakCurrencies: [ETH_SYMBOL, 'USDT', 'USDC', 'DAI'],
moonPay: {
defaultCurrencyCode: 'eth',
showOnlyCurrencies: 'eth,usdt,usdc,dai',
},
wyre: {
srn: 'ethereum',
currencyCode: ETH_SYMBOL,
},
coinbasePayCurrencies: [ETH_SYMBOL, 'USDC', 'DAI'],
},
[ROPSTEN_CHAIN_ID]: {
nativeCurrency: TEST_NETWORK_TICKER_MAP[ROPSTEN],
network: BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME,
},
[RINKEBY_CHAIN_ID]: {
nativeCurrency: TEST_NETWORK_TICKER_MAP[RINKEBY],
network: BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME,
},
[GOERLI_CHAIN_ID]: {
nativeCurrency: TEST_NETWORK_TICKER_MAP[GOERLI],
network: BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME,
},
[KOVAN_CHAIN_ID]: {
nativeCurrency: TEST_NETWORK_TICKER_MAP[KOVAN],
network: BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME,
},
[BSC_CHAIN_ID]: {
nativeCurrency: BNB_SYMBOL,
network: 'bsc',
transakCurrencies: [BNB_SYMBOL, 'BUSD'],
moonPay: {
defaultCurrencyCode: 'bnb_bsc',
showOnlyCurrencies: 'bnb_bsc,busd_bsc',
},
},
[POLYGON_CHAIN_ID]: {
nativeCurrency: MATIC_SYMBOL,
network: 'polygon',
transakCurrencies: [MATIC_SYMBOL, 'USDT', 'USDC', 'DAI'],
moonPay: {
defaultCurrencyCode: 'matic_polygon',
showOnlyCurrencies: 'matic_polygon,usdc_polygon',
},
wyre: {
srn: 'matic',
currencyCode: MATIC_SYMBOL,
},
},
[AVALANCHE_CHAIN_ID]: {
nativeCurrency: AVALANCHE_SYMBOL,
network: 'avaxcchain',
transakCurrencies: [AVALANCHE_SYMBOL],
moonPay: {
defaultCurrencyCode: 'avax_cchain',
showOnlyCurrencies: 'avax_cchain',
},
wyre: {
srn: 'avalanche',
currencyCode: AVALANCHE_SYMBOL,
},
coinbasePayCurrencies: [AVALANCHE_SYMBOL],
},
[FANTOM_CHAIN_ID]: {
nativeCurrency: FANTOM_SYMBOL,
network: 'fantom',
transakCurrencies: [FANTOM_SYMBOL],
},
[CELO_CHAIN_ID]: {
nativeCurrency: CELO_SYMBOL,
network: 'celo',
transakCurrencies: [CELO_SYMBOL],
moonPay: {
defaultCurrencyCode: 'celo',
showOnlyCurrencies: 'celo',
},
},
};
export const FEATURED_RPCS = [
{
chainId: ARBITRUM_CHAIN_ID,
nickname: ARBITRUM_DISPLAY_NAME,
rpcUrl: `https://arbitrum-mainnet.infura.io/v3/${infuraProjectId}`,
ticker: ARBITRUM_SYMBOL,
rpcPrefs: {
blockExplorerUrl: 'https://explorer.arbitrum.io',
imageUrl: AETH_TOKEN_IMAGE_URL,
},
},
{
chainId: AVALANCHE_CHAIN_ID,
nickname: AVALANCHE_DISPLAY_NAME,
rpcUrl: `https://avalanche-mainnet.infura.io/v3/${infuraProjectId}`,
ticker: AVALANCHE_SYMBOL,
rpcPrefs: {
blockExplorerUrl: 'https://snowtrace.io/',
imageUrl: AVAX_TOKEN_IMAGE_URL,
},
},
{
chainId: BSC_CHAIN_ID,
nickname: BNB_DISPLAY_NAME,
rpcUrl: 'https://bsc-dataseed.binance.org/',
ticker: BNB_SYMBOL,
rpcPrefs: {
blockExplorerUrl: 'https://bscscan.com/',
imageUrl: BNB_TOKEN_IMAGE_URL,
},
},
{
chainId: FANTOM_CHAIN_ID,
nickname: FANTOM_DISPLAY_NAME,
rpcUrl: 'https://rpc.ftm.tools/',
ticker: FANTOM_SYMBOL,
rpcPrefs: {
blockExplorerUrl: 'https://ftmscan.com/',
imageUrl: FTM_TOKEN_IMAGE_URL,
},
},
{
chainId: HARMONY_CHAIN_ID,
nickname: HARMONY_DISPLAY_NAME,
rpcUrl: 'https://api.harmony.one/',
ticker: HARMONY_SYMBOL,
rpcPrefs: {
blockExplorerUrl: 'https://explorer.harmony.one/',
imageUrl: HARMONY_ONE_TOKEN_IMAGE_URL,
},
},
{
chainId: OPTIMISM_CHAIN_ID,
nickname: OPTIMISM_DISPLAY_NAME,
rpcUrl: `https://optimism-mainnet.infura.io/v3/${infuraProjectId}`,
ticker: ETH_SYMBOL,
rpcPrefs: {
blockExplorerUrl: 'https://optimistic.etherscan.io/',
imageUrl: OPTIMISM_TOKEN_IMAGE_URL,
},
},
{
chainId: PALM_CHAIN_ID,
nickname: PALM_DISPLAY_NAME,
rpcUrl: `https://palm-mainnet.infura.io/v3/${infuraProjectId}`,
ticker: PALM_SYMBOL,
rpcPrefs: {
blockExplorerUrl: 'https://explorer.palm.io/',
imageUrl: PALM_TOKEN_IMAGE_URL,
},
},
{
chainId: POLYGON_CHAIN_ID,
nickname: `${POLYGON_DISPLAY_NAME} ${capitalize(MAINNET)}`,
rpcUrl: `https://polygon-mainnet.infura.io/v3/${infuraProjectId}`,
ticker: MATIC_SYMBOL,
rpcPrefs: {
blockExplorerUrl: 'https://polygonscan.com/',
imageUrl: MATIC_TOKEN_IMAGE_URL,
},
},
];

@ -0,0 +1,675 @@
import { capitalize } from 'lodash';
/**
* A type representing any valid value for 'type' for setProviderType and other
* methods that add or manipulate networks in MetaMask state.
*/
export type NetworkType = typeof NETWORK_TYPES[keyof typeof NETWORK_TYPES];
/**
* A union type of all possible hard-coded chain ids. This type is not
* exhaustive and cannot be used for typing chainId in areas where the user or
* dapp may specify any chainId.
*/
export type ChainId = typeof CHAIN_IDS[keyof typeof CHAIN_IDS];
/**
* A type that is a union type of all possible hardcoded currency symbols.
* This type is non-exhaustive, and cannot be used for areas where the user
* or dapp may supply their own symbol.
*/
type CurrencySymbol = typeof CURRENCY_SYMBOLS[keyof typeof CURRENCY_SYMBOLS];
/**
* For certain specific situations we need the above type, but with all symbols
* in lowercase format.
*/
type LowercaseCurrencySymbol = Lowercase<CurrencySymbol>;
/**
* Test networks have special symbols that combine the network name and 'ETH'
* so that they are distinct from mainnet and other networks that use 'ETH'.
*/
export type TestNetworkCurrencySymbol =
typeof TEST_NETWORK_TICKER_MAP[keyof typeof TEST_NETWORK_TICKER_MAP];
/**
* MoonPay is a fiat onramp provider, and there are some special strings that
* inform the MoonPay API which network the user is attempting to onramp into.
* This type reflects those possible values.
*/
type MoonPayNetworkAbbreviation = 'bsc' | 'cchain' | 'polygon';
/**
* MoonPay requires some settings that are configured per network that it is
* enabled on. This type describes those settings.
*/
type MoonPayChainSettings = {
/**
* What should the default onramp currency be, for example 'eth' on 'mainnet'
* This type matches a single LowercaseCurrencySymbol or a
* LowercaseCurrencySymbol and a MoonPayNetworkAbbreviation joined by a '_'.
*/
defaultCurrencyCode:
| LowercaseCurrencySymbol
| `${LowercaseCurrencySymbol}_${MoonPayNetworkAbbreviation}`;
/**
* We must also configure all possible onramp currencies we wish to support.
* This type matches 1 to 3 LowercaseCurrencySymbols, joined by ','. It also
* matches 1 or 2 LowercaseCurrencySymbols with a
* MoonPayNetworkAbbreviation joined by a '_', and concatenated with ','.
*/
showOnlyCurrencies:
| `${LowercaseCurrencySymbol}`
| `${LowercaseCurrencySymbol},${LowercaseCurrencySymbol}`
| `${LowercaseCurrencySymbol},${LowercaseCurrencySymbol},${LowercaseCurrencySymbol}`
| `${LowercaseCurrencySymbol},${LowercaseCurrencySymbol},${LowercaseCurrencySymbol},${LowercaseCurrencySymbol}`
| `${LowercaseCurrencySymbol}_${MoonPayNetworkAbbreviation}`
| `${LowercaseCurrencySymbol}_${MoonPayNetworkAbbreviation},${LowercaseCurrencySymbol}_${MoonPayNetworkAbbreviation}`;
};
/**
* An object containing preferences for an RPC definition
*/
type RPCPreferences = {
/**
* A URL for the block explorer for the RPC's network
*/
blockExplorerUrl: `https://${string}`;
/**
* A image reflecting the asset symbol for the network
*/
imageUrl: string;
};
/**
* An object that describes a network to be used inside of MetaMask
*/
type RPCDefinition = {
/**
* The hex encoded ChainId for the network
*/
chainId: ChainId;
/**
* The nickname for the network
*/
nickname: string;
/**
* The URL for the client to send network requests to
*/
rpcUrl: `https://${string}`;
/**
* The Currency Symbol for the network
*/
ticker: string;
/**
* Additional preferences for the network, such as blockExplorerUrl
*/
rpcPrefs: RPCPreferences;
};
/**
* Wyre is a fiat onramp provider. We must provide some settings for networks
* that support Wyre.
*/
type WyreChainSettings = {
/**
* The network name
*/
srn: string;
/**
* The native currency for the network
*/
currencyCode: CurrencySymbol;
};
/**
* For each chain that we support fiat onramps for, we provide a set of
* configuration options that help for initializing the connectiong to the
* onramp providers.
*/
type BuyableChainSettings = {
/**
* The native currency for the given chain
*/
nativeCurrency: CurrencySymbol | TestNetworkCurrencySymbol;
/**
* The network name or identifier
*/
network: string;
/**
* The list of supported currencies for the Transak onramp provider
*/
transakCurrencies?: CurrencySymbol[];
/**
* A configuration object for the MoonPay onramp provider
*/
moonPay?: MoonPayChainSettings;
/**
* A configuration object for the Wyre onramp provider
*/
wyre?: WyreChainSettings;
/**
* The list of supported currencies for the CoinbasePay onramp provider
*/
coinbasePayCurrencies?: CurrencySymbol[];
};
/**
* Throughout the extension we set the current provider by referencing its
* "type", which can be any of the values in the below object. These values
* represent the built-in networks of MetaMask, including test nets, as well
* as "rpc" which is the "type" of a custom network added by the user or via
* wallet_addEthereumChain.
*/
export const NETWORK_TYPES = {
GOERLI: 'goerli',
KOVAN: 'kovan',
LOCALHOST: 'localhost',
MAINNET: 'mainnet',
RINKEBY: 'rinkeby',
ROPSTEN: 'ropsten',
RPC: 'rpc',
} as const;
/**
* An object containing shortcut names for any non-builtin network. We need
* this to be able to differentiate between networks that require custom
* sections of code for our various features, such as swaps or token lists.
*/
export const NETWORK_NAMES = {
HOMESTEAD: 'homestead',
};
/**
* The Network ID for our builtin networks. This is the decimal equivalent of
* the chain id for the network, but is expresssed as a string. Many moons ago
* the decision was made on the extension team to expressly use chainId with
* hex encoding over network id. Consider that when accessing this object. Note
* for cross product purposes: alignment with mobile on this matter has not
* been fully achieved, thus it is possible for some dependencies to still
* ask for or require network id.
*/
export const NETWORK_IDS = {
MAINNET: '1',
ROPSTEN: '3',
RINKEBY: '4',
GOERLI: '5',
KOVAN: '42',
LOCALHOST: '1337',
} as const;
/**
* An object containing all of the chain ids for networks both built in and
* those that we have added custom code to support our feature set.
*/
export const CHAIN_IDS = {
MAINNET: '0x1',
ROPSTEN: '0x3',
RINKEBY: '0x4',
GOERLI: '0x5',
KOVAN: '0x2a',
LOCALHOST: '0x539',
BSC: '0x38',
OPTIMISM: '0xa',
OPTIMISM_TESTNET: '0x1a4',
POLYGON: '0x89',
AVALANCHE: '0xa86a',
FANTOM: '0xfa',
CELO: '0xa4ec',
ARBITRUM: '0xa4b1',
HARMONY: '0x63564c40',
PALM: '0x2a15c308d',
} as const;
/**
* The largest possible chain ID we can handle.
* Explanation: https://gist.github.com/rekmarks/a47bd5f2525936c4b8eee31a16345553
*/
export const MAX_SAFE_CHAIN_ID = 4503599627370476;
export const ROPSTEN_DISPLAY_NAME = 'Ropsten';
export const RINKEBY_DISPLAY_NAME = 'Rinkeby';
export const KOVAN_DISPLAY_NAME = 'Kovan';
export const MAINNET_DISPLAY_NAME = 'Ethereum Mainnet';
export const GOERLI_DISPLAY_NAME = 'Goerli';
export const LOCALHOST_DISPLAY_NAME = 'Localhost 8545';
export const BSC_DISPLAY_NAME = 'Binance Smart Chain';
export const POLYGON_DISPLAY_NAME = 'Polygon';
export const AVALANCHE_DISPLAY_NAME = 'Avalanche Network C-Chain';
export const ARBITRUM_DISPLAY_NAME = 'Arbitrum One';
export const BNB_DISPLAY_NAME =
'BNB Smart Chain (previously Binance Smart Chain Mainnet)';
export const OPTIMISM_DISPLAY_NAME = 'Optimism';
export const FANTOM_DISPLAY_NAME = 'Fantom Opera';
export const HARMONY_DISPLAY_NAME = 'Harmony Mainnet Shard 0';
export const PALM_DISPLAY_NAME = 'Palm';
export const infuraProjectId = process.env.INFURA_PROJECT_ID;
export const getRpcUrl = ({
network,
excludeProjectId = false,
}: {
network: NetworkType;
excludeProjectId?: boolean;
}) =>
`https://${network}.infura.io/v3/${excludeProjectId ? '' : infuraProjectId}`;
export const ROPSTEN_RPC_URL = getRpcUrl({
network: NETWORK_TYPES.ROPSTEN,
});
export const RINKEBY_RPC_URL = getRpcUrl({
network: NETWORK_TYPES.RINKEBY,
});
export const KOVAN_RPC_URL = getRpcUrl({ network: NETWORK_TYPES.KOVAN });
export const MAINNET_RPC_URL = getRpcUrl({
network: NETWORK_TYPES.MAINNET,
});
export const GOERLI_RPC_URL = getRpcUrl({ network: NETWORK_TYPES.GOERLI });
export const LOCALHOST_RPC_URL = 'http://localhost:8545';
/**
* An object containing the token symbols for various tokens that are either
* native currencies or those that have been special cased by the extension
* for supporting our feature set.
*/
export const CURRENCY_SYMBOLS = {
ARBITRUM: 'ETH',
AVALANCHE: 'AVAX',
BNB: 'BNB',
BUSD: 'BUSD',
CELO: 'CELO',
DAI: 'DAI',
ETH: 'ETH',
FANTOM: 'FTM',
HARMONY: 'ONE',
PALM: 'PALM',
MATIC: 'MATIC',
TEST_ETH: 'TESTETH',
USDC: 'USDC',
USDT: 'USDT',
WETH: 'WETH',
} as const;
export const ETH_TOKEN_IMAGE_URL = './images/eth_logo.svg';
export const TEST_ETH_TOKEN_IMAGE_URL = './images/black-eth-logo.svg';
export const BNB_TOKEN_IMAGE_URL = './images/bnb.png';
export const MATIC_TOKEN_IMAGE_URL = './images/matic-token.png';
export const AVAX_TOKEN_IMAGE_URL = './images/avax-token.png';
export const AETH_TOKEN_IMAGE_URL = './images/arbitrum.svg';
export const FTM_TOKEN_IMAGE_URL = './images/fantom-opera.svg';
export const HARMONY_ONE_TOKEN_IMAGE_URL = './images/harmony-one.svg';
export const OPTIMISM_TOKEN_IMAGE_URL = './images/optimism.svg';
export const PALM_TOKEN_IMAGE_URL = './images/palm.svg';
export const INFURA_PROVIDER_TYPES = [
NETWORK_TYPES.ROPSTEN,
NETWORK_TYPES.RINKEBY,
NETWORK_TYPES.KOVAN,
NETWORK_TYPES.MAINNET,
NETWORK_TYPES.GOERLI,
];
export const TEST_CHAINS = [
CHAIN_IDS.ROPSTEN,
CHAIN_IDS.RINKEBY,
CHAIN_IDS.GOERLI,
CHAIN_IDS.KOVAN,
CHAIN_IDS.LOCALHOST,
];
const typedCapitalize = <K extends string>(k: K): Capitalize<K> =>
capitalize(k) as Capitalize<typeof k>;
export const TEST_NETWORK_TICKER_MAP: {
[K in Exclude<
NetworkType,
'localhost' | 'mainnet' | 'rpc'
>]: `${Capitalize<K>}${typeof CURRENCY_SYMBOLS.ETH}`;
} = {
[NETWORK_TYPES.ROPSTEN]: `${typedCapitalize(NETWORK_TYPES.ROPSTEN)}${
CURRENCY_SYMBOLS.ETH
}`,
[NETWORK_TYPES.RINKEBY]: `${typedCapitalize(NETWORK_TYPES.RINKEBY)}${
CURRENCY_SYMBOLS.ETH
}`,
[NETWORK_TYPES.KOVAN]: `${typedCapitalize(NETWORK_TYPES.KOVAN)}${
CURRENCY_SYMBOLS.ETH
}`,
[NETWORK_TYPES.GOERLI]: `${typedCapitalize(NETWORK_TYPES.GOERLI)}${
CURRENCY_SYMBOLS.ETH
}`,
};
/**
* Map of all build-in Infura networks to their network, ticker and chain IDs.
*/
export const BUILT_IN_NETWORKS = {
[NETWORK_TYPES.ROPSTEN]: {
networkId: NETWORK_IDS.ROPSTEN,
chainId: CHAIN_IDS.ROPSTEN,
ticker: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.ROPSTEN],
},
[NETWORK_TYPES.RINKEBY]: {
networkId: NETWORK_IDS.RINKEBY,
chainId: CHAIN_IDS.RINKEBY,
ticker: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.RINKEBY],
},
[NETWORK_TYPES.KOVAN]: {
networkId: NETWORK_IDS.KOVAN,
chainId: CHAIN_IDS.KOVAN,
ticker: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.KOVAN],
},
[NETWORK_TYPES.GOERLI]: {
networkId: NETWORK_IDS.GOERLI,
chainId: CHAIN_IDS.GOERLI,
ticker: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.GOERLI],
},
[NETWORK_TYPES.MAINNET]: {
networkId: NETWORK_IDS.MAINNET,
chainId: CHAIN_IDS.MAINNET,
},
[NETWORK_TYPES.LOCALHOST]: {
networkId: NETWORK_IDS.LOCALHOST,
chainId: CHAIN_IDS.LOCALHOST,
},
} as const;
export const NETWORK_TO_NAME_MAP = {
[NETWORK_TYPES.ROPSTEN]: ROPSTEN_DISPLAY_NAME,
[NETWORK_TYPES.RINKEBY]: RINKEBY_DISPLAY_NAME,
[NETWORK_TYPES.KOVAN]: KOVAN_DISPLAY_NAME,
[NETWORK_TYPES.MAINNET]: MAINNET_DISPLAY_NAME,
[NETWORK_TYPES.GOERLI]: GOERLI_DISPLAY_NAME,
[NETWORK_TYPES.LOCALHOST]: LOCALHOST_DISPLAY_NAME,
[NETWORK_IDS.ROPSTEN]: ROPSTEN_DISPLAY_NAME,
[NETWORK_IDS.RINKEBY]: RINKEBY_DISPLAY_NAME,
[NETWORK_IDS.KOVAN]: KOVAN_DISPLAY_NAME,
[NETWORK_IDS.GOERLI]: GOERLI_DISPLAY_NAME,
[NETWORK_IDS.MAINNET]: MAINNET_DISPLAY_NAME,
[NETWORK_IDS.LOCALHOST]: LOCALHOST_DISPLAY_NAME,
[CHAIN_IDS.ROPSTEN]: ROPSTEN_DISPLAY_NAME,
[CHAIN_IDS.RINKEBY]: RINKEBY_DISPLAY_NAME,
[CHAIN_IDS.KOVAN]: KOVAN_DISPLAY_NAME,
[CHAIN_IDS.GOERLI]: GOERLI_DISPLAY_NAME,
[CHAIN_IDS.MAINNET]: MAINNET_DISPLAY_NAME,
[CHAIN_IDS.GOERLI]: LOCALHOST_DISPLAY_NAME,
} as const;
export const CHAIN_ID_TO_TYPE_MAP = {
[CHAIN_IDS.MAINNET]: NETWORK_TYPES.MAINNET,
[CHAIN_IDS.GOERLI]: NETWORK_TYPES.GOERLI,
[CHAIN_IDS.KOVAN]: NETWORK_TYPES.KOVAN,
[CHAIN_IDS.LOCALHOST]: NETWORK_TYPES.LOCALHOST,
[CHAIN_IDS.RINKEBY]: NETWORK_TYPES.RINKEBY,
[CHAIN_IDS.ROPSTEN]: NETWORK_TYPES.ROPSTEN,
} as const;
export const CHAIN_ID_TO_RPC_URL_MAP = {
[CHAIN_IDS.ROPSTEN]: ROPSTEN_RPC_URL,
[CHAIN_IDS.RINKEBY]: RINKEBY_RPC_URL,
[CHAIN_IDS.KOVAN]: KOVAN_RPC_URL,
[CHAIN_IDS.GOERLI]: GOERLI_RPC_URL,
[CHAIN_IDS.MAINNET]: MAINNET_RPC_URL,
[CHAIN_IDS.LOCALHOST]: LOCALHOST_RPC_URL,
} as const;
export const CHAIN_ID_TO_NETWORK_IMAGE_URL_MAP = {
[CHAIN_IDS.MAINNET]: ETH_TOKEN_IMAGE_URL,
[CHAIN_IDS.AVALANCHE]: AVAX_TOKEN_IMAGE_URL,
[CHAIN_IDS.BSC]: BNB_TOKEN_IMAGE_URL,
[CHAIN_IDS.POLYGON]: MATIC_TOKEN_IMAGE_URL,
[CHAIN_IDS.ARBITRUM]: AETH_TOKEN_IMAGE_URL,
[CHAIN_IDS.FANTOM]: FTM_TOKEN_IMAGE_URL,
[CHAIN_IDS.HARMONY]: HARMONY_ONE_TOKEN_IMAGE_URL,
[CHAIN_IDS.OPTIMISM]: OPTIMISM_TOKEN_IMAGE_URL,
[CHAIN_IDS.PALM]: PALM_TOKEN_IMAGE_URL,
} as const;
export const NETWORK_ID_TO_ETHERS_NETWORK_NAME_MAP = {
[NETWORK_IDS.ROPSTEN]: NETWORK_TYPES.ROPSTEN,
[NETWORK_IDS.RINKEBY]: NETWORK_TYPES.RINKEBY,
[NETWORK_IDS.GOERLI]: NETWORK_TYPES.GOERLI,
[NETWORK_IDS.MAINNET]: NETWORK_NAMES.HOMESTEAD,
} as const;
export const CHAIN_ID_TO_NETWORK_ID_MAP = {
[CHAIN_IDS.MAINNET]: NETWORK_IDS.MAINNET,
[CHAIN_IDS.GOERLI]: NETWORK_IDS.GOERLI,
[CHAIN_IDS.KOVAN]: NETWORK_IDS.KOVAN,
[CHAIN_IDS.LOCALHOST]: NETWORK_IDS.LOCALHOST,
[CHAIN_IDS.RINKEBY]: NETWORK_IDS.RINKEBY,
[CHAIN_IDS.ROPSTEN]: NETWORK_IDS.ROPSTEN,
} as const;
export const NATIVE_CURRENCY_TOKEN_IMAGE_MAP = {
[CURRENCY_SYMBOLS.ETH]: ETH_TOKEN_IMAGE_URL,
[CURRENCY_SYMBOLS.TEST_ETH]: TEST_ETH_TOKEN_IMAGE_URL,
[CURRENCY_SYMBOLS.BNB]: BNB_TOKEN_IMAGE_URL,
[CURRENCY_SYMBOLS.MATIC]: MATIC_TOKEN_IMAGE_URL,
[CURRENCY_SYMBOLS.AVALANCHE]: AVAX_TOKEN_IMAGE_URL,
} as const;
export const INFURA_BLOCKED_KEY = 'countryBlocked';
/**
* Hardforks are points in the chain where logic is changed significantly
* enough where there is a fork and the new fork becomes the active chain.
* These constants are presented in chronological order starting with BERLIN
* because when we first needed to track the hardfork we had launched support
* for EIP-2718 (where transactions can have types and different shapes) and
* EIP-2930 (optional access lists), which were included in BERLIN.
*
* BERLIN - forked at block number 12,244,000, included typed transactions and
* optional access lists
* LONDON - future, upcoming fork that introduces the baseFeePerGas, an amount
* of the ETH transaction fees that will be burned instead of given to the
* miner. This change necessitated the third type of transaction envelope to
* specify maxFeePerGas and maxPriorityFeePerGas moving the fee bidding system
* to a second price auction model.
*/
export const HARDFORKS = {
BERLIN: 'berlin',
LONDON: 'london',
} as const;
export const CHAIN_ID_TO_GAS_LIMIT_BUFFER_MAP = {
[CHAIN_IDS.OPTIMISM]: 1,
[CHAIN_IDS.OPTIMISM_TESTNET]: 1,
};
/**
* Ethereum JSON-RPC methods that are known to exist but that we intentionally
* do not support.
*/
export const UNSUPPORTED_RPC_METHODS = new Set([
// This is implemented later in our middleware stack – specifically, in
// eth-json-rpc-middleware – but our UI does not support it.
'eth_signTransaction' as const,
]);
export const IPFS_DEFAULT_GATEWAY_URL = 'dweb.link';
// The first item in transakCurrencies must be the
// default crypto currency for the network
const BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME = 'ethereum';
export const BUYABLE_CHAINS_MAP: {
[K in Exclude<
ChainId,
| typeof CHAIN_IDS.LOCALHOST
| typeof CHAIN_IDS.PALM
| typeof CHAIN_IDS.HARMONY
| typeof CHAIN_IDS.OPTIMISM
| typeof CHAIN_IDS.OPTIMISM_TESTNET
| typeof CHAIN_IDS.ARBITRUM
>]: BuyableChainSettings;
} = {
[CHAIN_IDS.MAINNET]: {
nativeCurrency: CURRENCY_SYMBOLS.ETH,
network: BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME,
transakCurrencies: [CURRENCY_SYMBOLS.ETH, 'USDT', 'USDC', 'DAI'],
moonPay: {
defaultCurrencyCode: 'eth',
showOnlyCurrencies: 'eth,usdt,usdc,dai',
},
wyre: {
srn: 'ethereum',
currencyCode: CURRENCY_SYMBOLS.ETH,
},
coinbasePayCurrencies: [CURRENCY_SYMBOLS.ETH, 'USDC', 'DAI'],
},
[CHAIN_IDS.ROPSTEN]: {
nativeCurrency: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.ROPSTEN],
network: BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME,
},
[CHAIN_IDS.RINKEBY]: {
nativeCurrency: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.RINKEBY],
network: BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME,
},
[CHAIN_IDS.GOERLI]: {
nativeCurrency: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.GOERLI],
network: BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME,
},
[CHAIN_IDS.KOVAN]: {
nativeCurrency: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.KOVAN],
network: BUYABLE_CHAIN_ETHEREUM_NETWORK_NAME,
},
[CHAIN_IDS.BSC]: {
nativeCurrency: CURRENCY_SYMBOLS.BNB,
network: 'bsc',
transakCurrencies: [CURRENCY_SYMBOLS.BNB, CURRENCY_SYMBOLS.BUSD],
moonPay: {
defaultCurrencyCode: 'bnb_bsc',
showOnlyCurrencies: 'bnb_bsc,busd_bsc',
},
},
[CHAIN_IDS.POLYGON]: {
nativeCurrency: CURRENCY_SYMBOLS.MATIC,
network: 'polygon',
transakCurrencies: [
CURRENCY_SYMBOLS.MATIC,
CURRENCY_SYMBOLS.USDT,
CURRENCY_SYMBOLS.USDC,
CURRENCY_SYMBOLS.DAI,
],
moonPay: {
defaultCurrencyCode: 'matic_polygon',
showOnlyCurrencies: 'matic_polygon,usdc_polygon',
},
wyre: {
srn: 'matic',
currencyCode: CURRENCY_SYMBOLS.MATIC,
},
},
[CHAIN_IDS.AVALANCHE]: {
nativeCurrency: CURRENCY_SYMBOLS.AVALANCHE,
network: 'avaxcchain',
transakCurrencies: [CURRENCY_SYMBOLS.AVALANCHE],
moonPay: {
defaultCurrencyCode: 'avax_cchain',
showOnlyCurrencies: 'avax_cchain',
},
wyre: {
srn: 'avalanche',
currencyCode: CURRENCY_SYMBOLS.AVALANCHE,
},
coinbasePayCurrencies: [CURRENCY_SYMBOLS.AVALANCHE],
},
[CHAIN_IDS.FANTOM]: {
nativeCurrency: CURRENCY_SYMBOLS.FANTOM,
network: 'fantom',
transakCurrencies: [CURRENCY_SYMBOLS.FANTOM],
},
[CHAIN_IDS.CELO]: {
nativeCurrency: CURRENCY_SYMBOLS.CELO,
network: 'celo',
transakCurrencies: [CURRENCY_SYMBOLS.CELO],
moonPay: {
defaultCurrencyCode: 'celo',
showOnlyCurrencies: 'celo',
},
},
};
export const FEATURED_RPCS: RPCDefinition[] = [
{
chainId: CHAIN_IDS.ARBITRUM,
nickname: ARBITRUM_DISPLAY_NAME,
rpcUrl: `https://arbitrum-mainnet.infura.io/v3/${infuraProjectId}`,
ticker: CURRENCY_SYMBOLS.ARBITRUM,
rpcPrefs: {
blockExplorerUrl: 'https://explorer.arbitrum.io',
imageUrl: AETH_TOKEN_IMAGE_URL,
},
},
{
chainId: CHAIN_IDS.AVALANCHE,
nickname: AVALANCHE_DISPLAY_NAME,
rpcUrl: `https://avalanche-mainnet.infura.io/v3/${infuraProjectId}`,
ticker: CURRENCY_SYMBOLS.AVALANCHE,
rpcPrefs: {
blockExplorerUrl: 'https://snowtrace.io/',
imageUrl: AVAX_TOKEN_IMAGE_URL,
},
},
{
chainId: CHAIN_IDS.BSC,
nickname: BNB_DISPLAY_NAME,
rpcUrl: 'https://bsc-dataseed.binance.org/',
ticker: CURRENCY_SYMBOLS.BNB,
rpcPrefs: {
blockExplorerUrl: 'https://bscscan.com/',
imageUrl: BNB_TOKEN_IMAGE_URL,
},
},
{
chainId: CHAIN_IDS.FANTOM,
nickname: FANTOM_DISPLAY_NAME,
rpcUrl: 'https://rpc.ftm.tools/',
ticker: CURRENCY_SYMBOLS.FANTOM,
rpcPrefs: {
blockExplorerUrl: 'https://ftmscan.com/',
imageUrl: FTM_TOKEN_IMAGE_URL,
},
},
{
chainId: CHAIN_IDS.HARMONY,
nickname: HARMONY_DISPLAY_NAME,
rpcUrl: 'https://api.harmony.one/',
ticker: CURRENCY_SYMBOLS.HARMONY,
rpcPrefs: {
blockExplorerUrl: 'https://explorer.harmony.one/',
imageUrl: HARMONY_ONE_TOKEN_IMAGE_URL,
},
},
{
chainId: CHAIN_IDS.OPTIMISM,
nickname: OPTIMISM_DISPLAY_NAME,
rpcUrl: `https://optimism-mainnet.infura.io/v3/${infuraProjectId}`,
ticker: CURRENCY_SYMBOLS.ETH,
rpcPrefs: {
blockExplorerUrl: 'https://optimistic.etherscan.io/',
imageUrl: OPTIMISM_TOKEN_IMAGE_URL,
},
},
{
chainId: CHAIN_IDS.PALM,
nickname: PALM_DISPLAY_NAME,
rpcUrl: `https://palm-mainnet.infura.io/v3/${infuraProjectId}`,
ticker: CURRENCY_SYMBOLS.PALM,
rpcPrefs: {
blockExplorerUrl: 'https://explorer.palm.io/',
imageUrl: PALM_TOKEN_IMAGE_URL,
},
},
{
chainId: CHAIN_IDS.POLYGON,
nickname: `${POLYGON_DISPLAY_NAME} ${capitalize(NETWORK_TYPES.MAINNET)}`,
rpcUrl: `https://polygon-mainnet.infura.io/v3/${infuraProjectId}`,
ticker: CURRENCY_SYMBOLS.MATIC,
rpcPrefs: {
blockExplorerUrl: 'https://polygonscan.com/',
imageUrl: MATIC_TOKEN_IMAGE_URL,
},
},
];

@ -1,18 +1,10 @@
import { import {
MAINNET_CHAIN_ID,
ETH_SYMBOL,
TEST_ETH_SYMBOL,
BNB_SYMBOL,
TEST_ETH_TOKEN_IMAGE_URL, TEST_ETH_TOKEN_IMAGE_URL,
BNB_TOKEN_IMAGE_URL, BNB_TOKEN_IMAGE_URL,
BSC_CHAIN_ID,
POLYGON_CHAIN_ID,
MATIC_SYMBOL,
MATIC_TOKEN_IMAGE_URL, MATIC_TOKEN_IMAGE_URL,
GOERLI_CHAIN_ID,
AVALANCHE_CHAIN_ID,
AVALANCHE_SYMBOL,
AVAX_TOKEN_IMAGE_URL, AVAX_TOKEN_IMAGE_URL,
CURRENCY_SYMBOLS,
CHAIN_IDS,
} from './network'; } from './network';
export const QUOTES_EXPIRED_ERROR = 'quotes-expired'; export const QUOTES_EXPIRED_ERROR = 'quotes-expired';
@ -27,7 +19,7 @@ export const SWAPS_FETCH_ORDER_CONFLICT = 'swaps-fetch-order-conflict';
const DEFAULT_TOKEN_ADDRESS = '0x0000000000000000000000000000000000000000'; const DEFAULT_TOKEN_ADDRESS = '0x0000000000000000000000000000000000000000';
export const ETH_SWAPS_TOKEN_OBJECT = { export const ETH_SWAPS_TOKEN_OBJECT = {
symbol: ETH_SYMBOL, symbol: CURRENCY_SYMBOLS.ETH,
name: 'Ether', name: 'Ether',
address: DEFAULT_TOKEN_ADDRESS, address: DEFAULT_TOKEN_ADDRESS,
decimals: 18, decimals: 18,
@ -35,7 +27,7 @@ export const ETH_SWAPS_TOKEN_OBJECT = {
}; };
export const BNB_SWAPS_TOKEN_OBJECT = { export const BNB_SWAPS_TOKEN_OBJECT = {
symbol: BNB_SYMBOL, symbol: CURRENCY_SYMBOLS.BNB,
name: 'Binance Coin', name: 'Binance Coin',
address: DEFAULT_TOKEN_ADDRESS, address: DEFAULT_TOKEN_ADDRESS,
decimals: 18, decimals: 18,
@ -43,7 +35,7 @@ export const BNB_SWAPS_TOKEN_OBJECT = {
}; };
export const MATIC_SWAPS_TOKEN_OBJECT = { export const MATIC_SWAPS_TOKEN_OBJECT = {
symbol: MATIC_SYMBOL, symbol: CURRENCY_SYMBOLS.MATIC,
name: 'Matic', name: 'Matic',
address: DEFAULT_TOKEN_ADDRESS, address: DEFAULT_TOKEN_ADDRESS,
decimals: 18, decimals: 18,
@ -51,7 +43,7 @@ export const MATIC_SWAPS_TOKEN_OBJECT = {
}; };
export const AVAX_SWAPS_TOKEN_OBJECT = { export const AVAX_SWAPS_TOKEN_OBJECT = {
symbol: AVALANCHE_SYMBOL, symbol: CURRENCY_SYMBOLS.AVALANCHE,
name: 'Avalanche', name: 'Avalanche',
address: DEFAULT_TOKEN_ADDRESS, address: DEFAULT_TOKEN_ADDRESS,
decimals: 18, decimals: 18,
@ -59,7 +51,7 @@ export const AVAX_SWAPS_TOKEN_OBJECT = {
}; };
export const TEST_ETH_SWAPS_TOKEN_OBJECT = { export const TEST_ETH_SWAPS_TOKEN_OBJECT = {
symbol: TEST_ETH_SYMBOL, symbol: CURRENCY_SYMBOLS.TEST_ETH,
name: 'Test Ether', name: 'Test Ether',
address: DEFAULT_TOKEN_ADDRESS, address: DEFAULT_TOKEN_ADDRESS,
decimals: 18, decimals: 18,
@ -67,7 +59,7 @@ export const TEST_ETH_SWAPS_TOKEN_OBJECT = {
}; };
export const GOERLI_SWAPS_TOKEN_OBJECT = { export const GOERLI_SWAPS_TOKEN_OBJECT = {
symbol: ETH_SYMBOL, symbol: CURRENCY_SYMBOLS.ETH,
name: 'Ether', name: 'Ether',
address: DEFAULT_TOKEN_ADDRESS, address: DEFAULT_TOKEN_ADDRESS,
decimals: 18, decimals: 18,
@ -115,83 +107,83 @@ const POLYGON_DEFAULT_BLOCK_EXPLORER_URL = 'https://polygonscan.com/';
const AVALANCHE_DEFAULT_BLOCK_EXPLORER_URL = 'https://snowtrace.io/'; const AVALANCHE_DEFAULT_BLOCK_EXPLORER_URL = 'https://snowtrace.io/';
export const ALLOWED_PROD_SWAPS_CHAIN_IDS = [ export const ALLOWED_PROD_SWAPS_CHAIN_IDS = [
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
SWAPS_TESTNET_CHAIN_ID, SWAPS_TESTNET_CHAIN_ID,
BSC_CHAIN_ID, CHAIN_IDS.BSC,
POLYGON_CHAIN_ID, CHAIN_IDS.POLYGON,
AVALANCHE_CHAIN_ID, CHAIN_IDS.AVALANCHE,
]; ];
export const ALLOWED_DEV_SWAPS_CHAIN_IDS = [ export const ALLOWED_DEV_SWAPS_CHAIN_IDS = [
...ALLOWED_PROD_SWAPS_CHAIN_IDS, ...ALLOWED_PROD_SWAPS_CHAIN_IDS,
GOERLI_CHAIN_ID, CHAIN_IDS.GOERLI,
]; ];
export const ALLOWED_SMART_TRANSACTIONS_CHAIN_IDS = [ export const ALLOWED_SMART_TRANSACTIONS_CHAIN_IDS = [
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
GOERLI_CHAIN_ID, CHAIN_IDS.GOERLI,
]; ];
export const SWAPS_CHAINID_CONTRACT_ADDRESS_MAP = { export const SWAPS_CHAINID_CONTRACT_ADDRESS_MAP = {
[MAINNET_CHAIN_ID]: MAINNET_CONTRACT_ADDRESS, [CHAIN_IDS.MAINNET]: MAINNET_CONTRACT_ADDRESS,
[SWAPS_TESTNET_CHAIN_ID]: TESTNET_CONTRACT_ADDRESS, [SWAPS_TESTNET_CHAIN_ID]: TESTNET_CONTRACT_ADDRESS,
[BSC_CHAIN_ID]: BSC_CONTRACT_ADDRESS, [CHAIN_IDS.BSC]: BSC_CONTRACT_ADDRESS,
[POLYGON_CHAIN_ID]: POLYGON_CONTRACT_ADDRESS, [CHAIN_IDS.POLYGON]: POLYGON_CONTRACT_ADDRESS,
[GOERLI_CHAIN_ID]: TESTNET_CONTRACT_ADDRESS, [CHAIN_IDS.GOERLI]: TESTNET_CONTRACT_ADDRESS,
[AVALANCHE_CHAIN_ID]: AVALANCHE_CONTRACT_ADDRESS, [CHAIN_IDS.AVALANCHE]: AVALANCHE_CONTRACT_ADDRESS,
}; };
export const SWAPS_WRAPPED_TOKENS_ADDRESSES = { export const SWAPS_WRAPPED_TOKENS_ADDRESSES = {
[MAINNET_CHAIN_ID]: WETH_CONTRACT_ADDRESS, [CHAIN_IDS.MAINNET]: WETH_CONTRACT_ADDRESS,
[SWAPS_TESTNET_CHAIN_ID]: WETH_CONTRACT_ADDRESS, [SWAPS_TESTNET_CHAIN_ID]: WETH_CONTRACT_ADDRESS,
[BSC_CHAIN_ID]: WBNB_CONTRACT_ADDRESS, [CHAIN_IDS.BSC]: WBNB_CONTRACT_ADDRESS,
[POLYGON_CHAIN_ID]: WMATIC_CONTRACT_ADDRESS, [CHAIN_IDS.POLYGON]: WMATIC_CONTRACT_ADDRESS,
[GOERLI_CHAIN_ID]: WETH_GOERLI_CONTRACT_ADDRESS, [CHAIN_IDS.GOERLI]: WETH_GOERLI_CONTRACT_ADDRESS,
[AVALANCHE_CHAIN_ID]: WAVAX_CONTRACT_ADDRESS, [CHAIN_IDS.AVALANCHE]: WAVAX_CONTRACT_ADDRESS,
}; };
export const ALLOWED_CONTRACT_ADDRESSES = { export const ALLOWED_CONTRACT_ADDRESSES = {
[MAINNET_CHAIN_ID]: [ [CHAIN_IDS.MAINNET]: [
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[MAINNET_CHAIN_ID], SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.MAINNET],
SWAPS_WRAPPED_TOKENS_ADDRESSES[MAINNET_CHAIN_ID], SWAPS_WRAPPED_TOKENS_ADDRESSES[CHAIN_IDS.MAINNET],
], ],
[SWAPS_TESTNET_CHAIN_ID]: [ [SWAPS_TESTNET_CHAIN_ID]: [
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[SWAPS_TESTNET_CHAIN_ID], SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[SWAPS_TESTNET_CHAIN_ID],
SWAPS_WRAPPED_TOKENS_ADDRESSES[SWAPS_TESTNET_CHAIN_ID], SWAPS_WRAPPED_TOKENS_ADDRESSES[SWAPS_TESTNET_CHAIN_ID],
], ],
[GOERLI_CHAIN_ID]: [ [CHAIN_IDS.GOERLI]: [
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[GOERLI_CHAIN_ID], SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.GOERLI],
SWAPS_WRAPPED_TOKENS_ADDRESSES[GOERLI_CHAIN_ID], SWAPS_WRAPPED_TOKENS_ADDRESSES[CHAIN_IDS.GOERLI],
], ],
[BSC_CHAIN_ID]: [ [CHAIN_IDS.BSC]: [
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[BSC_CHAIN_ID], SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.BSC],
SWAPS_WRAPPED_TOKENS_ADDRESSES[BSC_CHAIN_ID], SWAPS_WRAPPED_TOKENS_ADDRESSES[CHAIN_IDS.BSC],
], ],
[POLYGON_CHAIN_ID]: [ [CHAIN_IDS.POLYGON]: [
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[POLYGON_CHAIN_ID], SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.POLYGON],
SWAPS_WRAPPED_TOKENS_ADDRESSES[POLYGON_CHAIN_ID], SWAPS_WRAPPED_TOKENS_ADDRESSES[CHAIN_IDS.POLYGON],
], ],
[AVALANCHE_CHAIN_ID]: [ [CHAIN_IDS.AVALANCHE]: [
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[AVALANCHE_CHAIN_ID], SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.AVALANCHE],
SWAPS_WRAPPED_TOKENS_ADDRESSES[AVALANCHE_CHAIN_ID], SWAPS_WRAPPED_TOKENS_ADDRESSES[CHAIN_IDS.AVALANCHE],
], ],
}; };
export const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = { export const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {
[MAINNET_CHAIN_ID]: ETH_SWAPS_TOKEN_OBJECT, [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,
[SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT, [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,
[BSC_CHAIN_ID]: BNB_SWAPS_TOKEN_OBJECT, [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,
[POLYGON_CHAIN_ID]: MATIC_SWAPS_TOKEN_OBJECT, [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,
[GOERLI_CHAIN_ID]: GOERLI_SWAPS_TOKEN_OBJECT, [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,
[AVALANCHE_CHAIN_ID]: AVAX_SWAPS_TOKEN_OBJECT, [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,
}; };
export const SWAPS_CHAINID_DEFAULT_BLOCK_EXPLORER_URL_MAP = { export const SWAPS_CHAINID_DEFAULT_BLOCK_EXPLORER_URL_MAP = {
[BSC_CHAIN_ID]: BSC_DEFAULT_BLOCK_EXPLORER_URL, [CHAIN_IDS.BSC]: BSC_DEFAULT_BLOCK_EXPLORER_URL,
[MAINNET_CHAIN_ID]: MAINNET_DEFAULT_BLOCK_EXPLORER_URL, [CHAIN_IDS.MAINNET]: MAINNET_DEFAULT_BLOCK_EXPLORER_URL,
[POLYGON_CHAIN_ID]: POLYGON_DEFAULT_BLOCK_EXPLORER_URL, [CHAIN_IDS.POLYGON]: POLYGON_DEFAULT_BLOCK_EXPLORER_URL,
[GOERLI_CHAIN_ID]: GOERLI_DEFAULT_BLOCK_EXPLORER_URL, [CHAIN_IDS.GOERLI]: GOERLI_DEFAULT_BLOCK_EXPLORER_URL,
[AVALANCHE_CHAIN_ID]: AVALANCHE_DEFAULT_BLOCK_EXPLORER_URL, [CHAIN_IDS.AVALANCHE]: AVALANCHE_DEFAULT_BLOCK_EXPLORER_URL,
}; };
export const ETHEREUM = 'ethereum'; export const ETHEREUM = 'ethereum';

@ -1,10 +1,4 @@
import { import { CHAIN_IDS, MAX_SAFE_CHAIN_ID } from '../constants/network';
MAX_SAFE_CHAIN_ID,
BSC_CHAIN_ID,
POLYGON_CHAIN_ID,
AVALANCHE_CHAIN_ID,
MAINNET_CHAIN_ID,
} from '../constants/network';
/** /**
* Checks whether the given number primitive chain ID is safe. * Checks whether the given number primitive chain ID is safe.
@ -43,10 +37,10 @@ export function isPrefixedFormattedHexString(value) {
*/ */
export function isTokenDetectionEnabledForNetwork(chainId) { export function isTokenDetectionEnabledForNetwork(chainId) {
switch (chainId) { switch (chainId) {
case MAINNET_CHAIN_ID: case CHAIN_IDS.MAINNET:
case BSC_CHAIN_ID: case CHAIN_IDS.BSC:
case POLYGON_CHAIN_ID: case CHAIN_IDS.POLYGON:
case AVALANCHE_CHAIN_ID: case CHAIN_IDS.AVALANCHE:
return true; return true;
default: default:
return false; return false;

@ -1,4 +1,4 @@
import { MAINNET_CHAIN_ID } from '../../shared/constants/network'; import { CHAIN_IDS } from '../../shared/constants/network';
const createGetSmartTransactionFeesApiResponse = () => { const createGetSmartTransactionFeesApiResponse = () => {
return { return {
@ -128,10 +128,10 @@ export const createSwapsMockStore = () => {
}, },
}, },
provider: { provider: {
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
}, },
cachedBalances: { cachedBalances: {
[MAINNET_CHAIN_ID]: 5, [CHAIN_IDS.MAINNET]: 5,
}, },
preferences: { preferences: {
showFiatInTestnets: true, showFiatInTestnets: true,
@ -408,7 +408,7 @@ export const createSwapsMockStore = () => {
liveness: true, liveness: true,
fees: createGetSmartTransactionFeesApiResponse(), fees: createGetSmartTransactionFeesApiResponse(),
smartTransactions: { smartTransactions: {
[MAINNET_CHAIN_ID]: [ [CHAIN_IDS.MAINNET]: [
{ {
uuid: 'uuid2', uuid: 'uuid2',
status: 'success', status: 'success',

@ -10,7 +10,7 @@ import { tick } from '../../../../../test/lib/tick';
import { renderWithProvider } from '../../../../../test/lib/render-helpers'; import { renderWithProvider } from '../../../../../test/lib/render-helpers';
import * as actions from '../../../../store/actions'; import * as actions from '../../../../store/actions';
import { KOVAN_CHAIN_ID } from '../../../../../shared/constants/network'; import { CHAIN_IDS } from '../../../../../shared/constants/network';
import UnconnectedAccountAlert from '.'; import UnconnectedAccountAlert from '.';
describe('Unconnected Account Alert', () => { describe('Unconnected Account Alert', () => {
@ -39,7 +39,7 @@ describe('Unconnected Account Alert', () => {
}; };
const cachedBalances = { const cachedBalances = {
[KOVAN_CHAIN_ID]: { [CHAIN_IDS]: {
'0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc': '0x0', '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc': '0x0',
'0xec1adf982415d2ef5ec55899b9bfb8bc0f29251b': '0x0', '0xec1adf982415d2ef5ec55899b9bfb8bc0f29251b': '0x0',
}, },
@ -63,7 +63,7 @@ describe('Unconnected Account Alert', () => {
cachedBalances, cachedBalances,
keyrings, keyrings,
provider: { provider: {
chainId: KOVAN_CHAIN_ID, chainId: CHAIN_IDS,
}, },
permissionHistory: { permissionHistory: {
'https://test.dapp': { 'https://test.dapp': {

@ -33,14 +33,7 @@ import {
checkAndUpdateSingleCollectibleOwnershipStatus, checkAndUpdateSingleCollectibleOwnershipStatus,
removeAndIgnoreCollectible, removeAndIgnoreCollectible,
} from '../../../store/actions'; } from '../../../store/actions';
import { import { CHAIN_IDS } from '../../../../shared/constants/network';
GOERLI_CHAIN_ID,
KOVAN_CHAIN_ID,
MAINNET_CHAIN_ID,
POLYGON_CHAIN_ID,
RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID,
} from '../../../../shared/constants/network';
import { getEnvironmentType } from '../../../../app/scripts/lib/util'; import { getEnvironmentType } from '../../../../app/scripts/lib/util';
import { ENVIRONMENT_TYPE_POPUP } from '../../../../shared/constants/app'; import { ENVIRONMENT_TYPE_POPUP } from '../../../../shared/constants/app';
import CollectibleOptions from '../collectible-options/collectible-options'; import CollectibleOptions from '../collectible-options/collectible-options';
@ -99,14 +92,14 @@ export default function CollectibleDetails({ collectible }) {
const getOpenSeaLink = () => { const getOpenSeaLink = () => {
switch (currentNetwork) { switch (currentNetwork) {
case MAINNET_CHAIN_ID: case CHAIN_IDS.MAINNET:
return `https://opensea.io/assets/${address}/${tokenId}`; return `https://opensea.io/assets/${address}/${tokenId}`;
case POLYGON_CHAIN_ID: case CHAIN_IDS.POLYGON:
return `https://opensea.io/assets/matic/${address}/${tokenId}`; return `https://opensea.io/assets/matic/${address}/${tokenId}`;
case GOERLI_CHAIN_ID: case CHAIN_IDS.GOERLI:
case KOVAN_CHAIN_ID: case CHAIN_IDS.KOVAN:
case ROPSTEN_CHAIN_ID: case CHAIN_IDS.ROPSTEN:
case RINKEBY_CHAIN_ID: case CHAIN_IDS.RINKEBY:
return `https://testnets.opensea.io/assets/${address}/${tokenId}`; return `https://testnets.opensea.io/assets/${address}/${tokenId}`;
default: default:
return null; return null;

@ -7,8 +7,8 @@ import Button from '../../ui/button';
import * as actions from '../../../store/actions'; import * as actions from '../../../store/actions';
import { openAlert as displayInvalidCustomNetworkAlert } from '../../../ducks/alerts/invalid-custom-network'; import { openAlert as displayInvalidCustomNetworkAlert } from '../../../ducks/alerts/invalid-custom-network';
import { import {
NETWORK_TYPE_RPC,
LOCALHOST_RPC_URL, LOCALHOST_RPC_URL,
NETWORK_TYPES,
} from '../../../../shared/constants/network'; } from '../../../../shared/constants/network';
import { isPrefixedFormattedHexString } from '../../../../shared/modules/network.utils'; import { isPrefixedFormattedHexString } from '../../../../shared/modules/network.utils';
@ -152,7 +152,7 @@ class NetworkDropdown extends Component {
return reversedRpcListDetail.map((entry) => { return reversedRpcListDetail.map((entry) => {
const { rpcUrl, chainId, ticker = 'ETH', nickname = '' } = entry; const { rpcUrl, chainId, ticker = 'ETH', nickname = '' } = entry;
const isCurrentRpcTarget = const isCurrentRpcTarget =
provider.type === NETWORK_TYPE_RPC && rpcUrl === provider.rpcUrl; provider.type === NETWORK_TYPES.RPC && rpcUrl === provider.rpcUrl;
return ( return (
<DropdownMenuItem <DropdownMenuItem

@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import { screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import { MAINNET_CHAIN_ID } from '../../../../../shared/constants/network'; import { CHAIN_IDS } from '../../../../../shared/constants/network';
import { GasFeeContextProvider } from '../../../../contexts/gasFee'; import { GasFeeContextProvider } from '../../../../contexts/gasFee';
import { renderWithProvider } from '../../../../../test/jest'; import { renderWithProvider } from '../../../../../test/jest';
import configureStore from '../../../../store/store'; import configureStore from '../../../../store/store';
@ -20,7 +20,7 @@ jest.mock('../../../../store/actions', () => ({
const render = () => { const render = () => {
const store = configureStore({ const store = configureStore({
metamask: { metamask: {
provider: { chainId: MAINNET_CHAIN_ID }, provider: { chainId: CHAIN_IDS.MAINNET },
cachedBalances: {}, cachedBalances: {},
accounts: { accounts: {
'0xAddress': { '0xAddress': {

@ -1,5 +1,5 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { NETWORK_TYPE_RPC } from '../../../../shared/constants/network'; import { NETWORK_TYPES } from '../../../../shared/constants/network';
import * as actions from '../../../store/actions'; import * as actions from '../../../store/actions';
import { getNetworkIdentifier, isNetworkLoading } from '../../../selectors'; import { getNetworkIdentifier, isNetworkLoading } from '../../../selectors';
import LoadingNetworkScreen from './loading-network-screen.component'; import LoadingNetworkScreen from './loading-network-screen.component';
@ -10,7 +10,7 @@ const mapStateToProps = (state) => {
const { rpcUrl, chainId, ticker, nickname, type } = provider; const { rpcUrl, chainId, ticker, nickname, type } = provider;
const setProviderArgs = const setProviderArgs =
type === NETWORK_TYPE_RPC type === NETWORK_TYPES.RPC
? [rpcUrl, chainId, ticker, nickname] ? [rpcUrl, chainId, ticker, nickname]
: [provider.type]; : [provider.type];

@ -2,14 +2,14 @@ import React from 'react';
import configureStore from 'redux-mock-store'; import configureStore from 'redux-mock-store';
import { fireEvent, screen, waitFor } from '@testing-library/react'; import { fireEvent, screen, waitFor } from '@testing-library/react';
import { renderWithProvider } from '../../../../test/lib/render-helpers'; import { renderWithProvider } from '../../../../test/lib/render-helpers';
import { ROPSTEN_CHAIN_ID } from '../../../../shared/constants/network'; import { CHAIN_IDS } from '../../../../shared/constants/network';
import MenuBar from './menu-bar'; import MenuBar from './menu-bar';
const initState = { const initState = {
activeTab: {}, activeTab: {},
metamask: { metamask: {
provider: { provider: {
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
}, },
selectedAddress: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc', selectedAddress: '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc',
identities: { identities: {

@ -3,8 +3,8 @@ import PropTypes from 'prop-types';
import classnames from 'classnames'; import classnames from 'classnames';
import { useSelector } from 'react-redux'; import { useSelector } from 'react-redux';
import { import {
NETWORK_TYPE_RPC, NETWORK_TYPES,
NETWORK_TYPE_TO_ID_MAP, BUILT_IN_NETWORKS,
} from '../../../../shared/constants/network'; } from '../../../../shared/constants/network';
import LoadingIndicator from '../../ui/loading-indicator'; import LoadingIndicator from '../../ui/loading-indicator';
@ -48,12 +48,14 @@ export default function NetworkDisplay({
> >
<ColorIndicator <ColorIndicator
color={ color={
networkType === NETWORK_TYPE_RPC ? COLORS.ICON_MUTED : networkType networkType === NETWORK_TYPES.RPC
? COLORS.ICON_MUTED
: networkType
} }
size={indicatorSize} size={indicatorSize}
type={ColorIndicator.TYPES.FILLED} type={ColorIndicator.TYPES.FILLED}
iconClassName={ iconClassName={
networkType === NETWORK_TYPE_RPC && indicatorSize !== SIZES.XS networkType === NETWORK_TYPES.RPC && indicatorSize !== SIZES.XS
? 'fa fa-question' ? 'fa fa-question'
: undefined : undefined
} }
@ -66,7 +68,7 @@ export default function NetworkDisplay({
) : null ) : null
} }
label={ label={
networkType === NETWORK_TYPE_RPC networkType === NETWORK_TYPES.RPC
? networkNickname ?? t('privateNetwork') ? networkNickname ?? t('privateNetwork')
: t(networkType) : t(networkType)
} }
@ -95,8 +97,8 @@ NetworkDisplay.propTypes = {
*/ */
targetNetwork: PropTypes.shape({ targetNetwork: PropTypes.shape({
type: PropTypes.oneOf([ type: PropTypes.oneOf([
...Object.keys(NETWORK_TYPE_TO_ID_MAP), ...Object.keys(BUILT_IN_NETWORKS),
NETWORK_TYPE_RPC, NETWORK_TYPES.RPC,
]), ]),
nickname: PropTypes.string, nickname: PropTypes.string,
}), }),

@ -1,8 +1,8 @@
import React from 'react'; import React from 'react';
import { import {
NETWORK_TYPE_TO_ID_MAP, BUILT_IN_NETWORKS,
NETWORK_TYPE_RPC, NETWORK_TYPES,
} from '../../../../shared/constants/network'; } from '../../../../shared/constants/network';
import { SIZES } from '../../../helpers/constants/design-system'; import { SIZES } from '../../../helpers/constants/design-system';
@ -21,7 +21,7 @@ export default {
}, },
targetNetwork: { targetNetwork: {
control: 'select', control: 'select',
options: [...Object.keys(NETWORK_TYPE_TO_ID_MAP), NETWORK_TYPE_RPC], options: [...Object.keys(BUILT_IN_NETWORKS), NETWORK_TYPES.RPC],
}, },
disabled: { disabled: {
control: 'boolean', control: 'boolean',
@ -51,8 +51,8 @@ DefaultStory.storyName = 'Default';
export const TargetNetwork = (args) => { export const TargetNetwork = (args) => {
const targetNetworkArr = [ const targetNetworkArr = [
...Object.keys(NETWORK_TYPE_TO_ID_MAP), ...Object.keys(BUILT_IN_NETWORKS),
NETWORK_TYPE_RPC, NETWORK_TYPES.RPC,
]; ];
return ( return (
<> <>
@ -72,8 +72,8 @@ export const TargetNetwork = (args) => {
export const DisplayOnly = (args) => { export const DisplayOnly = (args) => {
const targetNetworkArr = [ const targetNetworkArr = [
...Object.keys(NETWORK_TYPE_TO_ID_MAP), ...Object.keys(BUILT_IN_NETWORKS),
NETWORK_TYPE_RPC, NETWORK_TYPES.RPC,
]; ];
return ( return (
<> <>

@ -1,8 +1,5 @@
import { GAS_LIMITS } from '../../../../shared/constants/gas'; import { GAS_LIMITS } from '../../../../shared/constants/gas';
import { import { CHAIN_IDS, NETWORK_IDS } from '../../../../shared/constants/network';
ROPSTEN_CHAIN_ID,
ROPSTEN_NETWORK_ID,
} from '../../../../shared/constants/network';
import { import {
TRANSACTION_STATUSES, TRANSACTION_STATUSES,
TRANSACTION_TYPES, TRANSACTION_TYPES,
@ -27,8 +24,8 @@ describe('TransactionActivityLog utils', () => {
id: 6400627574331058, id: 6400627574331058,
time: 1543958845581, time: 1543958845581,
status: TRANSACTION_STATUSES.UNAPPROVED, status: TRANSACTION_STATUSES.UNAPPROVED,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
loadingDefaults: true, loadingDefaults: true,
txParams: { txParams: {
from: '0x50a9d56c2b8ba9a5c7f2c08c3d26e0499f23a706', from: '0x50a9d56c2b8ba9a5c7f2c08c3d26e0499f23a706',
@ -75,8 +72,8 @@ describe('TransactionActivityLog utils', () => {
], ],
id: 6400627574331058, id: 6400627574331058,
loadingDefaults: false, loadingDefaults: false,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
status: TRANSACTION_STATUSES.DROPPED, status: TRANSACTION_STATUSES.DROPPED,
submittedTime: 1543958848135, submittedTime: 1543958848135,
time: 1543958845581, time: 1543958845581,
@ -97,8 +94,8 @@ describe('TransactionActivityLog utils', () => {
id: 6400627574331060, id: 6400627574331060,
time: 1543958857697, time: 1543958857697,
status: TRANSACTION_STATUSES.UNAPPROVED, status: TRANSACTION_STATUSES.UNAPPROVED,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
loadingDefaults: false, loadingDefaults: false,
txParams: { txParams: {
from: '0x50a9d56c2b8ba9a5c7f2c08c3d26e0499f23a706', from: '0x50a9d56c2b8ba9a5c7f2c08c3d26e0499f23a706',
@ -168,8 +165,8 @@ describe('TransactionActivityLog utils', () => {
id: 6400627574331060, id: 6400627574331060,
lastGasPrice: '0x4190ab00', lastGasPrice: '0x4190ab00',
loadingDefaults: false, loadingDefaults: false,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
status: TRANSACTION_STATUSES.CONFIRMED, status: TRANSACTION_STATUSES.CONFIRMED,
submittedTime: 1543958860054, submittedTime: 1543958860054,
time: 1543958857697, time: 1543958857697,
@ -191,8 +188,8 @@ describe('TransactionActivityLog utils', () => {
const expected = [ const expected = [
{ {
id: 6400627574331058, id: 6400627574331058,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
hash: '0xa14f13d36b3901e352ce3a7acb9b47b001e5a3370f06232a0953c6fc6fad91b3', hash: '0xa14f13d36b3901e352ce3a7acb9b47b001e5a3370f06232a0953c6fc6fad91b3',
eventKey: 'transactionCreated', eventKey: 'transactionCreated',
timestamp: 1543958845581, timestamp: 1543958845581,
@ -200,8 +197,8 @@ describe('TransactionActivityLog utils', () => {
}, },
{ {
id: 6400627574331058, id: 6400627574331058,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
hash: '0xa14f13d36b3901e352ce3a7acb9b47b001e5a3370f06232a0953c6fc6fad91b3', hash: '0xa14f13d36b3901e352ce3a7acb9b47b001e5a3370f06232a0953c6fc6fad91b3',
eventKey: 'transactionSubmitted', eventKey: 'transactionSubmitted',
timestamp: 1543958848147, timestamp: 1543958848147,
@ -209,8 +206,8 @@ describe('TransactionActivityLog utils', () => {
}, },
{ {
id: 6400627574331060, id: 6400627574331060,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
hash: '0xecbe181ee67c4291d04a7cb9ffbf1d5d831e4fbaa89994fd06bab5dd4cc79b33', hash: '0xecbe181ee67c4291d04a7cb9ffbf1d5d831e4fbaa89994fd06bab5dd4cc79b33',
eventKey: 'transactionResubmitted', eventKey: 'transactionResubmitted',
timestamp: 1543958860061, timestamp: 1543958860061,
@ -218,8 +215,8 @@ describe('TransactionActivityLog utils', () => {
}, },
{ {
id: 6400627574331060, id: 6400627574331060,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
hash: '0xecbe181ee67c4291d04a7cb9ffbf1d5d831e4fbaa89994fd06bab5dd4cc79b33', hash: '0xecbe181ee67c4291d04a7cb9ffbf1d5d831e4fbaa89994fd06bab5dd4cc79b33',
eventKey: 'transactionConfirmed', eventKey: 'transactionConfirmed',
timestamp: 1543958897165, timestamp: 1543958897165,
@ -256,8 +253,8 @@ describe('TransactionActivityLog utils', () => {
{ {
id: 5559712943815343, id: 5559712943815343,
loadingDefaults: true, loadingDefaults: true,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
status: TRANSACTION_STATUSES.UNAPPROVED, status: TRANSACTION_STATUSES.UNAPPROVED,
time: 1535507561452, time: 1535507561452,
txParams: { txParams: {
@ -397,8 +394,8 @@ describe('TransactionActivityLog utils', () => {
value: '0x2386f26fc10000', value: '0x2386f26fc10000',
}, },
hash: '0xabc', hash: '0xabc',
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
}; };
const expectedResult = [ const expectedResult = [
@ -408,8 +405,8 @@ describe('TransactionActivityLog utils', () => {
value: '0x2386f26fc10000', value: '0x2386f26fc10000',
id: 1, id: 1,
hash: '0xabc', hash: '0xabc',
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
}, },
{ {
eventKey: 'transactionSubmitted', eventKey: 'transactionSubmitted',
@ -417,8 +414,8 @@ describe('TransactionActivityLog utils', () => {
value: '0x2632e314a000', value: '0x2632e314a000',
id: 1, id: 1,
hash: '0xabc', hash: '0xabc',
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
}, },
{ {
eventKey: 'transactionConfirmed', eventKey: 'transactionConfirmed',
@ -426,8 +423,8 @@ describe('TransactionActivityLog utils', () => {
value: '0x2632e314a000', value: '0x2632e314a000',
id: 1, id: 1,
hash: '0xabc', hash: '0xabc',
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
}, },
]; ];

@ -5,7 +5,6 @@ import { I18nContext } from '../../../contexts/i18n';
import Popover from '../popover'; import Popover from '../popover';
import Button from '../button'; import Button from '../button';
import Identicon from '../identicon/identicon.component'; import Identicon from '../identicon/identicon.component';
import { NETWORK_TYPE_RPC } from '../../../../shared/constants/network';
import Box from '../box'; import Box from '../box';
import { import {
ALIGN_ITEMS, ALIGN_ITEMS,
@ -26,6 +25,7 @@ import {
import { IMPORT_TOKEN_ROUTE } from '../../../helpers/constants/routes'; import { IMPORT_TOKEN_ROUTE } from '../../../helpers/constants/routes';
import Chip from '../chip/chip'; import Chip from '../chip/chip';
import { setFirstTimeUsedNetwork } from '../../../store/actions'; import { setFirstTimeUsedNetwork } from '../../../store/actions';
import { NETWORK_TYPES } from '../../../../shared/constants/network';
const NewNetworkInfo = () => { const NewNetworkInfo = () => {
const t = useContext(I18nContext); const t = useContext(I18nContext);
@ -92,7 +92,7 @@ const NewNetworkInfo = () => {
backgroundColor={COLORS.BACKGROUND_ALTERNATIVE} backgroundColor={COLORS.BACKGROUND_ALTERNATIVE}
maxContent={false} maxContent={false}
label={ label={
currentProvider.type === NETWORK_TYPE_RPC currentProvider.type === NETWORK_TYPES.RPC
? currentProvider.nickname ?? t('privateNetwork') ? currentProvider.nickname ?? t('privateNetwork')
: t(currentProvider.type) : t(currentProvider.type)
} }

@ -1,10 +1,7 @@
import configureMockStore from 'redux-mock-store'; import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk'; import thunk from 'redux-thunk';
import sinon from 'sinon'; import sinon from 'sinon';
import { import { CHAIN_IDS, NETWORK_IDS } from '../../../shared/constants/network';
ROPSTEN_CHAIN_ID,
ROPSTEN_NETWORK_ID,
} from '../../../shared/constants/network';
import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction'; import { TRANSACTION_STATUSES } from '../../../shared/constants/transaction';
import ConfirmTransactionReducer, * as actions from './confirm-transaction.duck'; import ConfirmTransactionReducer, * as actions from './confirm-transaction.duck';
@ -278,7 +275,7 @@ describe('Confirm Transaction Duck', () => {
history: [], history: [],
id: 2603411941761054, id: 2603411941761054,
loadingDefaults: false, loadingDefaults: false,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
origin: 'faucet.metamask.io', origin: 'faucet.metamask.io',
status: TRANSACTION_STATUSES.UNAPPROVED, status: TRANSACTION_STATUSES.UNAPPROVED,
time: 1530838113716, time: 1530838113716,
@ -344,16 +341,16 @@ describe('Confirm Transaction Duck', () => {
metamask: { metamask: {
conversionRate: 468.58, conversionRate: 468.58,
currentCurrency: 'usd', currentCurrency: 'usd',
network: ROPSTEN_NETWORK_ID, network: NETWORK_IDS.ROPSTEN,
provider: { provider: {
chainId: ROPSTEN_CHAIN_ID, chainId: CHAIN_IDS.ROPSTEN,
}, },
unapprovedTxs: { unapprovedTxs: {
2603411941761054: { 2603411941761054: {
history: [], history: [],
id: 2603411941761054, id: 2603411941761054,
loadingDefaults: false, loadingDefaults: false,
metamaskNetworkId: ROPSTEN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.ROPSTEN,
origin: 'faucet.metamask.io', origin: 'faucet.metamask.io',
status: TRANSACTION_STATUSES.UNAPPROVED, status: TRANSACTION_STATUSES.UNAPPROVED,
time: 1530838113716, time: 1530838113716,

@ -8,7 +8,7 @@ import { ethers } from 'ethers';
import { getCurrentChainId } from '../selectors'; import { getCurrentChainId } from '../selectors';
import { import {
CHAIN_ID_TO_NETWORK_ID_MAP, CHAIN_ID_TO_NETWORK_ID_MAP,
MAINNET_NETWORK_ID, NETWORK_IDS,
NETWORK_ID_TO_ETHERS_NETWORK_NAME_MAP, NETWORK_ID_TO_ETHERS_NETWORK_NAME_MAP,
} from '../../shared/constants/network'; } from '../../shared/constants/network';
import { import {
@ -62,7 +62,7 @@ const slice = createSlice({
error.message === 'ENS name not defined.' error.message === 'ENS name not defined.'
) { ) {
state.error = state.error =
network === MAINNET_NETWORK_ID network === NETWORK_IDS.MAINNET
? ENS_NO_ADDRESS_FOR_NAME ? ENS_NO_ADDRESS_FOR_NAME
: ENS_NOT_FOUND_ON_NETWORK; : ENS_NOT_FOUND_ON_NETWORK;
} else if (error.message === 'Illegal character for ENS.') { } else if (error.message === 'Illegal character for ENS.') {

@ -5,7 +5,7 @@ import {
GAS_ESTIMATE_TYPES, GAS_ESTIMATE_TYPES,
NETWORK_CONGESTION_THRESHOLDS, NETWORK_CONGESTION_THRESHOLDS,
} from '../../../shared/constants/gas'; } from '../../../shared/constants/gas';
import { NETWORK_TYPE_RPC } from '../../../shared/constants/network'; import { NETWORK_TYPES } from '../../../shared/constants/network';
import { import {
accountsWithSendEtherInfoSelector, accountsWithSendEtherInfoSelector,
checkNetworkAndAccountSupports1559, checkNetworkAndAccountSupports1559,
@ -65,7 +65,7 @@ export default function reduceMetamask(state = {}, action) {
return { return {
...metamaskState, ...metamaskState,
provider: { provider: {
type: NETWORK_TYPE_RPC, type: NETWORK_TYPES.RPC,
rpcUrl: action.value, rpcUrl: action.value,
}, },
}; };

@ -10,10 +10,7 @@ import {
KNOWN_RECIPIENT_ADDRESS_WARNING, KNOWN_RECIPIENT_ADDRESS_WARNING,
NEGATIVE_ETH_ERROR, NEGATIVE_ETH_ERROR,
} from '../../pages/send/send.constants'; } from '../../pages/send/send.constants';
import { import { CHAIN_IDS } from '../../../shared/constants/network';
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
} from '../../../shared/constants/network';
import { GAS_ESTIMATE_TYPES, GAS_LIMITS } from '../../../shared/constants/gas'; import { GAS_ESTIMATE_TYPES, GAS_LIMITS } from '../../../shared/constants/gas';
import { import {
ASSET_TYPES, ASSET_TYPES,
@ -1577,10 +1574,10 @@ describe('Send Slice', () => {
blockGasLimit: '', blockGasLimit: '',
selectedAddress: '', selectedAddress: '',
provider: { provider: {
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
}, },
cachedBalances: { cachedBalances: {
[RINKEBY_CHAIN_ID]: { [CHAIN_IDS.RINKEBY]: {
'0xAddress': '0x0', '0xAddress': '0x0',
}, },
}, },
@ -2169,7 +2166,7 @@ describe('Send Slice', () => {
}, },
metamask: { metamask: {
provider: { provider: {
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
}, },
}, },
}; };
@ -2218,7 +2215,7 @@ describe('Send Slice', () => {
}, },
metamask: { metamask: {
provider: { provider: {
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
}, },
}, },
}; };
@ -2376,11 +2373,11 @@ describe('Send Slice', () => {
gasEstimateType: GAS_ESTIMATE_TYPES.NONE, gasEstimateType: GAS_ESTIMATE_TYPES.NONE,
gasFeeEstimates: {}, gasFeeEstimates: {},
provider: { provider: {
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
}, },
tokens: [], tokens: [],
addressBook: { addressBook: {
[RINKEBY_CHAIN_ID]: {}, [CHAIN_IDS.RINKEBY]: {},
}, },
identities: {}, identities: {},
accounts: { accounts: {
@ -2390,7 +2387,7 @@ describe('Send Slice', () => {
}, },
}, },
cachedBalances: { cachedBalances: {
[RINKEBY_CHAIN_ID]: { [CHAIN_IDS.RINKEBY]: {
'0xAddress': '0x0', '0xAddress': '0x0',
}, },
}, },
@ -2511,11 +2508,11 @@ describe('Send Slice', () => {
blockGasLimit: '0x3a98', blockGasLimit: '0x3a98',
selectedAddress: '', selectedAddress: '',
provider: { provider: {
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
}, },
tokens: [], tokens: [],
addressBook: { addressBook: {
[RINKEBY_CHAIN_ID]: {}, [CHAIN_IDS.RINKEBY]: {},
}, },
identities: {}, identities: {},
accounts: { accounts: {
@ -2525,7 +2522,7 @@ describe('Send Slice', () => {
}, },
}, },
cachedBalances: { cachedBalances: {
[RINKEBY_CHAIN_ID]: { [CHAIN_IDS.RINKEBY]: {
'0xAddress': '0x0', '0xAddress': '0x0',
}, },
}, },
@ -2685,7 +2682,7 @@ describe('Send Slice', () => {
blockGasLimit: '0x3a98', blockGasLimit: '0x3a98',
selectedAddress: '', selectedAddress: '',
provider: { provider: {
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
}, },
tokens: [ tokens: [
{ {
@ -2700,7 +2697,7 @@ describe('Send Slice', () => {
}, },
}, },
addressBook: { addressBook: {
[RINKEBY_CHAIN_ID]: {}, [CHAIN_IDS.RINKEBY]: {},
}, },
identities: {}, identities: {},
accounts: { accounts: {
@ -2710,7 +2707,7 @@ describe('Send Slice', () => {
}, },
}, },
cachedBalances: { cachedBalances: {
[RINKEBY_CHAIN_ID]: { [CHAIN_IDS.RINKEBY]: {
'0xAddress': '0x0', '0xAddress': '0x0',
}, },
}, },
@ -2915,7 +2912,7 @@ describe('Send Slice', () => {
expect( expect(
getGasInputMode({ getGasInputMode({
metamask: { metamask: {
provider: { chainId: MAINNET_CHAIN_ID }, provider: { chainId: CHAIN_IDS.MAINNET },
featureFlags: { advancedInlineGas: false }, featureFlags: { advancedInlineGas: false },
}, },
send: initialState, send: initialState,
@ -2941,7 +2938,7 @@ describe('Send Slice', () => {
expect( expect(
getGasInputMode({ getGasInputMode({
metamask: { metamask: {
provider: { chainId: MAINNET_CHAIN_ID }, provider: { chainId: CHAIN_IDS.MAINNET },
featureFlags: { advancedInlineGas: true }, featureFlags: { advancedInlineGas: true },
}, },
send: initialState, send: initialState,
@ -2953,7 +2950,7 @@ describe('Send Slice', () => {
expect( expect(
getGasInputMode({ getGasInputMode({
metamask: { metamask: {
provider: { chainId: MAINNET_CHAIN_ID }, provider: { chainId: CHAIN_IDS.MAINNET },
featureFlags: { advancedInlineGas: false }, featureFlags: { advancedInlineGas: false },
gasEstimateType: GAS_ESTIMATE_TYPES.ETH_GASPRICE, gasEstimateType: GAS_ESTIMATE_TYPES.ETH_GASPRICE,
}, },
@ -2967,7 +2964,7 @@ describe('Send Slice', () => {
expect( expect(
getGasInputMode({ getGasInputMode({
metamask: { metamask: {
provider: { chainId: MAINNET_CHAIN_ID }, provider: { chainId: CHAIN_IDS.MAINNET },
featureFlags: { advancedInlineGas: false }, featureFlags: { advancedInlineGas: false },
gasEstimateType: GAS_ESTIMATE_TYPES.ETH_GASPRICE, gasEstimateType: GAS_ESTIMATE_TYPES.ETH_GASPRICE,
}, },
@ -2981,7 +2978,7 @@ describe('Send Slice', () => {
expect( expect(
getGasInputMode({ getGasInputMode({
metamask: { metamask: {
provider: { chainId: MAINNET_CHAIN_ID }, provider: { chainId: CHAIN_IDS.MAINNET },
featureFlags: { advancedInlineGas: true }, featureFlags: { advancedInlineGas: true },
}, },
send: { send: {

@ -3,12 +3,7 @@ import nock from 'nock';
import { MOCKS, createSwapsMockStore } from '../../../test/jest'; import { MOCKS, createSwapsMockStore } from '../../../test/jest';
import { setSwapsLiveness, setSwapsFeatureFlags } from '../../store/actions'; import { setSwapsLiveness, setSwapsFeatureFlags } from '../../store/actions';
import { setStorageItem } from '../../helpers/utils/storage-helpers'; import { setStorageItem } from '../../helpers/utils/storage-helpers';
import { import { CHAIN_IDS } from '../../../shared/constants/network';
MAINNET_CHAIN_ID,
GOERLI_CHAIN_ID,
BSC_CHAIN_ID,
POLYGON_CHAIN_ID,
} from '../../../shared/constants/network';
import * as swaps from './swaps'; import * as swaps from './swaps';
jest.mock('../../store/actions.js', () => ({ jest.mock('../../store/actions.js', () => ({
@ -270,19 +265,19 @@ describe('Ducks - Swaps', () => {
it('returns false if feature flag is enabled, not a HW and is Polygon network', () => { it('returns false if feature flag is enabled, not a HW and is Polygon network', () => {
const state = createSwapsMockStore(); const state = createSwapsMockStore();
state.metamask.provider.chainId = POLYGON_CHAIN_ID; state.metamask.provider.chainId = CHAIN_IDS.POLYGON;
expect(swaps.getSmartTransactionsEnabled(state)).toBe(false); expect(swaps.getSmartTransactionsEnabled(state)).toBe(false);
}); });
it('returns false if feature flag is enabled, not a HW and is BSC network', () => { it('returns false if feature flag is enabled, not a HW and is BSC network', () => {
const state = createSwapsMockStore(); const state = createSwapsMockStore();
state.metamask.provider.chainId = BSC_CHAIN_ID; state.metamask.provider.chainId = CHAIN_IDS.BSC;
expect(swaps.getSmartTransactionsEnabled(state)).toBe(false); expect(swaps.getSmartTransactionsEnabled(state)).toBe(false);
}); });
it('returns true if feature flag is enabled, not a HW and is Goerli network', () => { it('returns true if feature flag is enabled, not a HW and is Goerli network', () => {
const state = createSwapsMockStore(); const state = createSwapsMockStore();
state.metamask.provider.chainId = GOERLI_CHAIN_ID; state.metamask.provider.chainId = CHAIN_IDS.GOERLI;
expect(swaps.getSmartTransactionsEnabled(state)).toBe(true); expect(swaps.getSmartTransactionsEnabled(state)).toBe(true);
}); });
@ -305,7 +300,7 @@ describe('Ducks - Swaps', () => {
const state = createSwapsMockStore(); const state = createSwapsMockStore();
expect(swaps.getCurrentSmartTransactions(state)).toMatchObject( expect(swaps.getCurrentSmartTransactions(state)).toMatchObject(
state.metamask.smartTransactionsState.smartTransactions[ state.metamask.smartTransactionsState.smartTransactions[
MAINNET_CHAIN_ID CHAIN_IDS.MAINNET
], ],
); );
}); });

@ -1,13 +1,10 @@
import { import { CHAIN_IDS, NETWORK_IDS } from '../../../shared/constants/network';
MAINNET_CHAIN_ID,
MAINNET_NETWORK_ID,
} from '../../../shared/constants/network';
import txHelper from './tx-helper'; import txHelper from './tx-helper';
describe('txHelper', () => { describe('txHelper', () => {
it('always shows the oldest tx first', () => { it('always shows the oldest tx first', () => {
const metamaskNetworkId = MAINNET_NETWORK_ID; const metamaskNetworkId = NETWORK_IDS.MAINNET;
const chainId = MAINNET_CHAIN_ID; const chainId = CHAIN_IDS.MAINNET;
const txs = { const txs = {
a: { metamaskNetworkId, time: 3 }, a: { metamaskNetworkId, time: 3 },
b: { metamaskNetworkId, time: 1 }, b: { metamaskNetworkId, time: 1 },

@ -6,14 +6,7 @@ import { DateTime } from 'luxon';
import { getFormattedIpfsUrl } from '@metamask/controllers/dist/util'; import { getFormattedIpfsUrl } from '@metamask/controllers/dist/util';
import slip44 from '@metamask/slip44'; import slip44 from '@metamask/slip44';
import { addHexPrefix } from '../../../app/scripts/lib/util'; import { addHexPrefix } from '../../../app/scripts/lib/util';
import { import { CHAIN_IDS } from '../../../shared/constants/network';
GOERLI_CHAIN_ID,
KOVAN_CHAIN_ID,
LOCALHOST_CHAIN_ID,
MAINNET_CHAIN_ID,
RINKEBY_CHAIN_ID,
ROPSTEN_CHAIN_ID,
} from '../../../shared/constants/network';
import { toChecksumHexAddress } from '../../../shared/modules/hexstring-utils'; import { toChecksumHexAddress } from '../../../shared/modules/hexstring-utils';
import { import {
TRUNCATED_ADDRESS_START_CHARS, TRUNCATED_ADDRESS_START_CHARS,
@ -52,12 +45,12 @@ export function formatDateWithYearContext(
export function isDefaultMetaMaskChain(chainId) { export function isDefaultMetaMaskChain(chainId) {
if ( if (
!chainId || !chainId ||
chainId === MAINNET_CHAIN_ID || chainId === CHAIN_IDS.MAINNET ||
chainId === ROPSTEN_CHAIN_ID || chainId === CHAIN_IDS.ROPSTEN ||
chainId === RINKEBY_CHAIN_ID || chainId === CHAIN_IDS.RINKEBY ||
chainId === KOVAN_CHAIN_ID || chainId === CHAIN_IDS.KOVAN ||
chainId === GOERLI_CHAIN_ID || chainId === CHAIN_IDS.GOERLI ||
chainId === LOCALHOST_CHAIN_ID chainId === CHAIN_IDS.LOCALHOST
) { ) {
return true; return true;
} }

@ -17,17 +17,7 @@ import { getSwapsTokens } from '../ducks/swaps/swaps';
import { isSwapsDefaultTokenSymbol } from '../../shared/modules/swaps.utils'; import { isSwapsDefaultTokenSymbol } from '../../shared/modules/swaps.utils';
import { toChecksumHexAddress } from '../../shared/modules/hexstring-utils'; import { toChecksumHexAddress } from '../../shared/modules/hexstring-utils';
import { TOKEN_BUCKET_PRIORITY } from '../../shared/constants/swaps'; import { TOKEN_BUCKET_PRIORITY } from '../../shared/constants/swaps';
import { import { CHAIN_IDS, CURRENCY_SYMBOLS } from '../../shared/constants/network';
ETH_SYMBOL,
MATIC_SYMBOL,
BNB_SYMBOL,
AVALANCHE_SYMBOL,
MAINNET_CHAIN_ID,
BSC_CHAIN_ID,
POLYGON_CHAIN_ID,
AVALANCHE_CHAIN_ID,
GOERLI_CHAIN_ID,
} from '../../shared/constants/network';
import { useEqualityCheck } from './useEqualityCheck'; import { useEqualityCheck } from './useEqualityCheck';
export function getRenderableTokenData( export function getRenderableTokenData(
@ -68,14 +58,14 @@ export function getRenderableTokenData(
: ''; : '';
const chainIdForTokenIcons = const chainIdForTokenIcons =
chainId === GOERLI_CHAIN_ID ? MAINNET_CHAIN_ID : chainId; chainId === CHAIN_IDS.GOERLI ? CHAIN_IDS.MAINNET : chainId;
const tokenIconUrl = const tokenIconUrl =
(symbol === ETH_SYMBOL && chainId === MAINNET_CHAIN_ID) || (symbol === CURRENCY_SYMBOLS.ETH && chainId === CHAIN_IDS.MAINNET) ||
(symbol === ETH_SYMBOL && chainId === GOERLI_CHAIN_ID) || (symbol === CURRENCY_SYMBOLS.ETH && chainId === CHAIN_IDS.GOERLI) ||
(symbol === BNB_SYMBOL && chainId === BSC_CHAIN_ID) || (symbol === CURRENCY_SYMBOLS.BNB && chainId === CHAIN_IDS.BSC) ||
(symbol === MATIC_SYMBOL && chainId === POLYGON_CHAIN_ID) || (symbol === CURRENCY_SYMBOLS.MATIC && chainId === CHAIN_IDS.POLYGON) ||
(symbol === AVALANCHE_SYMBOL && chainId === AVALANCHE_CHAIN_ID) (symbol === CURRENCY_SYMBOLS.AVALANCHE && chainId === CHAIN_IDS.AVALANCHE)
? iconUrl ? iconUrl
: formatIconUrlWithProxy({ : formatIconUrlWithProxy({
chainId: chainIdForTokenIcons, chainId: chainIdForTokenIcons,

@ -14,7 +14,7 @@ import { getTokens, getNativeCurrency } from '../ducks/metamask/metamask';
import { getMessage } from '../helpers/utils/i18n-helper'; import { getMessage } from '../helpers/utils/i18n-helper';
import messages from '../../app/_locales/en/messages.json'; import messages from '../../app/_locales/en/messages.json';
import { ASSET_ROUTE, DEFAULT_ROUTE } from '../helpers/constants/routes'; import { ASSET_ROUTE, DEFAULT_ROUTE } from '../helpers/constants/routes';
import { MAINNET_CHAIN_ID } from '../../shared/constants/network'; import { CHAIN_IDS } from '../../shared/constants/network';
import { import {
TRANSACTION_TYPES, TRANSACTION_TYPES,
TRANSACTION_GROUP_CATEGORIES, TRANSACTION_GROUP_CATEGORIES,
@ -192,7 +192,7 @@ describe('useTransactionDisplayData', () => {
} else if (selector === getCurrentCurrency) { } else if (selector === getCurrentCurrency) {
return 'ETH'; return 'ETH';
} else if (selector === getCurrentChainId) { } else if (selector === getCurrentChainId) {
return MAINNET_CHAIN_ID; return CHAIN_IDS.MAINNET;
} }
return null; return null;
}); });

@ -31,10 +31,7 @@ import {
ERC20, ERC20,
ERC721, ERC721,
} from '../../../../shared/constants/transaction'; } from '../../../../shared/constants/transaction';
import { import { CHAIN_IDS, TEST_CHAINS } from '../../../../shared/constants/network';
MAINNET_CHAIN_ID,
TEST_CHAINS,
} from '../../../../shared/constants/network';
export default class ConfirmApproveContent extends Component { export default class ConfirmApproveContent extends Component {
static contextTypes = { static contextTypes = {
@ -466,7 +463,7 @@ export default class ConfirmApproveContent extends Component {
const { t } = this.context; const { t } = this.context;
const useBlockExplorer = const useBlockExplorer =
rpcPrefs?.blockExplorerUrl || rpcPrefs?.blockExplorerUrl ||
[...TEST_CHAINS, MAINNET_CHAIN_ID].includes(chainId); [...TEST_CHAINS, CHAIN_IDS.MAINNET].includes(chainId);
let titleTokenDescription = t('token'); let titleTokenDescription = t('token');
const tokenIdWrapped = tokenId ? ` (#${tokenId})` : ''; const tokenIdWrapped = tokenId ? ` (#${tokenId})` : '';

@ -5,7 +5,7 @@ import { useLocation } from 'react-router-dom';
import { SEND_STAGES, startNewDraftTransaction } from '../../ducks/send'; import { SEND_STAGES, startNewDraftTransaction } from '../../ducks/send';
import { ensInitialState } from '../../ducks/ens'; import { ensInitialState } from '../../ducks/ens';
import { renderWithProvider } from '../../../test/jest'; import { renderWithProvider } from '../../../test/jest';
import { RINKEBY_CHAIN_ID } from '../../../shared/constants/network'; import { CHAIN_IDS } from '../../../shared/constants/network';
import { GAS_ESTIMATE_TYPES } from '../../../shared/constants/gas'; import { GAS_ESTIMATE_TYPES } from '../../../shared/constants/gas';
import { INITIAL_SEND_STATE_FOR_EXISTING_DRAFT } from '../../../test/jest/mocks'; import { INITIAL_SEND_STATE_FOR_EXISTING_DRAFT } from '../../../test/jest/mocks';
import Send from './send'; import Send from './send';
@ -81,17 +81,17 @@ const baseStore = {
}, },
currentCurrency: 'USD', currentCurrency: 'USD',
provider: { provider: {
chainId: RINKEBY_CHAIN_ID, chainId: CHAIN_IDS.RINKEBY,
}, },
nativeCurrency: 'ETH', nativeCurrency: 'ETH',
featureFlags: { featureFlags: {
sendHexData: false, sendHexData: false,
}, },
addressBook: { addressBook: {
[RINKEBY_CHAIN_ID]: [], [CHAIN_IDS.RINKEBY]: [],
}, },
cachedBalances: { cachedBalances: {
[RINKEBY_CHAIN_ID]: {}, [CHAIN_IDS.RINKEBY]: {},
}, },
accounts: { accounts: {
'0x0': { balance: '0x0', address: '0x0' }, '0x0': { balance: '0x0', address: '0x0' },

@ -4,7 +4,10 @@ import { fireEvent, screen } from '@testing-library/react';
import nock from 'nock'; import nock from 'nock';
import { renderWithProvider } from '../../../../../test/jest/rendering'; import { renderWithProvider } from '../../../../../test/jest/rendering';
import { defaultNetworksData } from '../networks-tab.constants'; import { defaultNetworksData } from '../networks-tab.constants';
import { MAINNET, getRpcUrl } from '../../../../../shared/constants/network'; import {
NETWORK_TYPES,
getRpcUrl,
} from '../../../../../shared/constants/network';
import NetworksForm from '.'; import NetworksForm from '.';
const renderComponent = (props) => { const renderComponent = (props) => {
@ -169,7 +172,10 @@ describe('NetworkForm Component', () => {
await fireEvent.change(rpcUrlField, { await fireEvent.change(rpcUrlField, {
target: { target: {
value: getRpcUrl({ network: MAINNET, excludeProjectId: true }), value: getRpcUrl({
network: NETWORK_TYPES.MAINNET,
excludeProjectId: true,
}),
}, },
}); });

@ -4,8 +4,8 @@ import classnames from 'classnames';
import { useDispatch, useSelector } from 'react-redux'; import { useDispatch, useSelector } from 'react-redux';
import { useI18nContext } from '../../../../hooks/useI18nContext'; import { useI18nContext } from '../../../../hooks/useI18nContext';
import { import {
NETWORK_TYPE_RPC,
CHAIN_ID_TO_NETWORK_IMAGE_URL_MAP, CHAIN_ID_TO_NETWORK_IMAGE_URL_MAP,
NETWORK_TYPES,
} from '../../../../../shared/constants/network'; } from '../../../../../shared/constants/network';
import LockIcon from '../../../../components/ui/lock-icon'; import LockIcon from '../../../../components/ui/lock-icon';
import IconCheck from '../../../../components/ui/icon/icon-check'; import IconCheck from '../../../../components/ui/icon/icon-check';
@ -41,7 +41,8 @@ const NetworksListItem = ({
const listItemNetworkIsSelected = selectedRpcUrl && selectedRpcUrl === rpcUrl; const listItemNetworkIsSelected = selectedRpcUrl && selectedRpcUrl === rpcUrl;
const listItemUrlIsProviderUrl = rpcUrl === provider.rpcUrl; const listItemUrlIsProviderUrl = rpcUrl === provider.rpcUrl;
const listItemTypeIsProviderNonRpcType = const listItemTypeIsProviderNonRpcType =
provider.type !== NETWORK_TYPE_RPC && currentProviderType === provider.type; provider.type !== NETWORK_TYPES.RPC &&
currentProviderType === provider.type;
const listItemNetworkIsCurrentProvider = const listItemNetworkIsCurrentProvider =
!networkIsSelected && !networkIsSelected &&
(listItemUrlIsProviderUrl || listItemTypeIsProviderNonRpcType); (listItemUrlIsProviderUrl || listItemTypeIsProviderNonRpcType);
@ -115,12 +116,12 @@ const NetworksListItem = ({
'networks-tab__networks-list-name--selected': 'networks-tab__networks-list-name--selected':
displayNetworkListItemAsSelected, displayNetworkListItemAsSelected,
'networks-tab__networks-list-name--disabled': 'networks-tab__networks-list-name--disabled':
currentProviderType !== NETWORK_TYPE_RPC && currentProviderType !== NETWORK_TYPES.RPC &&
!displayNetworkListItemAsSelected, !displayNetworkListItemAsSelected,
})} })}
> >
{label || t(labelKey)} {label || t(labelKey)}
{currentProviderType !== NETWORK_TYPE_RPC && ( {currentProviderType !== NETWORK_TYPES.RPC && (
<LockIcon width="14px" height="17px" fill="var(--color-icon-muted)" /> <LockIcon width="14px" height="17px" fill="var(--color-icon-muted)" />
)} )}
</div> </div>

@ -1,63 +1,70 @@
import { import {
GOERLI,
GOERLI_CHAIN_ID,
KOVAN,
KOVAN_CHAIN_ID,
MAINNET,
MAINNET_CHAIN_ID,
RINKEBY,
RINKEBY_CHAIN_ID,
ROPSTEN,
ROPSTEN_CHAIN_ID,
getRpcUrl, getRpcUrl,
ETH_SYMBOL,
TEST_NETWORK_TICKER_MAP, TEST_NETWORK_TICKER_MAP,
CURRENCY_SYMBOLS,
CHAIN_IDS,
NETWORK_TYPES,
} from '../../../../shared/constants/network'; } from '../../../../shared/constants/network';
const defaultNetworksData = [ const defaultNetworksData = [
{ {
labelKey: MAINNET, labelKey: NETWORK_TYPES.MAINNET,
iconColor: '#29B6AF', iconColor: '#29B6AF',
providerType: MAINNET, providerType: NETWORK_TYPES.MAINNET,
rpcUrl: getRpcUrl({ network: MAINNET, excludeProjectId: true }), rpcUrl: getRpcUrl({
chainId: MAINNET_CHAIN_ID, network: NETWORK_TYPES.MAINNET,
ticker: ETH_SYMBOL, excludeProjectId: true,
}),
chainId: CHAIN_IDS.MAINNET,
ticker: CURRENCY_SYMBOLS.ETH,
blockExplorerUrl: 'https://etherscan.io', blockExplorerUrl: 'https://etherscan.io',
}, },
{ {
labelKey: ROPSTEN, labelKey: NETWORK_TYPES.ROPSTEN,
iconColor: '#FF4A8D', iconColor: '#FF4A8D',
providerType: ROPSTEN, providerType: NETWORK_TYPES.ROPSTEN,
rpcUrl: getRpcUrl({ network: ROPSTEN, excludeProjectId: true }), rpcUrl: getRpcUrl({
chainId: ROPSTEN_CHAIN_ID, network: NETWORK_TYPES.ROPSTEN,
ticker: TEST_NETWORK_TICKER_MAP[ROPSTEN], excludeProjectId: true,
}),
chainId: CHAIN_IDS.ROPSTEN,
ticker: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.ROPSTEN],
blockExplorerUrl: 'https://ropsten.etherscan.io', blockExplorerUrl: 'https://ropsten.etherscan.io',
}, },
{ {
labelKey: RINKEBY, labelKey: NETWORK_TYPES.RINKEBY,
iconColor: '#F6C343', iconColor: '#F6C343',
providerType: RINKEBY, providerType: NETWORK_TYPES.RINKEBY,
rpcUrl: getRpcUrl({ network: RINKEBY, excludeProjectId: true }), rpcUrl: getRpcUrl({
chainId: RINKEBY_CHAIN_ID, network: NETWORK_TYPES.RINKEBY,
ticker: TEST_NETWORK_TICKER_MAP[RINKEBY], excludeProjectId: true,
}),
chainId: CHAIN_IDS.RINKEBY,
ticker: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.RINKEBY],
blockExplorerUrl: 'https://rinkeby.etherscan.io', blockExplorerUrl: 'https://rinkeby.etherscan.io',
}, },
{ {
labelKey: GOERLI, labelKey: NETWORK_TYPES.GOERLI,
iconColor: '#3099f2', iconColor: '#3099f2',
providerType: GOERLI, providerType: NETWORK_TYPES.GOERLI,
rpcUrl: getRpcUrl({ network: GOERLI, excludeProjectId: true }), rpcUrl: getRpcUrl({
chainId: GOERLI_CHAIN_ID, network: NETWORK_TYPES.GOERLI,
ticker: TEST_NETWORK_TICKER_MAP[GOERLI], excludeProjectId: true,
}),
chainId: CHAIN_IDS.GOERLI,
ticker: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.GOERLI],
blockExplorerUrl: 'https://goerli.etherscan.io', blockExplorerUrl: 'https://goerli.etherscan.io',
}, },
{ {
labelKey: KOVAN, labelKey: NETWORK_TYPES.KOVAN,
iconColor: '#9064FF', iconColor: '#9064FF',
providerType: KOVAN, providerType: NETWORK_TYPES.KOVAN,
rpcUrl: getRpcUrl({ network: KOVAN, excludeProjectId: true }), rpcUrl: getRpcUrl({
chainId: KOVAN_CHAIN_ID, network: NETWORK_TYPES.KOVAN,
ticker: TEST_NETWORK_TICKER_MAP[KOVAN], excludeProjectId: true,
}),
chainId: CHAIN_IDS.KOVAN,
ticker: TEST_NETWORK_TICKER_MAP[NETWORK_TYPES.KOVAN],
blockExplorerUrl: 'https://kovan.etherscan.io', blockExplorerUrl: 'https://kovan.etherscan.io',
}, },
]; ];

@ -20,7 +20,7 @@ import {
getProvider, getProvider,
} from '../../../selectors'; } from '../../../selectors';
import { import {
NETWORK_TYPE_RPC, NETWORK_TYPES,
TEST_CHAINS, TEST_CHAINS,
} from '../../../../shared/constants/network'; } from '../../../../shared/constants/network';
import { defaultNetworksData } from './networks-tab.constants'; import { defaultNetworksData } from './networks-tab.constants';
@ -58,7 +58,7 @@ const NetworksTab = ({ addNewNetwork }) => {
return { return {
label: rpc.nickname, label: rpc.nickname,
iconColor: 'var(--color-icon-alternative)', iconColor: 'var(--color-icon-alternative)',
providerType: NETWORK_TYPE_RPC, providerType: NETWORK_TYPES.RPC,
rpcUrl: rpc.rpcUrl, rpcUrl: rpc.rpcUrl,
chainId: rpc.chainId, chainId: rpc.chainId,
ticker: rpc.ticker, ticker: rpc.ticker,
@ -83,7 +83,7 @@ const NetworksTab = ({ addNewNetwork }) => {
networksToRender.find((network) => { networksToRender.find((network) => {
return ( return (
network.rpcUrl === provider.rpcUrl || network.rpcUrl === provider.rpcUrl ||
(network.providerType !== NETWORK_TYPE_RPC && (network.providerType !== NETWORK_TYPES.RPC &&
network.providerType === provider.type) network.providerType === provider.type)
); );
}) || {}; }) || {};

@ -2,14 +2,7 @@ import React, { useContext } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { I18nContext } from '../../../contexts/i18n'; import { I18nContext } from '../../../contexts/i18n';
import InfoTooltip from '../../../components/ui/info-tooltip'; import InfoTooltip from '../../../components/ui/info-tooltip';
import { import { CHAIN_IDS } from '../../../../shared/constants/network';
MAINNET_CHAIN_ID,
BSC_CHAIN_ID,
LOCALHOST_CHAIN_ID,
POLYGON_CHAIN_ID,
GOERLI_CHAIN_ID,
AVALANCHE_CHAIN_ID,
} from '../../../../shared/constants/network';
import TransactionDetail from '../../../components/app/transaction-detail/transaction-detail.component'; import TransactionDetail from '../../../components/app/transaction-detail/transaction-detail.component';
import TransactionDetailItem from '../../../components/app/transaction-detail-item/transaction-detail-item.component'; import TransactionDetailItem from '../../../components/app/transaction-detail-item/transaction-detail-item.component';
import Typography from '../../../components/ui/typography'; import Typography from '../../../components/ui/typography';
@ -40,17 +33,17 @@ export default function FeeCard({
const getTranslatedNetworkName = () => { const getTranslatedNetworkName = () => {
switch (chainId) { switch (chainId) {
case MAINNET_CHAIN_ID: case CHAIN_IDS.MAINNET:
return t('networkNameEthereum'); return t('networkNameEthereum');
case BSC_CHAIN_ID: case CHAIN_IDS.BSC:
return t('networkNameBSC'); return t('networkNameBSC');
case POLYGON_CHAIN_ID: case CHAIN_IDS.POLYGON:
return t('networkNamePolygon'); return t('networkNamePolygon');
case LOCALHOST_CHAIN_ID: case CHAIN_IDS.LOCALHOST:
return t('networkNameTestnet'); return t('networkNameTestnet');
case GOERLI_CHAIN_ID: case CHAIN_IDS.GOERLI:
return t('networkNameGoerli'); return t('networkNameGoerli');
case AVALANCHE_CHAIN_ID: case CHAIN_IDS.AVALANCHE:
return t('networkNameAvalanche'); return t('networkNameAvalanche');
default: default:
throw new Error('This network is not supported for token swaps'); throw new Error('This network is not supported for token swaps');

@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import { MAINNET_CHAIN_ID } from '../../../../shared/constants/network'; import { CHAIN_IDS } from '../../../../shared/constants/network';
import FeeCard from './fee-card'; import FeeCard from './fee-card';
const containerStyle = { const containerStyle = {
@ -95,7 +95,7 @@ export default {
tokenApprovalSourceTokenSymbol: 'ABC', tokenApprovalSourceTokenSymbol: 'ABC',
metaMaskFee: '0.875', metaMaskFee: '0.875',
numberOfQuotes: 6, numberOfQuotes: 6,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
isBestQuote: true, isBestQuote: true,
}, },
}; };

@ -9,7 +9,7 @@ import {
setBackgroundConnection, setBackgroundConnection,
MOCKS, MOCKS,
} from '../../../../test/jest'; } from '../../../../test/jest';
import { MAINNET_CHAIN_ID } from '../../../../shared/constants/network'; import { CHAIN_IDS } from '../../../../shared/constants/network';
import { checkNetworkAndAccountSupports1559 } from '../../../selectors'; import { checkNetworkAndAccountSupports1559 } from '../../../selectors';
import { import {
@ -82,7 +82,7 @@ const createProps = (customProps = {}) => {
numberOfQuotes: 6, numberOfQuotes: 6,
onQuotesClick: jest.fn(), onQuotesClick: jest.fn(),
tokenConversionRate: 0.015, tokenConversionRate: 0.015,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
networkAndAccountSupports1559: false, networkAndAccountSupports1559: false,
supportsEIP1559V2: false, supportsEIP1559V2: false,
...customProps, ...customProps,

@ -21,15 +21,7 @@ import {
isSwapsDefaultTokenAddress, isSwapsDefaultTokenAddress,
isSwapsDefaultTokenSymbol, isSwapsDefaultTokenSymbol,
} from '../../../shared/modules/swaps.utils'; } from '../../../shared/modules/swaps.utils';
import { import { CHAIN_IDS, CURRENCY_SYMBOLS } from '../../../shared/constants/network';
MAINNET_CHAIN_ID,
BSC_CHAIN_ID,
POLYGON_CHAIN_ID,
LOCALHOST_CHAIN_ID,
GOERLI_CHAIN_ID,
ETH_SYMBOL,
AVALANCHE_CHAIN_ID,
} from '../../../shared/constants/network';
import { SECOND } from '../../../shared/constants/time'; import { SECOND } from '../../../shared/constants/time';
import { import {
calcTokenValue, calcTokenValue,
@ -82,11 +74,11 @@ const getBaseUrlForNewSwapsApi = (type, chainId) => {
return `${v2ApiBaseUrl}/networks/${chainIdDecimal}`; return `${v2ApiBaseUrl}/networks/${chainIdDecimal}`;
}; };
const TEST_CHAIN_IDS = [GOERLI_CHAIN_ID, LOCALHOST_CHAIN_ID]; const TEST_CHAIN_IDS = [CHAIN_IDS.GOERLI, CHAIN_IDS.LOCALHOST];
export const getBaseApi = function (type, chainId = MAINNET_CHAIN_ID) { export const getBaseApi = function (type, chainId = CHAIN_IDS.MAINNET) {
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
chainId = TEST_CHAIN_IDS.includes(chainId) ? MAINNET_CHAIN_ID : chainId; chainId = TEST_CHAIN_IDS.includes(chainId) ? CHAIN_IDS.MAINNET : chainId;
const baseUrl = getBaseUrlForNewSwapsApi(type, chainId); const baseUrl = getBaseUrlForNewSwapsApi(type, chainId);
const chainIdDecimal = chainId && parseInt(chainId, 16); const chainIdDecimal = chainId && parseInt(chainId, 16);
if (!baseUrl) { if (!baseUrl) {
@ -509,7 +501,7 @@ export const getFeeForSmartTransaction = ({
const feeInWeiHex = decimalToHex(feeInWeiDec); const feeInWeiHex = decimalToHex(feeInWeiDec);
const ethFee = getValueFromWeiHex({ const ethFee = getValueFromWeiHex({
value: feeInWeiHex, value: feeInWeiHex,
toDenomination: ETH_SYMBOL, toDenomination: CURRENCY_SYMBOLS.ETH,
numberOfDecimals: 5, numberOfDecimals: 5,
}); });
const rawNetworkFees = getValueFromWeiHex({ const rawNetworkFees = getValueFromWeiHex({
@ -849,7 +841,7 @@ export function formatSwapsValueForDisplay(destinationAmount) {
*/ */
export const isContractAddressValid = ( export const isContractAddressValid = (
contractAddress, contractAddress,
chainId = MAINNET_CHAIN_ID, chainId = CHAIN_IDS.MAINNET,
) => { ) => {
if (!contractAddress || !ALLOWED_CONTRACT_ADDRESSES[chainId]) { if (!contractAddress || !ALLOWED_CONTRACT_ADDRESSES[chainId]) {
return false; return false;
@ -868,15 +860,15 @@ export const isContractAddressValid = (
*/ */
export const getNetworkNameByChainId = (chainId) => { export const getNetworkNameByChainId = (chainId) => {
switch (chainId) { switch (chainId) {
case MAINNET_CHAIN_ID: case CHAIN_IDS.MAINNET:
return ETHEREUM; return ETHEREUM;
case BSC_CHAIN_ID: case CHAIN_IDS.BSC:
return BSC; return BSC;
case POLYGON_CHAIN_ID: case CHAIN_IDS.POLYGON:
return POLYGON; return POLYGON;
case GOERLI_CHAIN_ID: case CHAIN_IDS.GOERLI:
return GOERLI; return GOERLI;
case AVALANCHE_CHAIN_ID: case CHAIN_IDS.AVALANCHE:
return AVALANCHE; return AVALANCHE;
default: default:
return ''; return '';
@ -892,8 +884,8 @@ export const getNetworkNameByChainId = (chainId) => {
*/ */
export const getSwapsLivenessForNetwork = (swapsFeatureFlags = {}, chainId) => { export const getSwapsLivenessForNetwork = (swapsFeatureFlags = {}, chainId) => {
const networkName = getNetworkNameByChainId(chainId); const networkName = getNetworkNameByChainId(chainId);
// Use old APIs for testnet and Goerli. // Use old APIs for testnet and Rinkeby.
if ([LOCALHOST_CHAIN_ID, GOERLI_CHAIN_ID].includes(chainId)) { if ([CHAIN_IDS.LOCALHOST, CHAIN_IDS.GOERLI].includes(chainId)) {
return { return {
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
}; };

@ -1,15 +1,6 @@
import nock from 'nock'; import nock from 'nock';
import { MOCKS } from '../../../test/jest'; import { MOCKS } from '../../../test/jest';
import { import { CHAIN_IDS, CURRENCY_SYMBOLS } from '../../../shared/constants/network';
MAINNET_CHAIN_ID,
BSC_CHAIN_ID,
POLYGON_CHAIN_ID,
LOCALHOST_CHAIN_ID,
GOERLI_CHAIN_ID,
KOVAN_CHAIN_ID,
AVALANCHE_CHAIN_ID,
ETH_SYMBOL,
} from '../../../shared/constants/network';
import { import {
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP, SWAPS_CHAINID_CONTRACT_ADDRESS_MAP,
SWAPS_CHAINID_DEFAULT_TOKEN_MAP, SWAPS_CHAINID_DEFAULT_TOKEN_MAP,
@ -112,7 +103,7 @@ describe('Swaps Util', () => {
sourceTokenInfo: { ...TOKENS[0] }, sourceTokenInfo: { ...TOKENS[0] },
destinationTokenInfo: { ...TOKENS[1] }, destinationTokenInfo: { ...TOKENS[1] },
}, },
{ chainId: MAINNET_CHAIN_ID }, { chainId: CHAIN_IDS.MAINNET },
); );
expect(result).toStrictEqual(expectedResult2); expect(result).toStrictEqual(expectedResult2);
}); });
@ -127,12 +118,12 @@ describe('Swaps Util', () => {
}); });
it('should fetch tokens', async () => { it('should fetch tokens', async () => {
const result = await fetchTokens(MAINNET_CHAIN_ID); const result = await fetchTokens(CHAIN_IDS.MAINNET);
expect(result).toStrictEqual(EXPECTED_TOKENS_RESULT); expect(result).toStrictEqual(EXPECTED_TOKENS_RESULT);
}); });
it('should fetch tokens on prod', async () => { it('should fetch tokens on prod', async () => {
const result = await fetchTokens(MAINNET_CHAIN_ID); const result = await fetchTokens(CHAIN_IDS.MAINNET);
expect(result).toStrictEqual(EXPECTED_TOKENS_RESULT); expect(result).toStrictEqual(EXPECTED_TOKENS_RESULT);
}); });
}); });
@ -146,12 +137,12 @@ describe('Swaps Util', () => {
}); });
it('should fetch aggregator metadata', async () => { it('should fetch aggregator metadata', async () => {
const result = await fetchAggregatorMetadata(MAINNET_CHAIN_ID); const result = await fetchAggregatorMetadata(CHAIN_IDS.MAINNET);
expect(result).toStrictEqual(AGGREGATOR_METADATA); expect(result).toStrictEqual(AGGREGATOR_METADATA);
}); });
it('should fetch aggregator metadata on prod', async () => { it('should fetch aggregator metadata on prod', async () => {
const result = await fetchAggregatorMetadata(MAINNET_CHAIN_ID); const result = await fetchAggregatorMetadata(CHAIN_IDS.MAINNET);
expect(result).toStrictEqual(AGGREGATOR_METADATA); expect(result).toStrictEqual(AGGREGATOR_METADATA);
}); });
}); });
@ -182,12 +173,12 @@ describe('Swaps Util', () => {
}, },
}; };
it('should fetch top assets', async () => { it('should fetch top assets', async () => {
const result = await fetchTopAssets(MAINNET_CHAIN_ID); const result = await fetchTopAssets(CHAIN_IDS.MAINNET);
expect(result).toStrictEqual(expectedResult); expect(result).toStrictEqual(expectedResult);
}); });
it('should fetch top assets on prod', async () => { it('should fetch top assets on prod', async () => {
const result = await fetchTopAssets(MAINNET_CHAIN_ID); const result = await fetchTopAssets(CHAIN_IDS.MAINNET);
expect(result).toStrictEqual(expectedResult); expect(result).toStrictEqual(expectedResult);
}); });
}); });
@ -208,28 +199,28 @@ describe('Swaps Util', () => {
it('returns true if "to" is WETH contract address', () => { it('returns true if "to" is WETH contract address', () => {
expect( expect(
isContractAddressValid(usedTradeTxParams.to, MAINNET_CHAIN_ID), isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.MAINNET),
).toBe(true); ).toBe(true);
}); });
it('returns true if "to" is WETH contract address with some uppercase chars', () => { it('returns true if "to" is WETH contract address with some uppercase chars', () => {
usedTradeTxParams.to = '0xc02AAA39B223fe8d0a0e5c4f27ead9083c756cc2'; usedTradeTxParams.to = '0xc02AAA39B223fe8d0a0e5c4f27ead9083c756cc2';
expect( expect(
isContractAddressValid(usedTradeTxParams.to, MAINNET_CHAIN_ID), isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.MAINNET),
).toBe(true); ).toBe(true);
}); });
it('returns true if "to" is ETH mainnet contract address on ETH mainnet', () => { it('returns true if "to" is ETH mainnet contract address on ETH mainnet', () => {
usedTradeTxParams.to = usedTradeTxParams.to =
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[MAINNET_CHAIN_ID]; SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.MAINNET];
expect( expect(
isContractAddressValid(usedTradeTxParams.to, MAINNET_CHAIN_ID), isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.MAINNET),
).toBe(true); ).toBe(true);
}); });
it('returns true if "to" is WBNB contract address on BSC mainnet', () => { it('returns true if "to" is WBNB contract address on BSC mainnet', () => {
usedTradeTxParams.to = WBNB_CONTRACT_ADDRESS; usedTradeTxParams.to = WBNB_CONTRACT_ADDRESS;
expect(isContractAddressValid(usedTradeTxParams.to, BSC_CHAIN_ID)).toBe( expect(isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.BSC)).toBe(
true, true,
); );
}); });
@ -237,19 +228,19 @@ describe('Swaps Util', () => {
it('returns true if "to" is WMATIC contract address on Polygon mainnet', () => { it('returns true if "to" is WMATIC contract address on Polygon mainnet', () => {
usedTradeTxParams.to = WMATIC_CONTRACT_ADDRESS; usedTradeTxParams.to = WMATIC_CONTRACT_ADDRESS;
expect( expect(
isContractAddressValid(usedTradeTxParams.to, POLYGON_CHAIN_ID), isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.POLYGON),
).toBe(true); ).toBe(true);
}); });
it('returns false if "to" is BSC contract address on ETH mainnet', () => { it('returns false if "to" is BSC contract address on ETH mainnet', () => {
usedTradeTxParams.to = SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[BSC_CHAIN_ID]; usedTradeTxParams.to = SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.BSC];
expect( expect(
isContractAddressValid(usedTradeTxParams.to, MAINNET_CHAIN_ID), isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.MAINNET),
).toBe(false); ).toBe(false);
}); });
it('returns false if contractAddress is null', () => { it('returns false if contractAddress is null', () => {
expect(isContractAddressValid(null, LOCALHOST_CHAIN_ID)).toBe(false); expect(isContractAddressValid(null, CHAIN_IDS.LOCALHOST)).toBe(false);
}); });
it('returns false if chainId is incorrect', () => { it('returns false if chainId is incorrect', () => {
@ -259,74 +250,74 @@ describe('Swaps Util', () => {
}); });
it('returns true if "to" is BSC contract address on BSC network', () => { it('returns true if "to" is BSC contract address on BSC network', () => {
usedTradeTxParams.to = SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[BSC_CHAIN_ID]; usedTradeTxParams.to = SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.BSC];
expect(isContractAddressValid(usedTradeTxParams.to, BSC_CHAIN_ID)).toBe( expect(isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.BSC)).toBe(
true, true,
); );
}); });
it('returns true if "to" is Polygon contract address on Polygon network', () => { it('returns true if "to" is Polygon contract address on Polygon network', () => {
usedTradeTxParams.to = usedTradeTxParams.to =
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[POLYGON_CHAIN_ID]; SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.POLYGON];
expect( expect(
isContractAddressValid(usedTradeTxParams.to, POLYGON_CHAIN_ID), isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.POLYGON),
).toBe(true); ).toBe(true);
}); });
it('returns true if "to" is Goerli contract address on Goerli network', () => { it('returns true if "to" is Goerli contract address on Goerli network', () => {
usedTradeTxParams.to = usedTradeTxParams.to =
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[GOERLI_CHAIN_ID]; SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.GOERLI];
expect( expect(
isContractAddressValid(usedTradeTxParams.to, GOERLI_CHAIN_ID), isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.GOERLI),
).toBe(true); ).toBe(true);
}); });
it('returns true if "to" is testnet contract address', () => { it('returns true if "to" is testnet contract address', () => {
usedTradeTxParams.to = usedTradeTxParams.to =
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[LOCALHOST_CHAIN_ID]; SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.LOCALHOST];
expect( expect(
isContractAddressValid(usedTradeTxParams.to, LOCALHOST_CHAIN_ID), isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.LOCALHOST),
).toBe(true); ).toBe(true);
}); });
it('returns true if "to" is testnet contract address with some uppercase chars', () => { it('returns true if "to" is testnet contract address with some uppercase chars', () => {
usedTradeTxParams.to = '0x881D40237659C251811CEC9c364ef91dC08D300C'; usedTradeTxParams.to = '0x881D40237659C251811CEC9c364ef91dC08D300C';
expect( expect(
isContractAddressValid(usedTradeTxParams.to, LOCALHOST_CHAIN_ID), isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.LOCALHOST),
).toBe(true); ).toBe(true);
}); });
it('returns false if "to" has mismatch with current chainId', () => { it('returns false if "to" has mismatch with current chainId', () => {
usedTradeTxParams.to = SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[BSC_CHAIN_ID]; usedTradeTxParams.to = SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[CHAIN_IDS.BSC];
expect( expect(
isContractAddressValid(usedTradeTxParams.to, LOCALHOST_CHAIN_ID), isContractAddressValid(usedTradeTxParams.to, CHAIN_IDS.LOCALHOST),
).toBe(false); ).toBe(false);
}); });
}); });
describe('getNetworkNameByChainId', () => { describe('getNetworkNameByChainId', () => {
it('returns "ethereum" for mainnet chain ID', () => { it('returns "ethereum" for mainnet chain ID', () => {
expect(getNetworkNameByChainId(MAINNET_CHAIN_ID)).toBe(ETHEREUM); expect(getNetworkNameByChainId(CHAIN_IDS.MAINNET)).toBe(ETHEREUM);
}); });
it('returns "bsc" for mainnet chain ID', () => { it('returns "bsc" for mainnet chain ID', () => {
expect(getNetworkNameByChainId(BSC_CHAIN_ID)).toBe(BSC); expect(getNetworkNameByChainId(CHAIN_IDS.BSC)).toBe(BSC);
}); });
it('returns "polygon" for mainnet chain ID', () => { it('returns "polygon" for mainnet chain ID', () => {
expect(getNetworkNameByChainId(POLYGON_CHAIN_ID)).toBe(POLYGON); expect(getNetworkNameByChainId(CHAIN_IDS.POLYGON)).toBe(POLYGON);
}); });
it('returns "goerli" for Goerli chain ID', () => { it('returns "goerli" for Goerli chain ID', () => {
expect(getNetworkNameByChainId(GOERLI_CHAIN_ID)).toBe(GOERLI); expect(getNetworkNameByChainId(CHAIN_IDS.GOERLI)).toBe(GOERLI);
}); });
it('returns "avalanche" for Avalanche chain ID', () => { it('returns "avalanche" for Avalanche chain ID', () => {
expect(getNetworkNameByChainId(AVALANCHE_CHAIN_ID)).toBe(AVALANCHE); expect(getNetworkNameByChainId(CHAIN_IDS.AVALANCHE)).toBe(AVALANCHE);
}); });
it('returns an empty string for an unsupported network', () => { it('returns an empty string for an unsupported network', () => {
expect(getNetworkNameByChainId(KOVAN_CHAIN_ID)).toBe(''); expect(getNetworkNameByChainId(CHAIN_IDS.KOVAN)).toBe('');
}); });
}); });
@ -338,7 +329,7 @@ describe('Swaps Util', () => {
expect( expect(
getSwapsLivenessForNetwork( getSwapsLivenessForNetwork(
MOCKS.createFeatureFlagsResponse(), MOCKS.createFeatureFlagsResponse(),
LOCALHOST_CHAIN_ID, CHAIN_IDS.LOCALHOST,
), ),
).toMatchObject(expectedSwapsLiveness); ).toMatchObject(expectedSwapsLiveness);
}); });
@ -350,7 +341,7 @@ describe('Swaps Util', () => {
expect( expect(
getSwapsLivenessForNetwork( getSwapsLivenessForNetwork(
MOCKS.createFeatureFlagsResponse(), MOCKS.createFeatureFlagsResponse(),
GOERLI_CHAIN_ID, CHAIN_IDS.GOERLI,
), ),
).toMatchObject(expectedSwapsLiveness); ).toMatchObject(expectedSwapsLiveness);
}); });
@ -362,7 +353,7 @@ describe('Swaps Util', () => {
expect( expect(
getSwapsLivenessForNetwork( getSwapsLivenessForNetwork(
MOCKS.createFeatureFlagsResponse(), MOCKS.createFeatureFlagsResponse(),
KOVAN_CHAIN_ID, CHAIN_IDS.KOVAN,
), ),
).toMatchObject(expectedSwapsLiveness); ).toMatchObject(expectedSwapsLiveness);
}); });
@ -374,7 +365,7 @@ describe('Swaps Util', () => {
expect( expect(
getSwapsLivenessForNetwork( getSwapsLivenessForNetwork(
MOCKS.createFeatureFlagsResponse(), MOCKS.createFeatureFlagsResponse(),
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
), ),
).toMatchObject(expectedSwapsLiveness); ).toMatchObject(expectedSwapsLiveness);
}); });
@ -386,7 +377,7 @@ describe('Swaps Util', () => {
const swapsFeatureFlags = MOCKS.createFeatureFlagsResponse(); const swapsFeatureFlags = MOCKS.createFeatureFlagsResponse();
swapsFeatureFlags[ETHEREUM].extension_active = false; swapsFeatureFlags[ETHEREUM].extension_active = false;
expect( expect(
getSwapsLivenessForNetwork(swapsFeatureFlags, MAINNET_CHAIN_ID), getSwapsLivenessForNetwork(swapsFeatureFlags, CHAIN_IDS.MAINNET),
).toMatchObject(expectedSwapsLiveness); ).toMatchObject(expectedSwapsLiveness);
}); });
}); });
@ -419,8 +410,8 @@ describe('Swaps Util', () => {
it('returns true if swapping from ETH to WETH', () => { it('returns true if swapping from ETH to WETH', () => {
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
SWAPS_CHAINID_DEFAULT_TOKEN_MAP[MAINNET_CHAIN_ID]?.address, SWAPS_CHAINID_DEFAULT_TOKEN_MAP[CHAIN_IDS.MAINNET]?.address,
WETH_CONTRACT_ADDRESS, WETH_CONTRACT_ADDRESS,
), ),
).toBe(true); ).toBe(true);
@ -431,7 +422,7 @@ describe('Swaps Util', () => {
'0X0000000000000000000000000000000000000000'; '0X0000000000000000000000000000000000000000';
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
ethAddressWithUpperCaseChars, ethAddressWithUpperCaseChars,
WETH_CONTRACT_ADDRESS, WETH_CONTRACT_ADDRESS,
), ),
@ -441,9 +432,9 @@ describe('Swaps Util', () => {
it('returns true if swapping from WETH to ETH', () => { it('returns true if swapping from WETH to ETH', () => {
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
WETH_CONTRACT_ADDRESS, WETH_CONTRACT_ADDRESS,
SWAPS_CHAINID_DEFAULT_TOKEN_MAP[MAINNET_CHAIN_ID]?.address, SWAPS_CHAINID_DEFAULT_TOKEN_MAP[CHAIN_IDS.MAINNET]?.address,
), ),
).toBe(true); ).toBe(true);
}); });
@ -453,9 +444,9 @@ describe('Swaps Util', () => {
'0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'; '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
wethContractAddressWithUpperCaseChars, wethContractAddressWithUpperCaseChars,
SWAPS_CHAINID_DEFAULT_TOKEN_MAP[MAINNET_CHAIN_ID]?.address, SWAPS_CHAINID_DEFAULT_TOKEN_MAP[CHAIN_IDS.MAINNET]?.address,
), ),
).toBe(true); ).toBe(true);
}); });
@ -463,8 +454,8 @@ describe('Swaps Util', () => {
it('returns false if swapping from ETH to a non-WETH token', () => { it('returns false if swapping from ETH to a non-WETH token', () => {
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
SWAPS_CHAINID_DEFAULT_TOKEN_MAP[MAINNET_CHAIN_ID]?.address, SWAPS_CHAINID_DEFAULT_TOKEN_MAP[CHAIN_IDS.MAINNET]?.address,
randomTokenAddress, randomTokenAddress,
), ),
).toBe(false); ).toBe(false);
@ -473,8 +464,8 @@ describe('Swaps Util', () => {
it('returns true if swapping from BNB to WBNB', () => { it('returns true if swapping from BNB to WBNB', () => {
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
BSC_CHAIN_ID, CHAIN_IDS.BSC,
SWAPS_CHAINID_DEFAULT_TOKEN_MAP[BSC_CHAIN_ID]?.address, SWAPS_CHAINID_DEFAULT_TOKEN_MAP[CHAIN_IDS.BSC]?.address,
WBNB_CONTRACT_ADDRESS, WBNB_CONTRACT_ADDRESS,
), ),
).toBe(true); ).toBe(true);
@ -483,9 +474,9 @@ describe('Swaps Util', () => {
it('returns true if swapping from WBNB to BNB', () => { it('returns true if swapping from WBNB to BNB', () => {
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
BSC_CHAIN_ID, CHAIN_IDS.BSC,
WBNB_CONTRACT_ADDRESS, WBNB_CONTRACT_ADDRESS,
SWAPS_CHAINID_DEFAULT_TOKEN_MAP[BSC_CHAIN_ID]?.address, SWAPS_CHAINID_DEFAULT_TOKEN_MAP[CHAIN_IDS.BSC]?.address,
), ),
).toBe(true); ).toBe(true);
}); });
@ -493,8 +484,8 @@ describe('Swaps Util', () => {
it('returns false if swapping from BNB to a non-WBNB token', () => { it('returns false if swapping from BNB to a non-WBNB token', () => {
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
BSC_CHAIN_ID, CHAIN_IDS.BSC,
SWAPS_CHAINID_DEFAULT_TOKEN_MAP[BSC_CHAIN_ID]?.address, SWAPS_CHAINID_DEFAULT_TOKEN_MAP[CHAIN_IDS.BSC]?.address,
randomTokenAddress, randomTokenAddress,
), ),
).toBe(false); ).toBe(false);
@ -503,8 +494,8 @@ describe('Swaps Util', () => {
it('returns true if swapping from MATIC to WMATIC', () => { it('returns true if swapping from MATIC to WMATIC', () => {
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
POLYGON_CHAIN_ID, CHAIN_IDS.POLYGON,
SWAPS_CHAINID_DEFAULT_TOKEN_MAP[POLYGON_CHAIN_ID]?.address, SWAPS_CHAINID_DEFAULT_TOKEN_MAP[CHAIN_IDS.POLYGON]?.address,
WMATIC_CONTRACT_ADDRESS, WMATIC_CONTRACT_ADDRESS,
), ),
).toBe(true); ).toBe(true);
@ -513,9 +504,9 @@ describe('Swaps Util', () => {
it('returns true if swapping from WMATIC to MATIC', () => { it('returns true if swapping from WMATIC to MATIC', () => {
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
POLYGON_CHAIN_ID, CHAIN_IDS.POLYGON,
WMATIC_CONTRACT_ADDRESS, WMATIC_CONTRACT_ADDRESS,
SWAPS_CHAINID_DEFAULT_TOKEN_MAP[POLYGON_CHAIN_ID]?.address, SWAPS_CHAINID_DEFAULT_TOKEN_MAP[CHAIN_IDS.POLYGON]?.address,
), ),
).toBe(true); ).toBe(true);
}); });
@ -523,8 +514,8 @@ describe('Swaps Util', () => {
it('returns false if swapping from MATIC to a non-WMATIC token', () => { it('returns false if swapping from MATIC to a non-WMATIC token', () => {
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
POLYGON_CHAIN_ID, CHAIN_IDS.POLYGON,
SWAPS_CHAINID_DEFAULT_TOKEN_MAP[POLYGON_CHAIN_ID]?.address, SWAPS_CHAINID_DEFAULT_TOKEN_MAP[CHAIN_IDS.POLYGON]?.address,
randomTokenAddress, randomTokenAddress,
), ),
).toBe(false); ).toBe(false);
@ -533,7 +524,7 @@ describe('Swaps Util', () => {
it('returns false if a source token is undefined', () => { it('returns false if a source token is undefined', () => {
expect( expect(
shouldEnableDirectWrapping( shouldEnableDirectWrapping(
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
undefined, undefined,
WETH_CONTRACT_ADDRESS, WETH_CONTRACT_ADDRESS,
), ),
@ -542,7 +533,7 @@ describe('Swaps Util', () => {
it('returns false if a destination token is undefined', () => { it('returns false if a destination token is undefined', () => {
expect( expect(
shouldEnableDirectWrapping(MAINNET_CHAIN_ID, WETH_CONTRACT_ADDRESS), shouldEnableDirectWrapping(CHAIN_IDS.MAINNET, WETH_CONTRACT_ADDRESS),
).toBe(false); ).toBe(false);
}); });
}); });
@ -571,7 +562,7 @@ describe('Swaps Util', () => {
describe('getSwapsTokensReceivedFromTxMeta', () => { describe('getSwapsTokensReceivedFromTxMeta', () => {
const createProps = () => { const createProps = () => {
return { return {
tokenSymbol: ETH_SYMBOL, tokenSymbol: CURRENCY_SYMBOLS.ETH,
txMeta: { txMeta: {
swapMetaData: { swapMetaData: {
token_to_amount: 5, token_to_amount: 5,
@ -586,7 +577,7 @@ describe('Swaps Util', () => {
accountAddress: '0xc011a73ee8576fb46f5e1c5751ca3b9fe0af2a6f', accountAddress: '0xc011a73ee8576fb46f5e1c5751ca3b9fe0af2a6f',
tokenDecimals: 6, tokenDecimals: 6,
approvalTxMeta: null, approvalTxMeta: null,
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
}; };
}; };

@ -2,7 +2,7 @@ import React from 'react';
import { shallow } from 'enzyme'; import { shallow } from 'enzyme';
import { Provider } from 'react-redux'; import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store'; import configureMockStore from 'redux-mock-store';
import { NETWORK_TYPE_RPC } from '../../../../shared/constants/network'; import { NETWORK_TYPES } from '../../../../shared/constants/network';
import { GAS_RECOMMENDATIONS } from '../../../../shared/constants/gas'; import { GAS_RECOMMENDATIONS } from '../../../../shared/constants/gas';
import ViewQuotePriceDifference from './view-quote-price-difference'; import ViewQuotePriceDifference from './view-quote-price-difference';
@ -12,7 +12,7 @@ describe('View Price Quote Difference', () => {
const state = { const state = {
metamask: { metamask: {
tokens: [], tokens: [],
provider: { type: NETWORK_TYPE_RPC, nickname: '', rpcUrl: '' }, provider: { type: NETWORK_TYPES.RPC, nickname: '', rpcUrl: '' },
preferences: { showFiatInTestnets: true }, preferences: { showFiatInTestnets: true },
currentCurrency: 'usd', currentCurrency: 'usd',
conversionRate: 600.0, conversionRate: 600.0,

@ -9,7 +9,7 @@ import { I18nContext } from '../../contexts/i18n';
import { useTokenTracker } from '../../hooks/useTokenTracker'; import { useTokenTracker } from '../../hooks/useTokenTracker';
import { useTokenFiatAmount } from '../../hooks/useTokenFiatAmount'; import { useTokenFiatAmount } from '../../hooks/useTokenFiatAmount';
import { showModal } from '../../store/actions'; import { showModal } from '../../store/actions';
import { NETWORK_TYPE_RPC } from '../../../shared/constants/network'; import { NETWORK_TYPES } from '../../../shared/constants/network';
import { ASSET_ROUTE, DEFAULT_ROUTE } from '../../helpers/constants/routes'; import { ASSET_ROUTE, DEFAULT_ROUTE } from '../../helpers/constants/routes';
import Tooltip from '../../components/ui/tooltip'; import Tooltip from '../../components/ui/tooltip';
import Button from '../../components/ui/button'; import Button from '../../components/ui/button';
@ -175,7 +175,7 @@ export default function TokenDetailsPage() {
marginTop={0} marginTop={0}
color={COLORS.TEXT_DEFAULT} color={COLORS.TEXT_DEFAULT}
> >
{networkType === NETWORK_TYPE_RPC {networkType === NETWORK_TYPES.RPC
? networkNickname ?? t('privateNetwork') ? networkNickname ?? t('privateNetwork')
: t(networkType)} : t(networkType)}
</Typography> </Typography>

@ -1,8 +1,4 @@
import { import { CHAIN_IDS, NETWORK_IDS } from '../../shared/constants/network';
KOVAN_CHAIN_ID,
KOVAN_NETWORK_ID,
MAINNET_CHAIN_ID,
} from '../../shared/constants/network';
import { TRANSACTION_TYPES } from '../../shared/constants/transaction'; import { TRANSACTION_TYPES } from '../../shared/constants/transaction';
import { import {
unconfirmedTransactionsCountSelector, unconfirmedTransactionsCountSelector,
@ -26,18 +22,18 @@ describe('Confirm Transaction Selector', () => {
metamask: { metamask: {
unapprovedTxs: { unapprovedTxs: {
1: { 1: {
metamaskNetworkId: KOVAN_NETWORK_ID, metamaskNetworkId: NETWORK_IDS.KOVAN,
}, },
2: { 2: {
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
}, },
}, },
unapprovedMsgCount: 1, unapprovedMsgCount: 1,
unapprovedPersonalMsgCount: 1, unapprovedPersonalMsgCount: 1,
unapprovedTypedMessagesCount: 1, unapprovedTypedMessagesCount: 1,
network: KOVAN_NETWORK_ID, network: NETWORK_IDS.KOVAN,
provider: { provider: {
chainId: KOVAN_CHAIN_ID, chainId: CHAIN_IDS.KOVAN,
}, },
}, },
}; };

@ -1,5 +1,5 @@
import { head, last } from 'lodash'; import { head, last } from 'lodash';
import { MAINNET_CHAIN_ID } from '../../shared/constants/network'; import { CHAIN_IDS } from '../../shared/constants/network';
import { import {
TRANSACTION_STATUSES, TRANSACTION_STATUSES,
TRANSACTION_TYPES, TRANSACTION_TYPES,
@ -76,7 +76,7 @@ const getStateTree = ({
metamask: { metamask: {
provider: { provider: {
nickname: 'mainnet', nickname: 'mainnet',
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
}, },
unapprovedMsgs, unapprovedMsgs,
selectedAddress: SENDERS.ONE, selectedAddress: SENDERS.ONE,

@ -1,4 +1,4 @@
import { KOVAN_CHAIN_ID } from '../../shared/constants/network'; import { CHAIN_IDS } from '../../shared/constants/network';
import { import {
getConnectedSubjectsForSelectedAddress, getConnectedSubjectsForSelectedAddress,
getLastConnectedInfo, getLastConnectedInfo,
@ -150,7 +150,7 @@ describe('selectors', () => {
}, },
metamask: { metamask: {
provider: { provider: {
chainId: KOVAN_CHAIN_ID, chainId: CHAIN_IDS.KOVAN,
}, },
accounts: { accounts: {
'0x7250739de134d33ec7ab1ee592711e15098c9d2d': { '0x7250739de134d33ec7ab1ee592711e15098c9d2d': {

@ -4,21 +4,16 @@ import { memoize } from 'lodash';
///: END:ONLY_INCLUDE_IN ///: END:ONLY_INCLUDE_IN
import { addHexPrefix } from '../../app/scripts/lib/util'; import { addHexPrefix } from '../../app/scripts/lib/util';
import { import {
MAINNET_CHAIN_ID,
TEST_CHAINS, TEST_CHAINS,
NETWORK_TYPE_RPC,
NATIVE_CURRENCY_TOKEN_IMAGE_MAP, NATIVE_CURRENCY_TOKEN_IMAGE_MAP,
OPTIMISM_CHAIN_ID,
OPTIMISM_TESTNET_CHAIN_ID,
BUYABLE_CHAINS_MAP, BUYABLE_CHAINS_MAP,
MAINNET_DISPLAY_NAME, MAINNET_DISPLAY_NAME,
BSC_CHAIN_ID,
POLYGON_CHAIN_ID,
AVALANCHE_CHAIN_ID,
BSC_DISPLAY_NAME, BSC_DISPLAY_NAME,
POLYGON_DISPLAY_NAME, POLYGON_DISPLAY_NAME,
AVALANCHE_DISPLAY_NAME, AVALANCHE_DISPLAY_NAME,
CHAIN_ID_TO_RPC_URL_MAP, CHAIN_ID_TO_RPC_URL_MAP,
CHAIN_IDS,
NETWORK_TYPES,
} from '../../shared/constants/network'; } from '../../shared/constants/network';
import { import {
KEYRING_TYPES, KEYRING_TYPES,
@ -99,7 +94,7 @@ export function getNetworkIdentifier(state) {
export function getMetricsNetworkIdentifier(state) { export function getMetricsNetworkIdentifier(state) {
const { provider } = state.metamask; const { provider } = state.metamask;
return provider.type === NETWORK_TYPE_RPC ? provider.rpcUrl : provider.type; return provider.type === NETWORK_TYPES.RPC ? provider.rpcUrl : provider.type;
} }
export function getCurrentChainId(state) { export function getCurrentChainId(state) {
@ -525,7 +520,7 @@ export function getSuggestedAssets(state) {
export function getIsMainnet(state) { export function getIsMainnet(state) {
const chainId = getCurrentChainId(state); const chainId = getCurrentChainId(state);
return chainId === MAINNET_CHAIN_ID; return chainId === CHAIN_IDS.MAINNET;
} }
export function getIsTestnet(state) { export function getIsTestnet(state) {
@ -986,8 +981,8 @@ export function getFrequentRpcListDetail(state) {
export function getIsOptimism(state) { export function getIsOptimism(state) {
return ( return (
getCurrentChainId(state) === OPTIMISM_CHAIN_ID || getCurrentChainId(state) === CHAIN_IDS.OPTIMISM ||
getCurrentChainId(state) === OPTIMISM_TESTNET_CHAIN_ID getCurrentChainId(state) === CHAIN_IDS.OPTIMISM_TESTNET
); );
} }
@ -1034,13 +1029,13 @@ export function getIsAdvancedGasFeeDefault(state) {
export const getTokenDetectionSupportNetworkByChainId = (state) => { export const getTokenDetectionSupportNetworkByChainId = (state) => {
const chainId = getCurrentChainId(state); const chainId = getCurrentChainId(state);
switch (chainId) { switch (chainId) {
case MAINNET_CHAIN_ID: case CHAIN_IDS.MAINNET:
return MAINNET_DISPLAY_NAME; return MAINNET_DISPLAY_NAME;
case BSC_CHAIN_ID: case CHAIN_IDS.BSC:
return BSC_DISPLAY_NAME; return BSC_DISPLAY_NAME;
case POLYGON_CHAIN_ID: case CHAIN_IDS.POLYGON:
return POLYGON_DISPLAY_NAME; return POLYGON_DISPLAY_NAME;
case AVALANCHE_CHAIN_ID: case CHAIN_IDS.AVALANCHE:
return AVALANCHE_DISPLAY_NAME; return AVALANCHE_DISPLAY_NAME;
default: default:
return ''; return '';
@ -1056,10 +1051,10 @@ export const getTokenDetectionSupportNetworkByChainId = (state) => {
export function getIsDynamicTokenListAvailable(state) { export function getIsDynamicTokenListAvailable(state) {
const chainId = getCurrentChainId(state); const chainId = getCurrentChainId(state);
return [ return [
MAINNET_CHAIN_ID, CHAIN_IDS.MAINNET,
BSC_CHAIN_ID, CHAIN_IDS.BSC,
POLYGON_CHAIN_ID, CHAIN_IDS.POLYGON,
AVALANCHE_CHAIN_ID, CHAIN_IDS.AVALANCHE,
].includes(chainId); ].includes(chainId);
} }

@ -1,7 +1,4 @@
import { import { CHAIN_IDS } from '../../shared/constants/network';
KOVAN_CHAIN_ID,
MAINNET_CHAIN_ID,
} from '../../shared/constants/network';
import { TRANSACTION_STATUSES } from '../../shared/constants/transaction'; import { TRANSACTION_STATUSES } from '../../shared/constants/transaction';
import { import {
unapprovedMessagesSelector, unapprovedMessagesSelector,
@ -33,7 +30,7 @@ describe('Transaction Selectors', () => {
1: msg, 1: msg,
}, },
provider: { provider: {
chainId: KOVAN_CHAIN_ID, chainId: CHAIN_IDS.KOVAN,
}, },
}, },
}; };
@ -63,7 +60,7 @@ describe('Transaction Selectors', () => {
1: msg, 1: msg,
}, },
provider: { provider: {
chainId: KOVAN_CHAIN_ID, chainId: CHAIN_IDS.KOVAN,
}, },
}, },
}; };
@ -94,7 +91,7 @@ describe('Transaction Selectors', () => {
1: msg, 1: msg,
}, },
provider: { provider: {
chainId: KOVAN_CHAIN_ID, chainId: CHAIN_IDS.KOVAN,
}, },
}, },
}; };
@ -112,7 +109,7 @@ describe('Transaction Selectors', () => {
metamask: { metamask: {
provider: { provider: {
nickname: 'mainnet', nickname: 'mainnet',
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
}, },
featureFlags: { featureFlags: {
showIncomingTransactions: false, showIncomingTransactions: false,
@ -176,7 +173,7 @@ describe('Transaction Selectors', () => {
metamask: { metamask: {
provider: { provider: {
nickname: 'mainnet', nickname: 'mainnet',
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
}, },
selectedAddress: '0xAddress', selectedAddress: '0xAddress',
featureFlags: { featureFlags: {
@ -260,7 +257,7 @@ describe('Transaction Selectors', () => {
metamask: { metamask: {
provider: { provider: {
nickname: 'mainnet', nickname: 'mainnet',
chainId: MAINNET_CHAIN_ID, chainId: CHAIN_IDS.MAINNET,
}, },
selectedAddress: '0xAddress', selectedAddress: '0xAddress',
featureFlags: { featureFlags: {

@ -1,6 +1,6 @@
import freeze from 'deep-freeze-strict'; import freeze from 'deep-freeze-strict';
import reducers from '../ducks'; import reducers from '../ducks';
import { NETWORK_TYPE_RPC } from '../../shared/constants/network'; import { NETWORK_TYPES } from '../../shared/constants/network';
import * as actionConstants from './actionConstants'; import * as actionConstants from './actionConstants';
describe('Redux actionConstants', () => { describe('Redux actionConstants', () => {
@ -26,7 +26,7 @@ describe('Redux actionConstants', () => {
}; };
const result = reducers(initialState, action); const result = reducers(initialState, action);
expect(result.metamask.provider.type).toStrictEqual(NETWORK_TYPE_RPC); expect(result.metamask.provider.type).toStrictEqual(NETWORK_TYPES.RPC);
expect(result.metamask.provider.rpcUrl).toStrictEqual('foo'); expect(result.metamask.provider.rpcUrl).toStrictEqual('foo');
}); });
}); });

Loading…
Cancel
Save